Parametrized module import
Oliver Fromme
olli at haluter.fromme.com
Thu Jul 8 08:27:05 EDT 2004
Heather Coppersmith <me at privacy.net> wrote:
> Jacek Generowicz <jacek.generowicz at cern.ch> wrote:
> > Oliver Fromme <olli at haluter.fromme.com> writes:
> > > You could create another module called "config" or "cfg" which
> > > contains some global variables. You import it into your
> > > configurable module as well as into your main program. Then
> > > you can configure the module's behaviour via those global
> > > variables before importing the module.
> >
> > Yes, my initial crappy prototype idea was to add configuration
> > information to the sys module, but this variation is much neater
> > ... in fact, after the first 2 minutes of thinking about it, it
> > looks perfect :-)
> >
> > However, one thing which keeps bothering me about the whole
> > business, is the possibilty of importing the module (with your
> > chosen configuration) after it has already been imported,
> > without you knowing it, with a different configuration. Ideally
> > there should be some warning about the fact that the
> > configuration you specified is being ignored as a result of the
> > module already being imported ... and I don't see how to achieve
> > this.
>
> Upon import, a module's "top level" code is executed, so try a
> variation on this theme at the top level of your module:
It's only executed when the module is imported for the
_first_ time, so that wouldn't work.
However, the problem can be solved by not modifying a
global variable in the "config" module directly, but by
using a function which allows only one call.
#--- File config.py: ---
foo_interface_mode = None
def set_foo_interface_mode (mode):
if foo_interface_mode is None:
foo_interface_mode = mode
else:
raise "foo_interface_mode may only be set once"
#--- File your_module.py: ---
import config
if config.foo_interface_mode is None:
raise "foo_interface_mode has not been set"
elif config.foo_interface_mode == 0:
... this interface
else:
... that interface
#--- File main_program.py: ---
import config
config.set_foo_interface_mode (1)
import your_module
Of course, you could use assert instead of raise, or just
print a warning and go on. Whatever you prefer.
Best regards
Oliver
--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany
``All that we see or seem is just a dream within a dream.''
(E. A. Poe)
More information about the Python-list
mailing list