Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal for a decorator which adds type validation to all fields #109

Open
pohlt opened this issue Nov 29, 2023 · 2 comments
Open

Proposal for a decorator which adds type validation to all fields #109

pohlt opened this issue Nov 29, 2023 · 2 comments

Comments

@pohlt
Copy link

pohlt commented Nov 29, 2023

Here's a snipped for a class decorator define_strict which makes all fields strict.

I can prepare a PR if you are interested.

import attrs
from attrs_strict import type_validator


def define_strict(maybe_cls=None, **kwargs):
    def add_validators_hook(_, fields):
        return [attr.evolve(validator=type_validator()) for attr in fields]

    d = attrs.define(**kwargs | {"field_transformer": add_validators_hook})

    if maybe_cls:
        return d(maybe_cls)
    else:
        return lambda cls: d(cls)


@define_strict(frozen=False)
class C:
    x: int
    y: float
    s: str


print(C(5, 4.0, "works"))
print(C(5, "BAM!", 42))  # 💥
@pohlt
Copy link
Author

pohlt commented Nov 29, 2023

Pitfalls:

  • It does not (yet) play nicely with other field transformers. Chaining should fix that.
  • VS Code does not understand that class C actually accepts/expects three parameters in the constructor. Any guidance appreciated.

@pohlt
Copy link
Author

pohlt commented Nov 29, 2023

Small change to handle given field_transformers:

    def add_validators_hook(cls, fields):
        return kwargs.get("field_transformer", lambda _, v: v)(
            cls, [attr.evolve(validator=type_validator()) for attr in fields]
        )

@pohlt pohlt changed the title Proposal for a decorator which add type validator to all fields Proposal for a decorator which adds type validation to all fields Nov 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant