How can a module know the module that imported it?

Ethan Furman ethan at
Wed Nov 11 22:44:06 CET 2009

Aahz wrote:
> In article <hdf63i$cmp$1 at>, kj  < at> wrote:
>>The subject line says it all.
> You are probably trying to remove a screw with a hammer -- why don't you
> tell us what you really want to do and we'll come up with a Pythonic
> solution?

Well, I don't know what kj is trying to do, but my project is another 
(!) configuration program.  (Don't worry, I won't release it... unless 
somebody is interested, of course !)

So here's the idea so far:
The configuration data is stored in a python module (call it  In order to be able to do things like add settings to it, 
save the file after changes are made, etc., will import the 
configuration module, called

A sample might look like this:

import configure

paths = configure.Item()
paths.tables = 'c:\\app\\data'
paths.temp = 'c:\\temp'

And in the main program I would have:

import settings

main_table = dbf.Table('%s\\main' % paths.tables)

# user can modify path locations, and does, so update
# we'll say it changes to \work\temp

settings.paths.temp = user_setting()

And of course, at this point now looks like

import configure

paths = configure.Item()
paths.tables = 'c:\\app\\data'
paths.temp = 'c:\\work\\temp'

Now, the tricky part is the line

How will save know which module it's supposed to be re-writing?  The 
solution that I have for now is

def _get_module():
     "get the calling module -- should be the config'ed module"
     target = os.path.splitext(inspect.stack()[2][1])[0]
     target = __import__(target)
     return target

If there's a better way, I'd love to know about it!

Oh, and I'm using 2.5.4, but I suspect kj is using 2.6.


More information about the Python-list mailing list