I have an instance of a python class.
class Fum(object):
foo = Foo()
bar = Bar()
fum = Fum()
For good reasons that I don't want to get into, I want to monkey patch this object so that one of its attributes is off-limits in a certain use case. I'd prefer that if I or another developer down the road tries to use the attribute on the monkey-patched object, a useful exception is raised which explains the situation. I tried to implement this with a property, but am not having luck.
e.g.,
def raiser():
raise AttributeError("Don't use this attribute on this object. Its disabled for X reason.")
fum.bar = property(raiser)
>>> fum.bar
>>> <property object at 0xb0b8b33f>
What am I missing?
You cannot monkeypatch properties directly onto instances of an object. descriptors
are a class-level concept and must be in an instance's class hierarchy. There is a trick that works, however:
class Fum(object):
foo = Foo()
bar = Bar()
fum = Fum()
class DerivedFum(fum.__class__):
bar = property(raiser)
fum.__class__ = DerivedFum
fum.bar # --> raise AttributeError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With