tags:

views:

153

answers:

3

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?

+4  A: 

The __module__ attribute of the function tells you what module it came from.

DNS
+2  A: 

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.

Jorenko
+3  A: 

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.

Jason Baker
Exactly what I needed! Thanks!
Geo
Just out of curiosity, why was this voted down? I'd genuinely like to know if there's something wrong with this approach that I'm missing. :-)
Jason Baker