Is there any way of finding which file contains a specific function? I'm using many modules in an application and I would like to see what file contains them. How could I do this?
The __module__
attribute of the function tells you what module it came from.
In order to avoid having this problem, you should avoid using from module import *
. Instead, either import only the particular symbols you need (from module import function
), or access them as members of the module (import module
, then module.function()
).
This will make it much more obvious where everything is coming from just by looking at the calling source.
Here's one way. I made a file test.py:
def foo():
pass
Then from the interactive interpreter:
>>> from test import foo
>>> foo.func_globals['__file__']
'test.py'
Of course, this doesn't seem to work on any compiled C modules, so be prepared to catch an AttributeError (since a C function won't have a func_globals attribute).
Also note that I haven't tested this out in any non-trivial program, so use it at your own risk! One potential problem area that I see is that accessing __
file__
in this manner may cause setuptools wonkiness, so you might want to set the zip-safe flag to false if you're using setuptools.