How can a module know the module that imported it?
Ethan Furman
ethan at stoneleaf.us
Wed Nov 11 16:44:06 EST 2009
Aahz wrote:
> In article <hdf63i$cmp$1 at reader1.panix.com>, kj <no.email at please.post> 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
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>
Now, the tricky part is the line
settings.configure.save()
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.
~Ethan~
More information about the Python-list
mailing list