PEP 8 warning “Do not use a lambda expression use a def” for a defaultdict lambda expression

牧云@^-^@ 提交于 2019-12-13 11:30:01

问题


I am using the below python code to create a dictionary.But I am getting one PEP 8 warning for the dct_structure variable. Warning is: do not use a lambda expression use a def

from collections import defaultdict

dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()
dct['protocol']['tcp'] = 'reliable'
dct['protocol']['udp'] = 'unreliable'

I am not comfortable with python lambda expression yet. So can anyone help me to define the function for the below two line of python code to avoid the PEP warning.

dct_structure = lambda: defaultdict(dct_structure)
dct = dct_structure()

回答1:


A lambda in Python is essentially an anonymous function with awkward restricted syntax; the warning is just saying that, given that you are assigning it straight to a variable - thus giving the lambda a name -, you could just use a def, which has clearer syntax and bakes the function name in the function object, which gives better diagnostics.

You may rewrite your snippet as

def dct_structure():
    return defaultdict(dct_structure) 

dct = dct_structure() 


来源:https://stackoverflow.com/questions/45790269/pep-8-warning-do-not-use-a-lambda-expression-use-a-def-for-a-defaultdict-lambd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!