python / python/cpython

Instances of generic classes defined with PEP695 syntax are unpickleable

未關閉
#129,250 6 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core topic-typing type-bug
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

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

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 issue 中的 reproducer 開始,重點關注 PEP 695 泛型類別、orig_class 和 pickle.dumps()。將行為與關聯的 PR gh-129446 進行比較;當使用所示語法建立的實例能夠在不出現所回報的 PicklingError 的情況下進行 pickle 時,這項工作就完成了。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
compilers
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。