python – Reference to a function within a function

Question:

In Python , every function is an object. But how then to get a reference to this object inside the function? The function does not see any self inside itself.

Answer:

What's stopping you from using the function name?

>>> def foo():
...    return foo
... 
>>> foo()
<function foo at 0x7f7cd66fba60>
>>> foo
<function foo at 0x7f7cd66fba60>

If the function name is unknown, then it cannot be retrieved. This functionality has been deprecated.

But, as they say, if you really want to, then there are several options. I wouldn't recommend doing this unless you really need to.

Through inspect :

import inspect

def foo():
   print inspect.stack()[0][3]

Via sys :

import sys

def foo():
    print sys._getframe().f_code.co_name

You can get the method, knowing the name of the function, through the globals() function

upd

Attention! According to the documentation , not all python implementations can include sys._getframe . This is a function for internal use of the CPython interpreter and may not work for others. Use at your own risk

Scroll to Top