Is it pythonic: naming lambdas

后端 未结 3 471
我寻月下人不归
我寻月下人不归 2020-11-27 08:18

I\'m beginning to appreciate the value of lambda expressions in python, particularly when it comes to functional programming, map, functions returning functions

3条回答
  •  情深已故
    2020-11-27 08:40

    This is not Pythonic and PEP8 discourages it:

    Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

    Yes:

    def f(x): return 2*x
    

    No:

    f = lambda x: 2*x
    

    The first form means that the name of the resulting function object is specifically 'f' instead of the generic ''. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

    A rule of thumb for this is to think on its definition: lambdas expressions are anonymous functions. If you name it, it isn't anonymous anymore. :)

提交回复
热议问题