Skip to content

Commit 6d13d0d

Browse files
authored
[mypyc] Fixing InitVar for dataclasses. (#18319)
Fixes mypyc/mypyc#934. `InitVar` variables are not attributes of a dataclass `PyTypeObject`. Adding check before removing `InitVar` keys from `PyTypeObject` in `CPyDataclass_SleightOfHand`.
1 parent ec04f73 commit 6d13d0d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

mypyc/lib-rt/misc_ops.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,8 @@ CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,
365365
pos = 0;
366366
PyObject *key;
367367
while (PyDict_Next(annotations, &pos, &key, NULL)) {
368-
if (PyObject_DelAttr(tp, key) != 0) {
368+
// Check and delete key. Key may be absent from tp for InitVar variables.
369+
if (PyObject_HasAttr(tp, key) == 1 && PyObject_DelAttr(tp, key) != 0) {
369370
goto fail;
370371
}
371372
}

mypyc/test-data/run-classes.test

+18
Original file line numberDiff line numberDiff line change
@@ -2655,3 +2655,21 @@ import native
26552655
[out]
26562656
(31, 12, 23)
26572657
(61, 42, 53)
2658+
2659+
[case testDataclassInitVar]
2660+
import dataclasses
2661+
2662+
@dataclasses.dataclass
2663+
class C:
2664+
init_v: dataclasses.InitVar[int]
2665+
v: float = dataclasses.field(init=False)
2666+
2667+
def __post_init__(self, init_v):
2668+
self.v = init_v + 0.1
2669+
2670+
[file driver.py]
2671+
import native
2672+
print(native.C(22).v)
2673+
2674+
[out]
2675+
22.1

0 commit comments

Comments
 (0)