-
Notifications
You must be signed in to change notification settings - Fork 131
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
Type annotations in Fishtest #2140
Comments
I have now created comprehensive documentation for |
Curiosities:
|
The classes are used both for type checking and for validation.
is functionally equivalent to
as far as The point is that if we get some untyped json
This will accomplish two things:
|
I used lower case for the classes since they are really |
Very interesting! I can use from typing import Annotated
from pydantic import (
AnyUrl,
BaseModel,
EmailStr,
Field,
IPvAnyAddress,
ValidationError,
conint,
conlist,
constr,
)
class AddressModel(BaseModel):
street: Annotated[constr(pattern=r"^\d+\s[A-Za-z\s\.]+$"), Field()]
city: Annotated[constr(pattern=r"^[A-Za-z\s]+$"), Field()]
zipcode: Annotated[constr(pattern=r"^\d{5}$"), Field()]
class UserModel(BaseModel):
name: Annotated[constr(min_length=2), Field()]
age: Annotated[conint(strict=True, gt=0, lt=120), Field()]
address: AddressModel
email: EmailStr
urls: list[AnyUrl] | None = None
ips: Annotated[conlist(IPvAnyAddress, min_length=2, max_length=2), Field()]
class NestedDictModel(BaseModel):
user: UserModel
other_key: str
def validate_data(data: dict) -> dict:
try:
validated_data = NestedDictModel(**data)
return validated_data.model_dump()
except ValidationError as e:
print(e.json())
raise
# Example usage
good_data = {
"user": {
"name": "John Doe",
"age": 40,
"address": {"street": "123 Main St.", "city": "Anytown", "zipcode": "12345"},
"email": "[email protected]",
"urls": ["https://example.com", "https://example.org"],
"ips": ["192.168.1.1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334"],
},
"other_key": "other_value",
}
try:
validated_data = validate_data(good_data)
print("Validated data:", validated_data)
except ValidationError as e:
print("Validation error:", e)
bad_data = {
"user": {
"name": "John",
"age": "ggggg",
"address": {"street": "Main St.", "city": 123, "zipcode": "123456"},
"email": "john.doe@invalid",
"urls": ["invalid-url"],
"ips": ["999.999"],
},
}
try:
validated_data = validate_data(bad_data)
print("Validated data:", validated_data)
except ValidationError as e:
print("Validation error:", e) |
So pydantic seems to be somewhat similar to vtjson... :) |
To stay up to date I adapted vtjson to work well with type annotations. This would be the new runs schema:
The text was updated successfully, but these errors were encountered: