Import Replacement

Gary Herron gherron at
Sat Jan 31 21:22:54 CET 2009

James Pruitt wrote:
> Imagine there are two files and is
> imported by another file Is it possible to make it so that
> under certain circumstances possibly based on an environment variable
> or something similar that when imports, it actually
> imports sort of like a behind the scenes replacement so
> that needs little, preferably absolutely no modification?
> Right now, I am investigating the use of sys.modules and doing
> something using sys.modules[''] = ''.
> ------------------------------------------------------------------------
> --

If horse and buffalo have the same interface then try something like this:

if ...:
  import horse as ridable
  import buffalo as ridable
# Now use ridable as any module...

If each defines a class of its own name, but the classes have identical
interfaces, then try

if ...:
  from horse import Horse as Ridable
  from buffalo import Buffalo as Ridable
# Then instantiate
animal = Ridable(...)

Gary Herron

More information about the Python-list mailing list