00__00__00
00__00__00

Reputation: 5327

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

Upvotes: 19

Views: 10623

Answers (5)

Smart Manoj
Smart Manoj

Reputation: 5824

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

Upvotes: 26

JobJob
JobJob

Reputation: 4127

How to get the source filename where the function is defined ... ?

import inspect
inspect.getfile(func)

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

To get the class of a method (i.e. when the function is an attribute of a object):

if inspect.ismethod(func):
    the_class = func.__self__.__class__

ref: https://docs.python.org/3/library/inspect.html

Upvotes: 11

AlexShein
AlexShein

Reputation: 186

You can use __file__ variable.

print(__file__)

Upvotes: 0

Moberg
Moberg

Reputation: 5493

As stated here https://docs.python.org/3/library/inspect.html func.__globals__ returns the global namespace where the function was defined.

Upvotes: 2

Ran Sasportas
Ran Sasportas

Reputation: 2266

For getting the filename just use -

print(os.path.basename(__file__))

if you want the full file path you can just use

print __file__

Upvotes: 1

Related Questions