简体   繁体   中英

Python Pydantic with Variables (Literal, ==, eq=)

How can I use pydantic to require that my object has an exact numeric value set by a variable?

from pydantic import BaseModel, Field

var = 10.0

class Group(BaseModel):
     value: Literal[var] # something like this
     value: float = Field(..., eq=var) # or this

Furthermore, what is the best way to create pydantic classes that use variables? Is there a way to do it within the class (instead of factory) so that the same class can be used to validate against different values?

from typing import Literal, TypeVar
from pydantic import BaseModel, Field

TGroup = TypeVar("TGroup", bound="Group") # does not work

def factory(var: float) -> TGroup: 
    class Group(BaseModel):
        value: Literal[var]
    return Group

# instead do something like this
class Group(BaseModel):
    def __init__(self, var: float, **data) -> None:
        self.value: str = Field(..., regex=f'{var}')
        super().__init__(**data)

obj = {'value': 10}
Group(var=10, **obj) # does not work

You could use a validator to validate the value that is passed.

Here's what your code could look like. Though, I have a doubt about the two variables with the same name...

from pydantic import BaseModel, ValidationError, validator

val: float = 10.0

class Group(BaseModel):
     # Are you sure you can have to variables with the same name?
     value: Literal[var] # something like this
     value: float

    @validator('value')
    def check_value(cls, v):
        if v == val:
            return v

        raise ValueError(f'Value must be equal to {val}')

And here the official docs

https://pydantic-docs.helpmanual.io/usage/validators/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM