Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cached properties should be pickled #1420

Open
Redoubts opened this issue Mar 21, 2025 · 1 comment
Open

cached properties should be pickled #1420

Redoubts opened this issue Mar 21, 2025 · 1 comment

Comments

@Redoubts
Copy link

Consider the following

 @attrs.define
 class A:
     @functools.cached_property
     def x(self) -> list[int]:
         print('caching')
         return list(range(5))

The following behavior is expected:

In []: attrs.__version__
Out[]: '25.3.0'

In []: a = A()

In []: a.x
caching
Out[]: [0, 1, 2, 3, 4]

In []: a.x
Out[]: [0, 1, 2, 3, 4]

a.x is cached. However, if I round trip through pickle:

In []: pickle.loads(pickle.dumps(a)).x
caching
Out[]: [0, 1, 2, 3, 4]

the cached property is rebuilt. Usually when I used cached properties, it's to hold expensive data, and it would be nice to capture this in a pickle. Can this be supported?

@hynek
Copy link
Member

hynek commented Mar 24, 2025

This seems dangerous and would have to be pre-property opt-in and I’m not sure how to do that. Just imagine the cached property determines something that is specific to the current process or machine.

If you want pickled expensive fields, I would recommend a classmethod constructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants