Monkey patching a module on import
-
28-09-2022 - |
سؤال
I've got a package structure like this
mypackage
|-- core.py
|-- device.py
|-- async.py
|-- ...
The core.py
defines a Command
class, which handles the communication with a device.
The communication is synchronous (blocking).
#core.py
class Command(object):
#...
The device module defines a device class, which uses the Command
class to provide an API for a real device, e.g. an oscilloscope.
# device.py
class MyDevice(object):
cmd1 = Command(...)
cmd2 = Command(...)
The async module defines an asyncronous version of Command
.
# async.py
class Command(object):
# asyncronous command implementation
Now what I'd like to to is the following:
# Note: There is no real /mypackage/async/device.py file
import mypackage.async.device
dev = mypackage.async.device.MyDevice(...) # uses asyncronous Command implementation
There are many classes like MyDevice
. I don't wan't to rewrite every one of them just to switch the Command
implementation. That's why I think patching would work quite nice. But it should also be explicit (different import, the user should not know that patching has been done).
Any suggestions how I can achieve this?
لا يوجد حل صحيح
لا تنتمي إلى StackOverflow