Skip to content

__post_init__ not called from replace #874

@kramar11

Description

@kramar11

Description

When using msgspec.structs.replace to create a new object, the __post_init__ method is not called (unlike with dataclass.replace).

from dataclasses import dataclass, replace
import msgspec
                                                                                                                   
@dataclass
class D:                                                                                                           
    x: int
    def __post_init__(self):
        print("dataclass: post init called")
                                                                                                                   
                                                                                                                   
class M(msgspec.Struct):                                                                                           
    x: int                                                                                                         
    def __post_init__(self):                                                                                       
        print("msgspec: post init called")                                                                         
                                                                                                                   
                                                                                                                   
d = D(1)                                                                                                           
m = M(1)                                                                                                           
                                                                                                                   
d2 = replace(d, x=2)                                                                                               
m2 = msgspec.structs.replace(m, x=2) 

# Output:
# dataclass: post init called
# msgspec: post init called
# dataclass: post init called

Tested with python 3.13.5.

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