-
-
Save ahoward/c381884688110fb56be88dacef039391 to your computer and use it in GitHub Desktop.
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
# current code. BAD. | |
import uuid | |
from uuid import UUID | |
from typing import cast | |
from dataclasses import dataclass | |
@dataclass | |
class DC: | |
uuid: UUID | |
print(type(DC(42).uuid)) #=> int! | |
print(type(DC('42').uuid)) #=> str! | |
print(type(DC('954df9cd-5539-4552-975c-d42223731620').uuid)) #=> str! | |
print(type(DC(cast(UUID, '954df9cd-5539-4552-975c-d42223731620')).uuid)) #=> omfg str! | |
print(type(DC(cast(UUID, ['what', 'the', 'eff'])).uuid)) #=> list | |
dc = DC(uuid.uuid4()) | |
dc.anything_goes = True # not even a warning... | |
some_form = {'name':'value'} | |
dc.silent_error = some_form['name'] # remembering that our forms have ZERO type checking, this one is __very easy to make | |
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
# new code. GOOD. | |
from uuid import UUID | |
from typing import cast | |
from pydantic import BaseModel | |
class DC(BaseModel): | |
uuid: UUID | |
try: | |
print(type(DC(uuid=42).uuid)) | |
except Exception as e: | |
print(e) | |
""" | |
1 validation error for DC | |
uuid | |
UUID input should be a string, bytes or UUID object [type=uuid_type, input_value=42, input_type=int] | |
For further information visit https://errors.pydantic.dev/2.4/v/uuid_type | |
""" | |
print(type(DC(uuid=UUID('954df9cd-5539-4552-975c-d42223731620')).uuid)) #=> UUID! obvi | |
print(type(DC(uuid=str('954df9cd-5539-4552-975c-d42223731620')).uuid)) #=> UUID! i'm cry ;-) | |
try: | |
dc = DC(uuid='954df9cd-5539-4552-975c-d42223731620') | |
dc.some_form_field_error = 'whoops!' | |
except Exception as e: | |
print(e) | |
""" | |
"DC" object has no field "some_form_field_error" | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment