enthought / enthought/traits

cache is not flushed in cached properties with explicit getter

Open
#282 1 comment 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

```
from traits.api import *

@cached_property
def an_explicit_getter_function(self):
return self.a

class Test(HasTraits):
a = Int
b = Property(
an_explicit_getter_function,
depends_on='a'
)

t = Test(a=1)
print(t.b)
t.a = 2
print(t.b)
```

will print twice `1`. Indeed, one possible bug by judging of the source-code is the fact that `cached_property` blindly takes `fget.__name__[5:]` as the name of the trait. Several variations (short and long names), `lambda` and direct setting of `cached` metadata or `cached_property` attribute to getter function do not work either.
As far as I can tell, the problem is that the caching logic inside the wrapper generated in `cached_property` uses a different key in the objects `__dict__` for caching than what the cache flushing machinery uses (see `MetaHasTraits._init_trait_property_listener`).

A solution would either need to propagate the key that is used from the `cached_property` decorator to the traits notification machinery, or better the other way around (which would mean the wrapper generation would have to be delayed to `MetaHasTraits.__new__` time. In any case, there should at least be an exception from `cached_property` rather than silently failing. These kind of problems take a lot of time to debug!

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.