Skip to content

Commit

Permalink
Support defining struct with field with no args
Browse files Browse the repository at this point in the history
Previously using `field()` (with no arguments) to define a struct field
would result in a segfault. This PR resolves that issue and adds a test.
  • Loading branch information
jcrist committed Mar 15, 2023
1 parent 07fbf62 commit 316192d
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
3 changes: 2 additions & 1 deletion msgspec/_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -5137,7 +5137,8 @@ structmeta_process_default(StructMetaInfo *info, PyObject *field) {
goto done;
}
else {
if (PyDict_SetItem(info->defaults_lk, field, NODEFAULT) < 0) return -1;
default_val = NODEFAULT;
Py_INCREF(default_val);
goto done;
}
}
Expand Down
4 changes: 3 additions & 1 deletion tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,11 +864,13 @@ def test_struct_defaults_from_field():
default = []

class Test(Struct):
req: int = field()
x: int = field(default=1)
y: int = field(default_factory=lambda: 2)
z: List[int] = field(default=default)

t = Test()
t = Test(100)
assert t.req == 100
assert t.x == 1
assert t.y == 2
assert t.z == []
Expand Down

0 comments on commit 316192d

Please sign in to comment.