Python: Some "__magic__" Attribute To Reference A Function From Within That Function
Is there an analog of PHP's __FUNCTION__ magic constant in Python? def func(x): print(__FUNCTION__) ## print(__FUNCTION__.__name__) ##
Solution 1:
You can get some of this functionality using the inspect module.
import inspect
def foo():
code = inspect.currentframe().f_code
print code.co_name
You could also execute the code from the code object using exec code
where code
is the variable created in the function above.
Note that inspect.currentframe()
gives you the same object as sys._getframe(0)
, but it is actually meant to be used this way.
Solution 2:
There isn't any such functionality in Python.
You could abuse the sys._getframe()
function to get access to the current code object though:
import sys
deffoo():
print sys._getframe(0).f_code.co_name
but that will only print the name of the function as it was defined originally. If you assign the foo
function to another identifier, the above code will continue to print foo
:
>>>bar = foo>>>bar()
'foo'
Solution 3:
Is this what you are after?
In[97]: defa():
...: printsys._getframe().f_code.co_name
...:
In[98]: a()
a
Post a Comment for "Python: Some "__magic__" Attribute To Reference A Function From Within That Function"