mypyc: dataclasss __annotations__ are wrong
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
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 by reproducing the mismatch with the dataclass example, then inspect mypyc's add_non_ext_class_attr function and its use of type_object_op. Trace how the annotation value is selected and verify that compiled classes expose the same int and str annotations as the pure-Python version.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100