msgspec.defstruct is not compatible with msgspec.StructMeta · Issue #974 · msgspec/msgspec · GitHub
Skip to content

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

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions