Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions mypyc/lib-rt/misc_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,
PyObject *dict, PyObject *annotations) {
PyTypeObject *ttp = (PyTypeObject *)tp;
Py_ssize_t pos;
PyObject *res;
PyObject *res = NULL;

/* Make a copy of the original class __dict__ */
PyObject *orig_dict = PyDict_Copy(ttp->tp_dict);
Expand Down Expand Up @@ -381,17 +381,30 @@ CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,
if (!res) {
goto fail;
}
Py_DECREF(res);
// These attributes are added or modified by @attr.s(slots=True).
const char * const keys[] = {"__attrs_attrs__", "__attrs_own_setattr__", "__init__", ""};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about doing this only when using @attr.s, but not for a regular dataclass? E.g. pass a flag to the function indicating whether we are dealing with an attrs class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If my understanding is correct, CPython actually uses res but CPyDataclass_SleightOfHand(...) is throwing it away. So, copying attributes will probably reduce errors. Anyway, I have added a condition to copy attributes only for attr and attr-auto dataclasses. Please take a look.

for (const char * const *key_iter = keys; **key_iter != '\0'; key_iter++) {
PyObject *value = NULL;
int rv = PyObject_GetOptionalAttrString(res, *key_iter, &value);
if (rv == 1) {
PyObject_SetAttrString(tp, *key_iter, value);
Py_DECREF(value);
} else if (rv == -1) {
goto fail;
}
}

/* Copy back the original contents of the dict */
if (_CPy_UpdateObjFromDict(tp, orig_dict) != 0) {
goto fail;
}

Py_DECREF(res);
Py_DECREF(orig_dict);
return 1;

fail:
Py_XDECREF(res);
Py_XDECREF(orig_dict);
return 0;
}
Expand Down
14 changes: 14 additions & 0 deletions mypyc/test-data/run-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -2705,3 +2705,17 @@ print(native.ColorCode.OKGREEN.value)

[out]
okgreen

[case testAttrWithSlots]
import attr

@attr.s(slots=True)
class A:
ints: list[int] = attr.ib()

[file driver.py]
import native
print(native.A(ints=[1, -17]).ints)

[out]
\[1, -17]
Loading