Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get function object inside a function (Python)

I want to have something like

def x():
  print get_def_name()

but not necessarily know the name of x.

Ideally it would return 'x' where x would be the name of the function.

like image 260
user3412497 Avatar asked Sep 26 '26 06:09

user3412497


1 Answers

You can do this by using Python's built-in inspect library.

You can read more of its documentation if you want to handle more complicated cases, but this snippet will work for you:

from inspect import getframeinfo, currentframe

def test_func_name():
    return getframeinfo(currentframe()).function

print(test_func_name())
like image 80
Tushar Vazirani Avatar answered Sep 27 '26 21:09

Tushar Vazirani