Created
October 4, 2020 08:52
-
-
Save gidgid/38360d1364e2165df4ab722de9f2b758 to your computer and use it in GitHub Desktop.
Using Pydantic field aliases to bridge inconsistent naming
This file contains hidden or 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
import pytest | |
from pydantic import BaseModel, Field, ValidationError | |
class Item(BaseModel): | |
item_id: str | |
is_available: bool = Field(alias='isAvailable') # 1 | |
def test_field_aliasing_bridges_inconsistant_conventions(): | |
item1 = Item(item_id='test-item-id', isAvailable=True) # 2 | |
assert item1.is_available is True # 3 | |
# Note that referring to is_available raises a ValidationErrror | |
# https://github.com/samuelcolvin/pydantic/issues/565#issuecomment-497467975-permalink:~:text=aliases%20as%20I%20think%20of%20them,the%20names%20used%20in%20your%20application | |
with pytest.raises(ValidationError): # 4 | |
Item(item_id='test-item-id', is_available=True) # 4 | |
class ItemWithVisibleId(BaseModel): | |
item_id: str = Field(alias='_id') # 1 | |
is_available: bool | |
def test_field_aliasing_solves_field_hiding(): | |
item = ItemWithVisibleId(_id='test-item-id', is_available=True) # 2 | |
assert item.item_id == 'test-item-id' # 3 | |
assert item.dict(by_alias=True).get('_id') == 'test-item-id' # 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment