enthought / enthought/traits

confusing behavior with `depends_on` kwarg

Open
#274 0 comments 0 reactions 0 assignees View on GitHub
type: bug
Dominant language
Python
Stars
462
Forks
90
PR merge metrics
No merged PRs in 30d

Description

When using `Property`, the `depends_on` kw can be set to a string or a list. In the case where we set its value to one value, it's behavior changes based on a confusing way we handle these two cases. The code below shows a case where when a string is used the property gets updated when items change as well as the list itself, while in the second case, the property does not update when the items change.

```
from traits.api import HasPrivateTraits, List, Int,\
Property, cached_property

class TestScores ( HasPrivateTraits ):

scores = List( Int )
average = Property( depends_on = 'scores' )

@cached_property
def _get_average ( self ):
s = self.scores
return (float( reduce( lambda n1, n2: n1 + n2, s, 0 ) )
/ len( s ))

class TestScoresList ( HasPrivateTraits ):

scores = List( Int )
average = Property( depends_on = ['scores'] )

@cached_property
def _get_average ( self ):
s = self.scores
return (float( reduce( lambda n1, n2: n1 + n2, s, 0 ) )
/ len( s ))

if __name__ == '__main__':

t = TestScores(scores = [1,2,3])
print t.scores, t.average
t.scores[2] = -100
print t.scores, t.average

t2 = TestScoresList(scores=[1,2,3])
print t2.scores, t2.average
t2.scores[2] = -100
print t2.scores, t2.average
```

The root of the behavior comes from these lines in the `has_traits.py` file:

```
if isinstance( depends_on, SequenceTypes ):
depends_on = ','.join( depends_on )
else:
# Note: We add the leading blank to force it to be treated
# as using the extended trait notation so that it will
# automatically add '_items' listeners to lists/dicts:
depends_on = ' ' + depends_on
```

This should probably be changed so that both cases end up with the same behavior

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.