Import Replacement

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


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

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

if ...:
  import horse as ridable
else:
  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
else:
  from buffalo import Buffalo as Ridable
# Then instantiate
animal = Ridable(...)



Gary Herron




More information about the Python-list mailing list