mypyc: dataclasss __annotations__ are wrong
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- 平均マージ
- 1日 18時間
- マージ済み PR(30日)
- 54
説明
Bug Report
The __annotations__ of a compiled dataclass are not the same as its pure-python counterpart.
To Reproduce
- Create a file with a dataclass
from dataclasses import dataclass
@dataclass
class Person:
age : int
name : str
- check it's annotations
python -c "import myfile;print(myfile.Person.__annotations__)"
{'age': <class 'int'>, 'name': <class 'str'>}
-
Compile it
-
Check the compiled annotations:
python -c "import myfile;print(myfile.Person.__annotations__)"
{'age': <class 'type'>, 'name': <class 'type'>}
Expected Behavior
The annotations for the compiled class should be {'age': <class 'int'>, 'name': <class 'str'>} but instead they are all <class 'type'>.
I see this in the code:
def add_non_ext_class_attr(builder: IRBuilder,
non_ext: NonExtClassInfo,
lvalue: NameExpr,
stmt: AssignmentStmt,
cdef: ClassDef,
attr_to_cache: List[Tuple[Lvalue, RType]]) -> None:
"""Add a class attribute to __annotations__ of a non-extension class.
If the attribute is initialized with a value, also add it to __dict__.
"""
# We populate __annotations__ because dataclasses uses it to determine
# which attributes to compute on.
# TODO: Maybe generate more precise types for annotations
key = builder.load_str(lvalue.name)
typ = builder.add(LoadAddress(type_object_op.type, type_object_op.src, stmt.line))
builder.call_c(dict_set_item_op, [non_ext.anns, key, typ], stmt.line)
So it looks like it's just hard-wiring type_object_op.
It's important to have accurate type annotations, because dataclasses are often inspected dynamically in order to automatically serialize them, generate protobufs, create UIs, etc based on their field data types.
Your Environment
- Mypy version used: 0.920 master
- Python version used: 3.8
- Operating system and version: mac
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず dataclass の例で不一致を再現し、次に mypyc の add_non_ext_class_attr 関数と、そこでの type_object_op の使用方法を調べます。アノテーション値がどのように選択されるかを追跡し、コンパイルされたクラスが pure-Python 版と同じ int および str のアノテーションを公開することを確認します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100