Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey patch to raise AttributeError on attempted use of a particular attribute of an object

Tags:

python

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?

like image 223
B Robster Avatar asked Oct 07 '22 01:10

B Robster


1 Answers

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
like image 103
Michael Merickel Avatar answered Oct 10 '22 01:10

Michael Merickel