diff --git a/mypyc/lib-rt/misc_ops.c b/mypyc/lib-rt/misc_ops.c index a2b03e7df247..a7f67fd67d50 100644 --- a/mypyc/lib-rt/misc_ops.c +++ b/mypyc/lib-rt/misc_ops.c @@ -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; } } diff --git a/mypyc/test-data/run-classes.test b/mypyc/test-data/run-classes.test index cf30bddbef64..f1d1d44fffc1 100644 --- a/mypyc/test-data/run-classes.test +++ b/mypyc/test-data/run-classes.test @@ -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