How can a module know the module that imported it?

AK Eric warpcat at sbcglobal.net
Thu Nov 12 19:35:55 CET 2009


On Nov 12, 10:10 am, Ethan Furman <et... at stoneleaf.us> wrote:
> 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?
>

Good point, I totally missed that.  Someone had passed that solution
to me at one point and I was so excited I kind of looked that over :P



More information about the Python-list mailing list