traits icon indicating copy to clipboard operation
traits copied to clipboard

Failed assignment to HasStrictTraits instance modifies the class.

Open mdickinson opened this issue 11 years ago • 3 comments

I encountered the following behaviour while (foolishly) trying to monkeypatch a HasStrictTraits subclass. The fact that the monkeypatching doesn't work isn't really surprising. What is suprising is that the attempt to monkeypatch one instance of the class breaks the class itself.

>>> from traits.api import *
>>> class A(HasStrictTraits):
...     def start(self): print "Starting"
... 
>>> try:
...     A().start = 3.2  # Monkey-patching fails;  too bad.
... except Exception:
...     pass
... 
>>> A().start  # Surprise: the failure above affects new A instances!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'start'

What appears to be happening is that the assignment to A().start creates a new class trait start for A and puts it into the A.__class_traits__ dictionary, before the failure occurs. After the failure, that new class trait still exists.

mdickinson avatar May 17 '13 08:05 mdickinson

It looks like get_prefix_trait in ctraits.c could be the place to fix this. I don't have time to produce a fix right now; I may come back to this later.

mdickinson avatar May 17 '13 09:05 mdickinson

Closely related to #30.

mdickinson avatar Jan 09 '20 14:01 mdickinson

Another team ran into this issue recently: see #1375.

mdickinson avatar Dec 18 '20 16:12 mdickinson