How can a module know the module that imported it?

Ethan Furman ethan at stoneleaf.us
Thu Nov 12 13:10:53 EST 2009


AK Eric wrote:
> so:
> 
> # moduleA.py
> import moduleB
> 
> # moduleB.py
> import sys
> stuff = sys._getframe(1).f_locals
> print stuff
> 
> Prints:
> 
> {'__builtins__': <module '__builtin__' (built-in)>,
> '__file__': 'C:\\Documents and Settings\\<userName>\\My Documents\
> \python\\moduleA.py',
> '__name__': '__main__',
> '__doc__': None}
> 
> Looks like you could query stuff['__file__'] to pull what you're
> after.
> ?

The leading _ in _getframe indicates a private function to sys (aka 
implementation detail); in other words, something that could easily 
change between one Python version and the next.

I'm using the inspect module (for the moment, at least), and my question 
boils down to:  Will it work correctly on all versions of Python in the 
2.x range?  3.x range?

~Ethan~



More information about the Python-list mailing list