You could access the lambda's code object with func_code
, and access the code's local names with co_names
.
>>> f = lambda x: x.method_foo
>>> f.func_code.co_names
('method_foo',)
>>> f.func_code.co_names[0]
'method_foo'
Question
I have a lambda function which is passed to a object and stored as a variable:
f = lambda x: x.method_foo()
I want to determine the name of method called on the variable x
as a string. So I want
method_foo
saved as a string.
Any help appreciated.
Solution
You could access the lambda's code object with func_code
, and access the code's local names with co_names
.
>>> f = lambda x: x.method_foo
>>> f.func_code.co_names
('method_foo',)
>>> f.func_code.co_names[0]
'method_foo'
OTHER TIPS
This is a bit "crazy", but you can use pass a Mock
to f
and get the method that was added to the mock after calling the function:
>>> from mock import Mock
>>> f = lambda x: x.method_foo
>>> m = Mock()
>>> old_methods = dir(m)
>>> f(m)
<Mock name='mock.method_foo' id='4517582608'>
>>> new_methods = dir(m)
>>> next(method for method in new_methods if method not in old_methods)
'method_foo'