Angel
Angel

Reputation: 2865

Can I use Pydantic models with constant variable names and later referencing them using their value?

Can I use pydantic models using constant names and later referencing them using their value?

An example is worth more than a thousand words:

Is there a way to do this:

from pydantic import BaseModel

COLUMN_MEAN = "mean"
COLUMN_LENGTH = "length"

class Item(BaseModel):
    COLUMN_MEAN: float
    COLUMN_LENGTH: int
    

But later, when using the model, doing it like this:

Item(mean=2.1, length=10)

Upvotes: 1

Views: 5536

Answers (1)

zhenhua32
zhenhua32

Reputation: 264

You can not use const in python, refer this.

Buf if you want another name for BaseModel field, can use alias.

from pydantic import BaseModel, Field
from typing import Final

COLUMN_MEAN = "mean"
COLUMN_LENGTH = "length"

class Item(BaseModel):
    COLUMN_MEAN: float = Field(alias=COLUMN_MEAN)
    COLUMN_LENGTH: int = Field(alias=COLUMN_LENGTH)

Item(mean=2.1, length=10)

output in jupyter:

Item(COLUMN_MEAN=2.1, COLUMN_LENGTH=10)

Upvotes: 2

Related Questions