Skip to content

Instantly share code, notes, and snippets.

@dwreeves
Created October 16, 2022 21:31
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 dwreeves/9cfcdf847153971634501b551fad8308 to your computer and use it in GitHub Desktop.
Save dwreeves/9cfcdf847153971634501b551fad8308 to your computer and use it in GitHub Desktop.
from pydantic import BaseModel, ConstrainedStr, StrictStr
class MyStr(ConstrainedStr):
to_upper = True
class Foo(BaseModel):
x: str
class Bar(BaseModel):
x: MyStr
class Baz(BaseModel):
x: StrictStr
obj1 = Foo(x=MyStr("hello, world!"))
print(obj1.x.to_upper) # works, despite objections of IDE
obj2 = Bar(x="hello, world!")
print(obj2.x.to_upper) # fails, despite IDE not telling you
obj3 = Baz(x="hello, world!")
print(obj3.x.to_upper) # fails, despite IDE not telling you
obj4 = Baz(x=StrictStr("hello, world!"))
print(obj4.x.to_upper) # works + type is StrictStr
obj5 = Baz(x=MyStr("hello, world!"))
print(obj5.x.to_upper) # works, but type is MyStr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment