pythonfunctionintrospection

determine from which file a function is defined in python


I am programmatically printing out a list of function in python. I can get the name from __name__

for i, func in enumerate(list_of_functions):
    print(str(i) + func.__name__)

How to get the source filename where the function is defined as well?

and in case the function it is attribute of a object, how to get the type of parent object?


portability python2/3 is a must


Solution

  • func.__module__
    

    Will return the module in which it is defined

    func.__globals__['__file__']
    

    will return the whole path of the file where it is defined. Only for user-defined functions