jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.44k stars 75 forks source link

Field Alias Overrides in Subclasses Not Reflected in __struct_encode_fields__ #654

Open c0x65o opened 8 months ago

c0x65o commented 8 months ago

Description

When subclassing a msgspec.Struct and redefine a field with a new alias using msgspec.field(name="new_name"), the new alias does not appear to update the struct_encode_fields attribute of the subclass. Instead, the subclass retains the parent's field alias in struct_encode_fields. This behavior seems inconsistent with the expectation that subclass field redefinitions should override parent definitions, including aliases used for encoding.

from msgspec import Struct, field

class Parent(Struct):
    field1: str = field(name="_field1")

assert Parent.__struct_encode_fields__ == ("_field1",)  # This passes

class NewParent(Parent):
    field1: str = field(name="field1")

assert NewParent.__struct_encode_fields__ == ("field1",)  # This fails with AssertionError

Expected Behavior:

The struct_encode_fields attribute of NewParent should reflect the new alias "field1" instead of inheriting "_field1" from Parent, considering the explicit redefinition of field1 in NewParent with a new alias.

Actual Behavior:

The assertion that NewParent.struct_encode_fields == ("field1",) fails, indicating that struct_encode_fields still contains the parent's alias ("_field1",).