In Python EPD Traits I can keep variables that depend on others up to date either with a property or with actions in the method that takes care of changes of the ‘master’ variable.
I show here both ways, first with a Property:
from traits.api import HasTraits, Int, Property
class MyClass(HasTraits):
val = Int
dependent = Property(depends_on = 'val')
def _get_dependent(self):
return 4*self.val
and now with a trait handler:
from traits.api import HasTraits, Int
class MyClass(HasTraits):
val = Int
dependent = Int
def _val_changed(self):
self.dependent = 4*self.val
My question is, when should I use what? While researching this, I realized that one difference is that in the case of using a Property, the ‘dependent’ variable becomes read-only, if set up like here. But let’s say, the dependent is really dependent and I never have enough knowledge to set it directly, is there still a difference that I should be aware of?
Edit: This is similar to my other Traits related question, but not directly related.
In this case I would definitely use a property, because
dependentis in fact not holding any useful state you need to keep, you just need to access it.The second variant could also easily explode into your face in some cases. Imagine you have many more dependencies and you will need to add more in future. Every time you add a new member depending on
val, you have to go to_val_changedand let you new member know. On the other hand, if you create you new member as a property readingval, it’s separate from the rest and you don’t mess you code more every time you add a dependency.