Clone a module and make changes to the copy
To phrase another way, can I inherit from a module, and then override or modify parts of it?
Yes.
import module
You can use stuff from module
or override stuff in your script.
You can also do this to create a "derived" module.
Call this "module_2".
from module import *
Which imports everything. You can then use stuff from module
or override stuff in this new module, "module_2".
Other scripts can then do
import module_2
And get all the stuff from module modified by the overrides in module_2.
The namespace of a Python module is writable. Consider:
# contrived.pyCONST = 100def foo(): return CONST
You can modify the value of CONST
after it's been imported:
import contrivedcontrived.CONST = 200contrived.foo() # 200
However, only a single instance of a module can be imported so there is not anyway to create a clone and continue to use the original module. If you don't need access to the original module, then it's fairly straight-forward to create a wrapper module and override whatever you want to change.
One thing to look out for is that code like this will not work as you expect:
# clone.pyfrom contrived import *CONST = 200
This will actually assign CONST
in clone
's namespace, functions imported from contrived
will continue to reference the CONST
in contrive
's namespace:
import cloneclone.foo() # 100
In this case you could do something like this:
# clone.pyimport contrivedcontrived.CONST = 200from contrived import *