Monkey patching a @property
Subclass the base class (Foo
) and change single instance's class to match the new subclass using __class__
attribute:
>>> class Foo:... @property... def bar(self):... return 'Foo.bar'...>>> f = Foo()>>> f.bar'Foo.bar'>>> class _SubFoo(Foo):... bar = 0...>>> f.__class__ = _SubFoo>>> f.bar0>>> f.bar = 42>>> f.bar42
from module import ClassToPatchdef get_foo(self): return 'foo'setattr(ClassToPatch, 'foo', property(get_foo))
To monkey patch a property, there is an even simpler way:
from module import ClassToPatchdef get_foo(self): return 'foo'ClassToPatch.foo = property(get_foo)