3

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.

Community
  • 1
  • 1
K.-Michael Aye
  • 5,465
  • 6
  • 44
  • 56

1 Answers1

2

In this case I would definitely use a property, because dependent is 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_changed and let you new member know. On the other hand, if you create you new member as a property reading val, it's separate from the rest and you don't mess you code more every time you add a dependency.

tchap
  • 1,047
  • 8
  • 10
  • sorry for the delay in acceptance. I must have been so busy working on it at those times... – K.-Michael Aye Oct 24 '12 at 23:36
  • Np. Btw I haven't even recognised my answer after such a long time, I thought that my account was forged or something :D – tchap Oct 26 '12 at 08:35