Skip to content Skip to sidebar Skip to footer

What Does "_" Mean In Lambda Function And Why Is It Used?

I have an anonymous function with '_' as parameters, I don't know what it means and why it is used here. and function is: f = lambda _: model.loss(X, y)[0] grad_num = eval_numerica

Solution 1:

It's a convention in Python to use _ for variables that are not going to be used later. There is no black magic involved and it is an ordinary variable name that behaves exactly as you'd expect.

In this case it is used because f is passed as a callback which will be passed an argument when it is called (fxph = f(x)).

If f would have been implemented as

f = lambda: model.loss(X, y)[0]

then a TypeError: <lambda>() takes 0 positional arguments but 1 was given error will be raised.

Solution 2:

In your case, it's a convention, telling that the lambda parameter is not used (the answer from DeepSpace explain why).

General use:

You can use _ when you have to get a value but you do not use it. It is a python convention, developers use it to make their code more readable to other developers. With _, you say that you are aware that the variable is not used. Some IDE like PyCharm warn you if you don't:

def test(s):
    print("foobar")


if __name__ == '__main__':
    test("barfoo")

Will result of a warning in Pycharm for example:

warning

But not with _:

def test(_):
    print("foobar")


if __name__ == '__main__':
    test("barfoo")

Result no warning:

no warning

Post a Comment for "What Does "_" Mean In Lambda Function And Why Is It Used?"