Is it possible to Monkey Patch an attribute within a Python class? A quick google for "monkey patching python" returns a ton of results about patching methods
, but no mention of changing fields within a class.
Patching Methods:
- Adding a Method to an Existing Object
- Duck punching a property
- changing methods and attributes at runtime
However, like I said, no mention of changing Class attributes/fields.
To give a somewhat contrived example, let's say I have a class which has a multiprocessing
queue
, and I want to patch it with a threading Queue.Queue
.
import threading
import multiprocessing
class MyClassWithAQueue(object):
def__init__(self):
self.q = multiprocessing.Queue()
Is there a way to patch this? Attempting to simply assign it via the class name before construction appears to do nothing.
if __name__ == '__main__':
MyClassWithAQueue.q = Queue.Queue()
myclass = MyClassWithAQueue()
print myclass.q
# still shows as a multiprocessing queue
>>><multiprocessing.queues.Queue object at 0x10064493>
Is there a way to do this?