I have a class with several methods, some of which are only valid when the object is in a certain state. I would like methods to simply not be bound to objects when they are not in a suitable state, so I get something like:
>>> wiz=Wizard()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.addmana()
>>> dir(wiz)
['__doc__', '__module__', 'addmana', 'domagic']
>>> wiz.domagic()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.domagic()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'
I can see how to add methods (types.MethodType (method, object)), but I see no way to remove a method for only one object:
>>> wiz.domagic
<bound method Wizard.domagic of <__main__.Wizard instance at 0x7f0390d06950>>
>>> del wiz.domagic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'
Overriding __dir__ (and getting an InvalidState or NotEnoughMana exception when called instead of AttributeError for the link) might be fine, but I don't see how to accurately simulate the built-in dir () behavior. (Ideally, I would prefer a method that also works in Python 2.5)
Ideas?