Skip to content

A nicer way to force validation when creating instances #812

@ionelmc

Description

@ionelmc

Description

I would like a way that does the runtime validation when creating instances manually.

Currently I have this as a base class:

class Base(Struct, kw_only=True, frozen=True):
    @classmethod
    def create(cls, **kwargs):
        try:
            return convert(kwargs, type=cls)
        except ValidationError as exc:
            raise TypeError(f"Failed creating {cls.__module__}.{cls.__name__} with {kwargs}: {exc}") from None

I know msgspec's principle is that there is no validation done in __init__ cause that is typechecker's job but on some projects it's just impossible to run one.

What I would like is something like this:

class Base(Struct, kw_only=True, frozen=True, init_validates=True):
    pass

Then my IDE would autocomplete arguments just fine (you can imagine that **kwargs is a complete mystery to my editor).

I have thought of using convert(self, from_attributes=True, type=type(self)) in __post_init__ but creating something and then throwing it away doesn't seem like a clean solution.

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