a module who knows its caller

Jeff Epler jepler at unpythonic.net
Fri Apr 11 12:27:10 EDT 2003


On Fri, Apr 11, 2003 at 09:12:35AM -0700, Michele Simionato wrote:
> I have a module (say m.py) that can be called by different scripts (say a.py 
> and b.py). I want m.py to be able to tell if it has been called by a.py or
> by b.py.

this is the sort of thing you abuse sys._getframe() for.

# a.py and b.py
import m

# m.py
import sys
try:
	f = sys._getframe(1)
except ValueError:
	print "not imported by anyone"
else:
	print "imported from file", f.f_code.co_filename
	# could use f_globals['__name__'] but this doesn't exist
	# when the importer is __main__
	print "imported from module", f.f_globals['__name__']


now, several ways to cause m to be imported:
[jepler at parrot cb]$ python -c 'import a'
imported from file a.py
imported from module a
[jepler at parrot cb]$ python a.py
imported from file a.py
imported from module __main__
[jepler at parrot cb]$ python -c 'import m'
imported from file <string>
imported from module __main__
[jepler at parrot cb]$ python m.py
not imported by anyone
[jepler at parrot cb]$ python -c 'import a; import b'
imported from file a.py
imported from module a

Notice that when m is imported twice (once from a and once from b), only
one message is printed.  That's a sign that this kind of perversity will
ultimately do you wrong.

Jeff





More information about the Python-list mailing list