Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.6.1
pydantic compiled: True
install path: /root/projects/py/landlords-server/.venv/lib/python3.8/site-packages/pydantic
python version: 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0]
platform: Linux-4.19.84-microsoft-standard-x86_64-with-glibc2.29
optional deps. installed: ['typing-extensions']
from pydantic import BaseModel
class UserInfo(BaseModel):
""" for my application """
name: str
email: str
class GoogleUserInfo(UserInfo):
""" google account """
sub: str
family_name: str
given_name: str
picture: str
class OtherOAuthUserInfo(UserInfo):
...
def sign_in(user_info: UserInfo):
database.save(user_info)
def main():
google_user_info = GoogleUserInfo(...)
other_user_info = OtherOAuthUserInfo(...)
sign_in(UserInfo(google_user_info)) # error
sign_in(UserInfo(other_user_info)) # error
I want to use up-casting. but, user_info variable is GoogleUserInfo instance in sign_in function.
Can I use up-casting?
Hello @mcauto
I would go with something like this
from typing import Union
from pydantic import BaseModel
class BaseUserInfo(BaseModel):
""" for my application """
name: str
email: str
class GoogleUserInfo(BaseUserInfo):
""" google account """
sub: str
family_name: str
given_name: str
picture: str
class OtherOAuthUserInfo(BaseUserInfo):
...
and then either declare the main model and user parse_obj to avoid having to set __root__ manually:
class UserInfo(BaseModel):
__root__: Union[GoogleUserInfo, OtherOAuthUserInfo]
UserInfo.parse_obj(google_user_infos)
or just
from pydantic.tools import parse_obj_as
UserInfo = Union[GoogleUserInfo, OtherOAuthUserInfo]
parse_obj_as(UserInfo, google_user_infos)
Hello! @PrettyWood
Thank you for your time.
It's nice explanation.
Could you review my code?
UserInfo(**google_auth_info.dict())
UserInfo(**other_user_info.dict())
@mcauto What should I review ? I don't get it sorry