PEP 8 warning “Do not use a lambda expression use

2019-09-22 04: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条回答
Melony?
2楼-- · 2019-09-22 04:53

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() 
查看更多
登录 后发表回答