enthought / enthought/traits

Troubles with properties and defaults initializations

Open
#709 5 comments 0 reactions 0 assignees View on GitHub
topic: hastraits initialization
Dominant language
Python
Stars
462
Forks
90
PR merge metrics
No merged PRs in 30d

Description

In the following example, an `AttributeError` is raised complaining that the `foo` attribute is `None` even though the `foo` attribute is supplied at instantiation.

My fuzzy understanding is that the presence of the `Property` attempts to connect some traits listener that attempts to access `foo` before `foo` itself is attached to the `Baz` instance.

This is possible to workaround by removing the `Property` and setting the `bad_prop` via an `on_trait_change`. Still, the behavior here is unexpected.

### Example

```python
from traits.api import *

class Foo(HasTraits):
x = Int

class Bar(HasTraits):
y = Int

class Baz(HasTraits):
foo = Instance(Foo)
bar = Instance(Bar)
bad_prop = Property(depends_on='bar.y')

def _bar_default(self):
return Bar(y=self.foo.x)

def _get_bad_prop(self):
return self.bar.y + 1

if __name__ == '__main__':
Baz(foo=Foo(x=1))
```

### Traceback

```
File ".../traits/has_traits.py", line 3566, in _init_trait_listeners
getattr(self, "_init_trait_%s_listener" % data[0])(name, *data)
File ".../traits/has_traits.py", line 3619, in _init_trait_property_listener
self.on_trait_change(notify, pattern, target=self)
File ".../traits/has_traits.py", line 2825, in on_trait_change
listener.register(self)
File ".../traits/traits_listener.py", line 464, in register
value = getattr(self, type)(new, name, False)
File ".../traits/traits_listener.py", line 738, in _register_simple
return next.register(getattr(object, name))
File "nothing.py", line 18, in _bar_default
return Bar(y=self.foo.x)
AttributeError: 'NoneType' object has no attribute 'x'
```

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.