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

How to validate Annotation on __init__ #776

Open
raidgar98 opened this issue Nov 29, 2024 · 2 comments
Open

How to validate Annotation on __init__ #776

raidgar98 opened this issue Nov 29, 2024 · 2 comments

Comments

@raidgar98
Copy link

Question

I have example like this:

AccountName = Annotated[str, ms.Meta(min_length=3, max_length=16, pattern="^([a-z]+)$")]

but this does not throw any error:

AccountName("0")

how to force validation? I thought about something like this:

class AccountName(Annotated[str, ms.Meta(min_length=3, max_length=16, pattern="^([a-z]+)$")]):
    def __init__(self, value: Any) -> None:
        super().__init__(value)
        msgspec.validate(self)  # something like this

or

AccountNameImpl = Annotated[str, ms.Meta(min_length=3, max_length=16, pattern="^([a-z]+)$")]

def AccountName(value: str) -> AccountNameImpl:
    result = AccountNameImpl(value)
    msgspec.validate(result)
    # msgspec.json.encode(result)  # i don't want it to validate like this
    return result

But i can't find validate method and because of large amount of objects that are created in my project i don't want to encode to validate all the time. If dedicated method was exposed i can deal with this

@jack-mcivor
Copy link

jack-mcivor commented Nov 29, 2024

msgspec.convert("0", type=AccountName)

However in general the idea is that you can rely on a type checker to perform validation when types can be statically determined. This is a really good read https://jcristharif.com/msgspec/structs.html#type-validation

See also https://jcristharif.com/msgspec/converters.html for info on the convert method

@jack-mcivor
Copy link

There is an existing discussion here #513

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

2 participants