PEP 8警告“请勿使用lambda表达式,请使用def".用于defaultdict lambda表达式 [英] PEP 8 warning "Do not use a lambda expression use a def" for a defaultdict lambda expression

查看:75
本文介绍了PEP 8警告“请勿使用lambda表达式,请使用def".用于defaultdict lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的python代码创建字典.但是我收到了 dct_structure 变量的 PEP 8 警告.警告是:请勿使用lambda表达式,请使用def

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'

我对python lambda表达式还不满意.因此,任何人都可以帮助我为以下两行python代码定义函数以避免PEP警告.

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()

推荐答案

Python中的lambda本质上是具有笨拙的受限语法的匿名函数.警告只是说,假设您直接将其分配给变量-因此为lambda命名-您可以使用 def ,它具有更清晰的语法并将函数名称烘焙为函数对象,可以提供更好的诊断.

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.

您可以将代码段重写为

def dct_structure():
    return defaultdict(dct_structure) 

dct = dct_structure() 

这篇关于PEP 8警告“请勿使用lambda表达式,请使用def".用于defaultdict lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆