Expose StructMeta in Python API#890
Conversation
…ns like asdict/json to handle structs created by StructMeta subclasses
|
Thanks! Just to confirm, you pretty much used this comparison right? main...nightsailer:msgspec-x:f9bd49fc907fa4b683f582257a463f3470e1a359 |
|
Yes, that's right! |
|
It would be worthwhile to document these changes as well, maybe with some use cases as examples EDIT: @ofek ahah, synchronized comments |
|
I'll review later tonight but at a quick glance I noticed there is no information about how to use the new capabilities. Do you think you could take a crack at writing some very basic docs and then I can expand or touch up as need be? |
|
Yeah, good point. No problem, will add something simple! |
|
How's this, @ofek? |
ofek
left a comment
There was a problem hiding this comment.
Thanks a lot for picking this back up!
|
Amazing, glad to see this is finally merged!! Thank you! |
|
which version had this exposed? I'm using 0.19.0 and cannot import it. uv run python
Python 3.12.10 (main, Apr 9 2025, 03:49:38) [Clang 20.1.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import msgspec
>>> dir(msgspec)
['DecodeError', 'EncodeError', 'Meta', 'MsgspecError', 'NODEFAULT', 'Raw', 'Struct', 'UNSET', 'UnsetType', 'ValidationError', '_Field', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_core', '_json_schema', '_utils', '_version', 'convert', 'defstruct', 'field', 'inspect', 'json', 'msgpack', 'structs', 'to_builtins', 'toml', 'yaml']
>>> msgspec.StructMeta
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'msgspec' has no attribute 'StructMeta' |
|
@landeholt this feature has not been released on pypi yet, it's only available if you clone the main branch of the repository |
Re-opening PR for #843 and #844. Copying @nightsailer's initial PR message below:
Expose and Enable Inheritance of StructMeta Metaclass
Changes
StructMetametaclass to Python for direct usePy_TPFLAGS_BASETYPEflag to enable Python inheritance ofStructMetaWhy
This allows users to:
StructMetadirectly without subclassingStructStructMetabehaviorThis PR resolves:
kw_onlyforStruct(e.g.,kw_only_default=True) #841msgspec.Struct#837Example
Technical Details
Added StructMeta to module exports in _core.c Added Py_TPFLAGS_BASETYPE flag to StructMetaType Updated init.py to import and expose StructMeta Added type hints in init.pyi
Compatibility
These changes are backward compatible and only add new capabilities without modifying existing behavior.
Related Issues