Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of a function (plus its module) in Python?

Trying to get the full name of a function in Python. this question about function names specifies that the __name__ field should be used to get the function name. However, for this particular case, the full name is needed: the modules that contain it plus the function's name.

The purpose of this is to enable accessing a function through a different program in the same project.

Example:

# file /my/project/funcs.py
def fun_1(a):
    ...

# Looking for a function like this:

def get_fun_name(function):
    ...

>>> get_fun_name(fun_1)
my.project.funcs.fun_1

As you can see, the ideal answer would print out hte modules and the function of the function object that is provided as argument.

Thanks very much! Any help will definitely be appreciated!

like image 606
Juan Carlos Coto Avatar asked Nov 17 '25 16:11

Juan Carlos Coto


2 Answers

How about

def get_fun(fn):
    return '.'.join([fn.__module__, fn.__name__])

(see e.g. http://docs.python.org/2/reference/datamodel.html)

like image 200
jonathanverner Avatar answered Nov 20 '25 06:11

jonathanverner


If you want the name and module, they are available as the __name__ and __module__ attributes. Note that for functions defined within another function or class this will still give you an inaccurate "path". Python 3.3 adds a __qualname__ attribute which includes that information.

like image 26
Nick Olson-Harris Avatar answered Nov 20 '25 05:11

Nick Olson-Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!