Question

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!

Was it helpful?

Solution

How about

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

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top