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.

有帮助吗?

解决方案

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'

其他提示

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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top