Skip to content

Add option to add __dict__ on msgspec.Struct types #324

Description

@jcrist

Description

Currently msgspec.Struct types are __slots__ only, defining no instance dicts. This is for both efficiency (slots reduce memory usage and require no dict-lookup for internal access) and correctness (no instance __dict__ means you get a runtime error for typos when setting attributes). However sometimes it can be useful to have a lazily-created __dict__ defined. One use case is functools.cached_property support, which only works for objects with a __dict__ defined (#204).

We should enable this as an opt-in feature. Something like:

class Point(Struct, dict=True):  # probably a better option name
    x: int
    y: int

# both `x` and `y` are still stored in `__slots__`, no `__dict__` allocated yet
p = Point(1, 2)

# Setting an undeclared attribute will allocate a `__dict__` and store the attribute there
p.z = 3

# undeclared attributes are ignored by msgspec's encoders
msgspec.json.encode(p)
# {"x":1,"y":2}

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