Instances of generic classes defined with PEP695 syntax are unpickleable
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
Generic classes that are instantiated with the Class[Type](...) syntax have an undocumented(?) __orig_class__ attribute defined on them that contains a reference to the type passed in the brackets. This attribute is pickled along with the class as usual, and in the cases when that type is well-behaved this works fine. However, PEP695-defined TypeVars have their __module__ set to typing, and so pickling fails as it is not a true member of the typing module. This prevents the usage of either Class[Type](...) syntax or PEP695 syntax in code near anything that must be pickled.
import pickle
from typing import Generic, TypeVar
T = TypeVar('T')
class Foo(Generic[T]): # equivalently class Foo[Anything]:
pass
def bar[Baz]():
return Foo[Baz]()
pickle.dumps(bar())
# pickle.dumps(bar())
# ~~~~~~~~~~~~^^^^^^^
# _pickle.PicklingError: Can't pickle Baz: attribute lookup Baz on typing failed
print(bar().__dict__)
# {'__orig_class__': __main__.Foo[Baz]}
print(bar().__orig_class__.__parameters__[0])
# Baz
print(bar().__orig_class__.__parameters__[0].__module__)
# typing
CPython versions tested on:
3.13
Operating systems tested on:
Linux
Linked PRs
- gh-129446
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducer in the issue, focusing on PEP 695 generic classes, orig_class, and pickle.dumps(). Compare the behavior with linked PR gh-129446; the work is complete when instances created with the shown syntax can be pickled without the reported PicklingError.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100