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

Classes and instances produced by dataclasses.make_dataclass are not pickleable #102103

Closed
sobolevn opened this issue Feb 21, 2023 · 2 comments
Closed
Assignees
Labels
stdlib Python modules in the Lib dir type-bug An unexpected behavior, bug, or error

Comments

@sobolevn
Copy link
Member

sobolevn commented Feb 21, 2023

Repro:

## Setup

>>> import pickle
>>> import dataclasses
>>> A = dataclasses.make_dataclass('A', [])
>>> @dataclasses.dataclass
... class B: pass
... 

## Correct

>>> pickle.loads(pickle.dumps(B))
<class '__main__.B'>
>>> pickle.loads(pickle.dumps(B()))
B()

## Wrong

>>> pickle.load(pickle.dump(A))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'types.A'>: attribute lookup A on types failed

>>> pickle.loads(pickle.dumps(A()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'types.A'>: attribute lookup A on types failed

I think that this happens because of this:

>>> A.__module__
'types'
>>> B.__module__
'__main__'

After a manual fix it works as it should:

>>> A.__module__ = '__main__'
>>> pickle.loads(pickle.dumps(A()))
A()

So, I propose to do it for all dataclasses that we create in make_dataclass.

I have a simple PR ready, it is inspired by namedtuple's logic :)

Linked PRs

@sobolevn
Copy link
Member Author

@Fatal1ty great timing, happy to help! 🙂

@endlisnis
Copy link

Funny timing. I just ran into this bug myself yesterday.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

3 participants