Skip to content

Instantly share code, notes, and snippets.

@gidgid
gidgid / last_custom_root_examples.py
Last active November 20, 2020 14:23
Showing wrong order and specialized models in jsons
from pydantic import BaseModel
class Age(BaseModel):
__root__: int
def divide_age(x: Age, y: int): # 1
'''implementation irrelevant'''
@gidgid
gidgid / functions_are_dry_with_models.py
Last active October 4, 2020 19:04
Why is it useful to pass specialized models to functions
from pydantic import BaseModel
class Age(BaseModel):
__root__: int
def age_in_days(age: Age) -> int:
return age.__root__ * 365 # 1
@gidgid
gidgid / non_key_values.py
Last active September 29, 2020 19:17
Basic non key-value models
from pydantic import BaseModel
class Age(BaseModel):
__root__: int # 1
def test_specialized_models_are_not_equal_to_their_primitives():
age = Age(__root__=42)
assert age != 42 # 2
@gidgid
gidgid / non_key_value_model.py
Created September 29, 2020 19:12
Defining non key-value models
from pydantic import BaseModel
class Age(BaseModel):
__root__: int
def test_specialized_models_are_not_equal_to_their_primitives():
age = Age(__root__=42)
assert age != 42
@gidgid
gidgid / validate_assignment_enforces_coercion.py
Last active October 2, 2020 11:46
Using validate_assignment to enforce type coercion
import pytest
from pydantic import BaseModel, ValidationError
class StrictPizza(BaseModel):
toppings_count: int
size: str
class Config:
validate_assignment = True # enforces coercion
@gidgid
gidgid / set_without_type_coercion.py
Last active November 20, 2020 13:39
Pydantic models set method doesnt execute type coercion
import pytest
from pydantic import BaseModel, ValidationError
class Pizza(BaseModel):
toppings_count: int
size: str
def test_field_set_doesnt_perform_conversion_either():
@gidgid
gidgid / copy_update_without_type_coercion.py
Created September 28, 2020 12:24
Copy with update doesn't perform type coercion
from pydantic import BaseModel
class Pizza(BaseModel):
toppings_count: int
size: str
def test_copy_with_update_doesnt_perform_conversion():
pizza = Pizza(toppings_count='4', size='XL')
@gidgid
gidgid / inconsistant_naming.py
Last active October 2, 2020 11:36
Inconsistant Naming Conventions
from pydantic import BaseModel
class CamelCaseItem(BaseModel):
id: str
isAvailable: bool
def test_python_camel_case_names_are_weird_in_python():
item = CamelCaseItem(id='test-item-id', isAvailable=True)
@gidgid
gidgid / .zshrc (or .bashrc)
Created April 10, 2020 17:28
Activating virtual envs with FZF
vf() {
# note that you need to extract the absolute path in order to get this to work
ls -d ~/.virtualenv/*/ | fzf | while read file; do source $file/bin/activate; done
}
@gidgid
gidgid / .zshrc (or .bashrc)
Last active April 9, 2020 13:29
Source different env files
# source relevant env files via fzf
# note that sf() can also be used without Kubectl
sf() {
find ~/.envs -type f | fzf | while read filename; do source $filename; done
}