Skip to content

Commit

Permalink
[mypyc] Fixing InitVar for dataclasses. (#18319)
Browse files Browse the repository at this point in the history
Fixes mypyc/mypyc#934.

`InitVar` variables are not attributes of a dataclass `PyTypeObject`.
Adding check before removing `InitVar` keys from `PyTypeObject` in
`CPyDataclass_SleightOfHand`.
  • Loading branch information
advait-dixit authored Dec 27, 2024
1 parent ec04f73 commit 6d13d0d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion mypyc/lib-rt/misc_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,8 @@ CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,
pos = 0;
PyObject *key;
while (PyDict_Next(annotations, &pos, &key, NULL)) {
if (PyObject_DelAttr(tp, key) != 0) {
// Check and delete key. Key may be absent from tp for InitVar variables.
if (PyObject_HasAttr(tp, key) == 1 && PyObject_DelAttr(tp, key) != 0) {
goto fail;
}
}
Expand Down
18 changes: 18 additions & 0 deletions mypyc/test-data/run-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -2655,3 +2655,21 @@ import native
[out]
(31, 12, 23)
(61, 42, 53)

[case testDataclassInitVar]
import dataclasses

@dataclasses.dataclass
class C:
init_v: dataclasses.InitVar[int]
v: float = dataclasses.field(init=False)

def __post_init__(self, init_v):
self.v = init_v + 0.1

[file driver.py]
import native
print(native.C(22).v)

[out]
22.1

0 comments on commit 6d13d0d

Please sign in to comment.