3

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!

2 Answers 2

4

How about

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind that this won't work for methods that are a part of classes.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.