Skip to content

Instantly share code, notes, and snippets.

@ahoward
Last active November 8, 2023 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoward/c381884688110fb56be88dacef039391 to your computer and use it in GitHub Desktop.
Save ahoward/c381884688110fb56be88dacef039391 to your computer and use it in GitHub Desktop.
# 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
# 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