Skip to content

msgspec.defstruct is not compatible with msgspec.StructMeta #974

@kunesj

Description

@kunesj

Description

Structs that were defined with custom metaclass (subclass of msgspec.StructMeta) can't be subclassed with msgspec.defstruct. (msgspec 0.20.0)

Following code:

import msgspec

class _FooStructMeta(msgspec.StructMeta):
    def __new__(mcls, name, bases, namespace, **struct_config):
        return super().__new__(mcls, name, bases, namespace, **struct_config)

class FooStruct(msgspec.Struct, metaclass=_FooStructMeta):
    pass

BarStruct = msgspec.defstruct(name="BarStruct", fields=[("id", int)], bases=(FooStruct,))

Raises this error:

Traceback (most recent call last):
  File "/home/jirka642/.config/JetBrains/PyCharm2025.3/scratches/scratch_1.py", line 13, in <module>
    BarStruct = msgspec.defstruct(name="BarStruct", fields=[("id", int)], bases=(FooStruct,))
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jirka642/.config/JetBrains/PyCharm2025.3/scratches/scratch_1.py", line 6, in __new__
    return super().__new__(mcls, name, bases, namespace, **struct_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Struct types cannot define __slots__

I have been able to hotfix it by running namespace.pop("__slots__", None) in the metaclass, but I'm not sure if that is safe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions