Re: Enthought-Dev Digest, Vol 103, Issue 39

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Re: Enthought-Dev Digest, Vol 103, Issue 39

> On Sun, Mar 24, 2013 at 3:51 PM, Des.P <[hidden email]> wrote:
>> I did a test of this:
>> class Person(HasTraits):
>>    owns = Instance('House')
>>    def _owns_changed(self, old, new):
>>        if old is not None and old is not Undefined:
>>            old.owned_by = None
>>        if new is not None and new is not Undefined:
>>            new.owned_by = self
>> And it seems that the _owns_changed has to be part of the class definition itself for Traits to propagate changes i.e. I cannot later dynamically add it to the class Person with something like:
>>        Person._owns_changed = types.MethodType(_owns_changed, None, Person)
>> Can you confirm that Traits requires _x_changed methods to be in the original class definition itself?
> Yes, they are analyzed and hooked up by the metaclass underneath
> HasTraits on class construction time. Why do you want to add it to the
> class after the class has been defined?

Good question. My actual goal is to be able to use something roughly like this:
class Person(HasTraits):
  owns = Instance('House', inverse="owned_by")

and then auto-generate supporting methods based on 'owns'-inverse-'owned_by':
  def _owns_changed(self, old, new): ....

and add such methods to both Person & House as appropriate, to correctly maintain inverse relations in my models. I use such inverse relations a lot, and the code for
is identical everywhere (with a variant for 1-1, 1-N, and N-M relations).

Any hooks in Traits I could utilize? Or any alternative approaches I should consider?


Enthought-Dev mailing list
[hidden email]