Skip to content

Commit 924f477

Browse files
authored
Declare Struct instance defaults in the type stub (msgspec#1173)
`__struct_defaults__` is available on both Struct classes and instances, but only the metaclass stub declares it. Access through an instance therefore fails type checking even though it works at runtime. Add the missing Struct annotation and cover class and instance access in the existing typing examples. Runtime behavior is unchanged. Fixes msgspec#779. Validation: the new instance assertion fails with mypy, pyright, and pyrefly before the change; all three typing suites and stubtest pass afterward. On CPython 3.12, all 6,412 unit tests and 7 package doctests pass, with 118 skips; the repository's lint, format, and spelling checks pass. Windows validation used UTF-8 mode for the existing C-source text checks and a private LLVM-MinGW compiler adapter to build the unchanged extension. Neither is included in this patch. Implemented and independently reviewed by automated agents before submission.
1 parent 2c34802 commit 924f477

2 files changed

Lines changed: 3 additions & 0 deletions

File tree

‎src/msgspec/__init__.pyi‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ def field(*, name: str | None = None) -> Any: ...
9696
@dataclass_transform(field_specifiers=(field,))
9797
class Struct(metaclass=StructMeta):
9898
__struct_fields__: ClassVar[tuple[str, ...]]
99+
__struct_defaults__: ClassVar[tuple[Any, ...]]
99100
__struct_config__: ClassVar[structs.StructConfig]
100101
__struct_encode_fields__: ClassVar[tuple[str, ...]]
101102
__match_args__: ClassVar[tuple[str, ...]]

‎tests/typing/basic_typing_examples.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ class Point(msgspec.Struct):
344344
y: int
345345

346346
assert_type(Point.__struct_fields__, tuple[str, ...])
347+
assert_type(Point.__struct_defaults__, tuple[Any, ...])
347348

348349
for field in Point.__match_args__:
349350
# mypy inferences `field` as `str`,
@@ -354,6 +355,7 @@ class Point(msgspec.Struct):
354355

355356
assert_type(p.__struct_fields__, tuple[str, ...])
356357
assert_type(p.__struct_encode_fields__, tuple[str, ...])
358+
assert_type(p.__struct_defaults__, tuple[Any, ...])
357359

358360

359361
def check_struct_config() -> None:

0 commit comments

Comments
 (0)