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

Viewed 32

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
0 Answers
Related