Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

defstruct accepts None for module/namespace/bases #445

Merged
merged 1 commit into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion msgspec/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def defstruct(
name: str,
fields: Iterable[Union[str, Tuple[str, type], Tuple[str, type, Any]]],
*,
bases: Tuple[Type[Struct], ...] = (),
bases: Optional[Tuple[Type[Struct], ...]] = None,
module: Optional[str] = None,
namespace: Optional[Dict[str, Any]] = None,
tag: Union[None, bool, str, int, Callable[[str], Union[str, int]]] = None,
Expand Down
32 changes: 26 additions & 6 deletions msgspec/_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -5930,7 +5930,7 @@ StructMeta_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)


PyDoc_STRVAR(msgspec_defstruct__doc__,
"defstruct(name, fields, *, bases=(), module=None, namespace=None, "
"defstruct(name, fields, *, bases=None, module=None, namespace=None, "
"tag_field=None, tag=None, rename=None, omit_defaults=False, "
"forbid_unknown_fields=False, frozen=False, eq=True, order=False, "
"kw_only=False, repr_omit_defaults=False, array_like=False, gc=True, "
Expand Down Expand Up @@ -5986,8 +5986,8 @@ msgspec_defstruct(PyObject *self, PyObject *args, PyObject *kwargs)

/* Parse arguments: (name, bases, dict) */
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "UO|$O!UO!OOOppppppppppp:defstruct", kwlist,
&name, &fields, &PyTuple_Type, &bases, &module, &PyDict_Type, &namespace,
args, kwargs, "UO|$OOOOOOppppppppppp:defstruct", kwlist,
&name, &fields, &bases, &module, &namespace,
&arg_tag_field, &arg_tag, &arg_rename,
&arg_omit_defaults, &arg_forbid_unknown_fields,
&arg_frozen, &arg_eq, &arg_order, &arg_kw_only,
Expand All @@ -5998,20 +5998,40 @@ msgspec_defstruct(PyObject *self, PyObject *args, PyObject *kwargs)

MsgspecState *mod = msgspec_get_global_state();

namespace = (namespace == NULL) ? PyDict_New() : PyDict_Copy(namespace);
/* Handle namespace */
if (namespace == NULL || namespace == Py_None) {
namespace = PyDict_New();
}
else {
if (!PyDict_Check(namespace)) {
PyErr_SetString(PyExc_TypeError, "namespace must be a dict or None");
return NULL;
}
namespace = PyDict_Copy(namespace);
}
if (namespace == NULL) return NULL;

if (module != NULL) {
/* Handle module */
if (module != NULL && module != Py_None) {
if (!PyUnicode_CheckExact(module)) {
PyErr_SetString(PyExc_TypeError, "module must be a str or None");
goto cleanup;
}
if (PyDict_SetItemString(namespace, "__module__", module) < 0) goto cleanup;
}

if (bases == NULL) {
/* Handle bases */
if (bases == NULL || bases == Py_None) {
new_bases = PyTuple_New(1);
if (new_bases == NULL) goto cleanup;
Py_INCREF(mod->StructType);
PyTuple_SET_ITEM(new_bases, 0, mod->StructType);
bases = new_bases;
}
else if (!PyTuple_CheckExact(bases)) {
PyErr_SetString(PyExc_TypeError, "bases must be a tuple or None");
goto cleanup;
}

annotations = PyDict_New();
if (annotations == NULL) goto cleanup;
Expand Down
5 changes: 4 additions & 1 deletion tests/basic_typing_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,15 +376,18 @@ def check_defstruct_bases() -> None:
class Base(msgspec.Struct):
pass

Test = msgspec.defstruct("Test", ["x", "y"], bases=(Base,))
msgspec.defstruct("Test", ["x", "y"], bases=(Base,))
msgspec.defstruct("Test2", ["x", "y"], bases=None)


def check_defstruct_namespace() -> None:
msgspec.defstruct("Test", ["x", "y"], namespace={"classval": 1})
msgspec.defstruct("Test2", ["x", "y"], namespace=None)


def check_defstruct_module() -> None:
msgspec.defstruct("Test", ["x", "y"], module="mymod")
msgspec.defstruct("Test2", ["x", "y"], module=None)


def check_defstruct_config_options() -> None:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -1996,6 +1996,15 @@ def test_defstruct_errors(self):
with pytest.raises(TypeError, match="items in `fields` must be one of"):
defstruct("Test", ["x", (1, 2)])

with pytest.raises(TypeError, match="must be a tuple or None"):
defstruct("Test", [], bases=[])

with pytest.raises(TypeError, match="must be a str or None"):
defstruct("Test", [], module=1)

with pytest.raises(TypeError, match="must be a dict or None"):
defstruct("Test", [], namespace=1)

def test_defstruct_bases(self):
class Base(Struct):
z: int
Expand All @@ -2006,17 +2015,30 @@ class Base(Struct):
assert as_tuple(Point(1, 2, 0)) == (1, 2, 0)
assert as_tuple(Point(1, 2, 3)) == (1, 2, 3)

def test_defstruct_bases_none(self):
Point = defstruct("Point", ["x", "y"], bases=None)
assert Point.mro() == [Point, *Struct.mro()]
assert Point(1, 2) == Point(1, 2)

def test_defstruct_module(self):
Test = defstruct("Test", [], module="testmod")
assert Test.__module__ == "testmod"

def test_defstruct_module_none(self):
Test = defstruct("Test", [], module=None)
assert Test.__module__ == "test_struct"

def test_defstruct_namespace(self):
Test = defstruct(
"Test", ["x", "y"], namespace={"add": lambda self: self.x + self.y}
)
t = Test(1, 2)
assert t.add() == 3

def test_defstruct_namespace_none(self):
Test = defstruct("Test", [], namespace=None)
assert Test() == Test() # smoketest

def test_defstruct_kw_only(self):
Test = defstruct("Test", ["x", "y"], kw_only=True)
t = Test(x=1, y=2)
Expand Down