1

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)
Angel
  • 1,959
  • 18
  • 37

1 Answers1

2

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)
zhenhua32
  • 256
  • 1
  • 6
  • I know this way, however, then you cannot do later `item.mean` you need to convert it to JSON with the `byalias`flag – Angel Jul 30 '21 at 08:52