Last active
October 3, 2022 14:04
-
-
Save cbonesana/1d673aedd557ecf78ce48d8d39ffedb0 to your computer and use it in GitHub Desktop.
Working with string enums and pydantic objects in python
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 pydantic import BaseModel | |
from enum import Enum | |
import json | |
class Season(str, Enum): | |
SPRING = 'spring' | |
SUMMER = 'summer' | |
AUTUMN = 'autumn' | |
WINTER = 'winter' | |
class X(BaseModel): | |
season: Season | |
secret: str = None | |
class Config: | |
fields = { | |
'secret': {'exclude': True}, | |
'poppy': {'exclude': True}, | |
} | |
class Y(X): | |
poppy: str = None | |
x = Y(season=Season.SPRING, secret='ahah', poppy='lol') | |
print('1 object:', x) | |
# output: 1 object: season=<Season.SPRING: 'spring'> secret='ahah' poppy='lol' | |
x_dict = x.dict() | |
print('2 dict:', x_dict) | |
# output: 2 dict: {'season': <Season.SPRING: 'spring'>} | |
x_str = json.dumps(x_dict) | |
print('3 string:', x_str) | |
# output: 3 string: {"season": "spring"} | |
x_load_dict = json.loads(x_str) | |
print('4 loaded dict: ', x_load_dict) | |
# output: 4 loaded dict: {'season': 'spring'} | |
x_load = Y(**x_load_dict) | |
print('5 loaded object:', x_load) | |
# output: 5 loaded object: season=<Season.SPRING: 'spring'> secret=None poppy=None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment