2

Is there an analog of PHP's __FUNCTION__ magic constant in Python?

def func(x):
    print(__FUNCTION__)  ## <function func at 0x00B02810>
    print(__FUNCTION__.__name__)  ## func

UPD:

To have an example:

import sys

def func(f = "Foo"):
    b = "Bar"
    print(sys._getframe().f_code) ## <code object func at 0x00B09A20, file "C:\py\func.py", line 5>
    print(func.__code__) ## <code object func at 0x00B09A20, file "C:\py\func.py", line 5>, the same

    print(sys._getframe().f_trace) ## None
    print(sys._getframe().f_locals) ## {'b': 'Bar', 'f': 'Foo'}
    print(sys._getframe().f_lineno) ## 12

if __name__ == "__main__":
    func()
Green
  • 28,742
  • 61
  • 158
  • 247
  • Out of interest, why do you want to do this? – Gareth Latty Feb 20 '13 at 18:32
  • @Lattyware, in PHP I often used `__FUNCTION__`, `__METHOD__`, `__CLASS__` to create smth like flags to see in which component smth happened. As now I learn Python and have been testing function decorators I wanted to use the same technic to see what function have been called. – Green Feb 20 '13 at 18:53

3 Answers3

3

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
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

def foo():
    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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • +1 Is there something equivalent to get the name of an instance ? – eyquem Feb 20 '13 at 19:01
  • @eyquem: That is much harder; you can introspect the code object of the current frame for a first argument to the function that happens to be a custom class instance (if it is called `self` so much the better). This is not failproof however. – Martijn Pieters Feb 20 '13 at 19:35
  • Thank you. I will explore these possibilities some day – eyquem Feb 20 '13 at 19:57
2

Is this what you are after?

In [97]: def a():
    ...:     print sys._getframe().f_code.co_name
    ...:     

In [98]: a()
a

Source

Community
  • 1
  • 1
mbatchkarov
  • 15,487
  • 9
  • 60
  • 79