Skip to content

Instantly share code, notes, and snippets.

@nymous
Created April 5, 2020 17:12
Show Gist options
  • Save nymous/8a59c91d40b35c9df4767f3ad83a8d07 to your computer and use it in GitHub Desktop.
Save nymous/8a59c91d40b35c9df4767f3ad83a8d07 to your computer and use it in GitHub Desktop.
Pydantic parsing derived classes
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__)
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