python中的匿名内联函数
fonc的Python项目详细描述
方舟子
<;small>;python中的多行内联匿名函数<;/small>
>>>fromfoncimportfonc>>>[...fonc("""... def x(input): # doesn't matter what this function is called... value = input * 3.14... return int(value)... """)(value)forvaluein[1,2,3,4]...][3,6,9,12]
你为什么要做这种可怕的事
:):):):):):):):):):):):):)
这会污染我的全局命名空间吗?在
不!在
想象一下这个内联函数:
>>>fromfoncimportfonc>>>[...fonc("""... def x(input): # doesn't matter what this function is called... value = input * 3.14... return int(value)... """)(value)forvaluein[1,2,3,4]...][3,6,9,12]
可以想象这意味着x
函数名被覆盖到全局命名空间中。不是的!在
>>>x(1)
NameError: name 'x' is not defined
请问这是怎么回事?在
- 解析字符串并确定定义函数的名称
- 将其替换为已知的随机值
- 将对该内联函数的调用替换为对重命名函数的调用
从不问问题
- 在
我可以访问这个函数中的全局变量吗?在
是吗
在 - 在
我可以在生产中使用这个吗?在
你绝对不是傻瓜
在
- 项目
标签: