Search code examples
pythonfunctionlambda

Get lambda function's name as string


How can I get a lambda function's name?

Using the __name__ property returns <lambda>:

def myfunc():
    pass
myfunc_l = lambda :None

print myfunc.__name__
print myfunc_l.__name__

>>myfunc
>><lambda>

I was expecting myfunc_l but I got <lambda>


Solution

  • Lambdas are anonymous, which means they do not have a name.

    You can always assign a name to __name__ if you feel they should have one anyway:

    myfunc_l = lambda: None
    myfunc_l.__name__ = 'foo'
    

    Note that Python cannot know that you assigned the lambda function object to a specific name; the assignment takes place after the lambda expression was executed. Remember, you don't even have to assign a lambda:

    result = (lambda x: x ** 2)(4)
    

    or you could store the lambda in a list:

    several_lambdas = [lambda y: (y // 2) for y in range(10, 20)]
    

    and in neither context is there a name to assign to these objects.

    Full-blown function definitions on the other hand are statements, not expressions, and the def statement requires that you specify a name. You can never use a def statement without naming the resulting function, which is why Python can assign the name to the object:

    >>> def foo(): pass
    ...
    >>> print foo.__name__
    'foo'
    

    You can still assign foo to something else, delete the foo global reference, rename the function object by assigning to the __name__ attribute, but it won't change the nature of the function. lambdas are the same, really, apart from the fact that there's no context to set the initial name (and the fact that they can only represent a single expression).