top | item 40480392

(no title)

okso | 1 year ago

You may be interested in the type matching provided by Pydantic. It is a handy way to avoid writing `match-case` expressions.

``` >>> from pydantic import BaseModel >>> from typing import Literal, List

>>> class Chicken(BaseModel): ... n_legs: Literal[2]

>>> class Cat(BaseModel): ... n_legs: Literal[4]

>>> class Farm(BaseModel): ... animals: List[Chicken | Cat]

>>> Farm.model_validate(dict(animals=[{'n_legs': 2}, {'n_legs': 4}])) Farm(animals=[Chicken(n_legs=2), Cat(n_legs=4)]) ```

discuss

order

No comments yet.