You can also check the official documentation and example here https://pydantic-docs.helpmanual.io/usage/types/#literal-type
Created
April 5, 2020 17:12
-
-
Save nymous/8a59c91d40b35c9df4767f3ad83a8d07 to your computer and use it in GitHub Desktop.
Pydantic parsing derived classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Union | |
from pydantic import parse_obj_as | |
from models import LocalRepo, RemoteRepo, VirtualRepo | |
local = { | |
"rclass": "local", | |
"name": "local-repo" | |
} | |
remote = { | |
"rclass": "remote", | |
"name": "remote-repo" | |
} | |
virtual = { | |
"rclass": "virtual", | |
"name": "virtual-repo" | |
} | |
local_repository = parse_obj_as(Union[LocalRepo, RemoteRepo, VirtualRepo], local) | |
remote_repository = parse_obj_as(Union[LocalRepo, RemoteRepo, VirtualRepo], remote) | |
virtual_repository = parse_obj_as(Union[LocalRepo, RemoteRepo, VirtualRepo], virtual) | |
print(type(local_repository).__name__) | |
print(type(remote_repository).__name__) | |
print(type(virtual_repository).__name__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum | |
from typing_extensions import Literal | |
from pydantic import BaseModel | |
class RclassEnum(str, Enum): | |
local = "local" | |
remote = "remote" | |
virtual = "virtual" | |
class BaseRepo(BaseModel): | |
rclass: RclassEnum | |
name: str | |
class LocalRepo(BaseRepo): | |
rclass: Literal[RclassEnum.local] = RclassEnum.local | |
class RemoteRepo(BaseRepo): | |
rclass: Literal[RclassEnum.remote] = RclassEnum.remote | |
class VirtualRepo(BaseRepo): | |
rclass: Literal[RclassEnum.virtual] = RclassEnum.virtual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment