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>
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. lambda
s 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).
Work around:
Using the inspect module you can do this:
from inspect import getsource
get_lambda_name = lambda l: getsource(l).split('=')[0].strip()
print(get_lambda_name(get_lambda_name))
# result: get_lambda_name
This way you obtain the source code and extract the "anonymous" name. Note: this doesn't work in Idle command line.
The Lambda function name is always available as in environment variable, so should be accessible as:
os.environ['AWS_LAMBDA_FUNCTION_NAME']
https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With