问题描述
请考虑以下两个功能:
def f1():
return "potato"
f2 = lambda: "potato"
f2.__name__ = f2.__qualname__ = "f2"
简短地对原始源代码进行内省,是否有任何方法可以检测到f1
是def而f2
是lambda?
Short of introspecting the original source code, is there any way to detect that f1
was a def and f2
was a lambda?
>>> black_magic(f1)
"def"
>>> black_magic(f2)
"lambda"
推荐答案
您可以检查代码对象的名称.与函数名称不同,不能重新分配代码对象的名称. Lambda的代码对象的名称仍为'<lambda>'
:
You could check the code object's name. Unlike the function's name, the code object's name cannot be reassigned. A lambda's code object's name will still be '<lambda>'
:
>>> x = lambda: 5
>>> x.__name__ = 'foo'
>>> x.__name__
'foo'
>>> x.__code__.co_name
'<lambda>'
>>> x.__code__.co_name = 'foo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
def
语句无法定义其代码对象名称为'<lambda>'
的函数.创建后可以 替换函数的代码对象,但是这样做很少见,而且很怪异,以至于可能不值得处理.同样,这将无法处理通过手动调用types.FunctionType
或types.CodeType
创建的函数或代码对象.我看不到任何处理__code__
重新分配或手动创建的函数和代码对象的好方法.
It is impossible for a def
statement to define a function whose code object's name is '<lambda>'
. It is possible to replace a function's code object after creation, but doing so is rare and weird enough that it's probably not worth handling. Similarly, this won't handle functions or code objects created by manually calling types.FunctionType
or types.CodeType
. I don't see any good way to handle __code__
reassignment or manually-created functions and code objects.
这篇关于有什么办法可以判断一个函数对象是lambda还是def?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!