How can a module know the module that imported it?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Nov 12 08:33:21 EST 2009


On Wed, 11 Nov 2009 13:44:06 -0800, Ethan Furman wrote:

> 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
> settings.py).  In order to be able to do things like add settings to it,
> save the file after changes are made, etc., settings.py will import the
> configuration module, called configure.py.
> 
> A sample might look like this:
> 
> <settings.py>
> import configure
> 
> paths = configure.Item()
> paths.tables = 'c:\\app\\data'
> paths.temp = 'c:\\temp'
> </settings.py>
> 
> And in the main program I would have:
> 
> <some_app.py>
> 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()
> settings.configure.save()
> </some_app.py>
> 
> And of course, at this point settings.py now looks like
> 
> <settings.py>
> import configure
> 
> paths = configure.Item()
> paths.tables = 'c:\\app\\data'
> paths.temp = 'c:\\work\\temp'
> </settings.py>


Self-modifying code?

UNCLEAN!!! UNCLEAN!!!


> Now, the tricky part is the line
> 
> settings.configure.save()
> 
> How will save know which module it's supposed to be re-writing?

In my opinion, the cleanest way is to tell it which module to re-write. 
Or better still, tell it which *file* to write to:

settings.configure.save(settings.__file__)

which is still self-modifying, but at least it doesn't need magic to 
modify itself.




-- 
Steven



More information about the Python-list mailing list