Replacing a package with another

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Jan 27 20:15:45 CET 2008


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

> 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:

=== a.py ===
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

=== path_a.py ===
import a

def foo():
   print "other foo"

print "patching a.foo",
a.foo = foo
print a.foo

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

=== main.py ===
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 a.foo:"
a.foo()
print "calling a.tax(100.0):"
a.tax(100.0)

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

-- 
Gabriel Genellina




More information about the Python-list mailing list