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

后端 未结 3 1403
感动是毒
感动是毒 2021-01-12 10:56

Consider the two functions below:

def f1():
    return \"potato\"

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

Short of

3条回答
  •  渐次进展
    2021-01-12 11:23

    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 '':

    >>> x = lambda: 5
    >>> x.__name__ = 'foo'
    >>> x.__name__
    'foo'
    >>> x.__code__.co_name
    ''
    >>> x.__code__.co_name = 'foo'
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: readonly attribute
    

    It is impossible for a def statement to define a function whose code object's name is ''. 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.

提交回复
热议问题