E731 do not assign a lambda expression, use a def

前端 未结 4 1118
忘掉有多难
忘掉有多难 2020-11-27 02:18

I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?

4条回答
  •  孤城傲影
    2020-11-27 02:58

    Here is the story, I had a simple lambda function which I was using twice.

    a = map(lambda x : x + offset, simple_list)
    b = map(lambda x : x + offset, another_simple_list)
    

    This is just for the representation, I have faced couple of different versions of this.

    Now, to keep things DRY, I start to reuse this common lambda.

    f = lambda x : x + offset
    a = map(f, simple_list)
    b = map(f, another_simple_list)
    

    At this point my code quality checker complains about lambda being a named function so I convert it into a function.

    def f(x):
        return x + offset
    a = map(f, simple_list)
    b = map(f, another_simple_list)
    

    Now the checker complains that a function has to be bounded by one blank line before and after.

    def f(x):
        return x + offset
    
    a = map(f, simple_list)
    b = map(f, another_simple_list)
    

    Here we have now 6 lines of code instead of original 2 lines with no increase in readability and no increase in being pythonic. At this point the code checker complains about the function not having docstrings.

    In my opinion this rule better be avoided and broken when it makes sense, use your judgement.

提交回复
热议问题