Search code examples
pythonfunctionmoduleintrospectionpython-import

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!


Solution

  • How about

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

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