traitlets icon indicating copy to clipboard operation
traitlets copied to clipboard

copy(HasTraits) creates a clone with shared state from the original

Open ankostis opened this issue 7 years ago • 2 comments

Actually the results of using copy() on a Hastrait with borged trait values:

from copy import copy

class C(HasTraits):
    a = Int()

c = C(a=1)
copy(c).a = 2
assert c.a == 1  # This FAILS because it is also 2!

Suggested solution

I guess we need this line:

        d['_trait_values'] = self._trait_values.copy()

in HasTraits.__getstate__(): https://github.com/ipython/traitlets/blob/3164ffb43167e9d1688046fbe0aefa424af5b58d/traitlets/traitlets.py#L1084-L1091

And i'm wondering whether the lock must no be shared, either:

        d['_cross_validation_lock'] = False

ankostis avatar Mar 21 '18 17:03 ankostis

Also related to #94.

ankostis avatar Mar 21 '18 17:03 ankostis

@ankostis I think you're right about setting _cross_validation_lock to False.

The only way _cross_validation_lock would be True is if the object were copied inside a hold_trait_notifications context, in which case the copied object would never have the lock reverted back to False (since that would only happen to the original). So yes, we definitely should not be sharing that.

rmorshea avatar Mar 21 '18 23:03 rmorshea