Replacing a package with another

Gabriel Genellina gagsl-py2 at
Sun Jan 27 20:15:45 CET 2008

En Sat, 26 Jan 2008 12:10:03 -0200, J. Pablo Fernández <pupeno at>  

> Is it possible to replace one package with another at runtime, that is, I
> have package a.blah which I want instead of b.blah, so I can "inject"
> functionality in an existing package?

It might be done, just assign the replacement functions/classes to the  
existing module.
This has the same warnings as the reload() function: already created  
objects maintain their original behavior, already imported names from  
modules maintain their original value, already bound names to default  
arguments maintain their original value, etc.
So it is best to do it as early as possible, but anyway some effects can't  
be avoided:

=== ===
default_tax_pct = 21
print "in a, default_tax_pct=",default_tax_pct

def foo():
   print "original foo"

def tax(amount, pct=default_tax_pct):
   print amount, pct, amount*pct/100

=== ===
import a

def foo():
   print "other foo"

print "patching", = foo

print "patching a.default_tax_pct",
a.default_tax_pct = 15
print a.default_tax_pct

=== ===
import a
 from a import default_tax_pct
import patch_a

print "in main, a.default_tax_pct", a.default_tax_pct
print "in main, default_tax_pct", default_tax_pct
print "calling"
print "calling"

=== output ===
in a, default_tax_pct= 21
patching <function foo at 0x00A3F0B0>
patching a.default_tax_pct 15
in main, a.default_tax_pct 15
in main, default_tax_pct 21
other foo
100.0 21 21.0

Gabriel Genellina

More information about the Python-list mailing list