Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Is there any way to tell if a function object was a lambda or a def?

Consider the two functions below:

def f1():
    return "potato"

f2 = lambda: "potato"
f2.__name__ = f2.__qualname__ = "f2"

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...