Skip to content

Instantly share code, notes, and snippets.

from dataclasses import dataclass
class Expression:
"""Represents an ADT expression"""
@dataclass
class Literal(Expression):
value: int
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
T = TypeVar("T")
class Option(Generic[T]):
pass
from abc import ABC, abstractmethod
from dataclasses import dataclass
class Bool(ABC):
@abstractmethod
def __bool__(self):
"""True/False depends on the type"""
@dataclass
@gidgid
gidgid / python_adt_example.py
Last active December 17, 2020 07:48
adts_users_example.py
from dataclasses import dataclass
class User:
pass
@dataclass
class AuthenticatedUser(User):
id_: str
@gidgid
gidgid / gist.scala
Created December 13, 2020 19:25
adts_users_example.scala
sealed trait User
case class AuthenticatedUser(id: String, email: String, password: String) extends User
case class AnonymousUser(name: String) extends User
@gidgid
gidgid / root_with_literals_improved.py
Last active November 14, 2020 18:32
A slightly more concise way to read envs with literal types
import os
from typing import Union
import pytest
from pydantic import BaseSettings, HttpUrl, ValidationError, parse_obj_as
from typing_extensions import Literal
class LocalContext(BaseSettings): # 1
env: Literal["local"] # 1
@gidgid
gidgid / structured_access_to_dictionaries.py
Last active November 7, 2020 19:34
Nested dictionaries make us coupled to the internal structure
def test_hobbies_names_is_reliant_on_hobbies_to_have_names():
employee = {
"name": "John",
"age": 42,
"hobbies": [
{"name": "Rock Climbing", "_id": "1234"},
{"name": "Acrobatics", "_id": "5678"},
],
}
@gidgid
gidgid / data_class_with_properties.py
Last active November 7, 2020 19:39
Properties are a great way to abstract over an internal structure
from typing import List, Set
import attr
@attr.s(auto_attribs=True)
class Employee:
name: str
age: int
hobbies: List[dict] # 1
@gidgid
gidgid / comparing_parsing_to_validation.py
Last active October 29, 2020 07:09
The functions signatures already show the difference between these 2 approaches
from dataclasses import dataclass
from typing import List
# Users have:
# a name which is a non-empty string
# an age which is a positive int
# at least one hobbie (which is a non empty list)
@dataclass
@gidgid
gidgid / parse_vs_validation.py
Created October 27, 2020 21:44
Comparing parsing to validation
from dataclasses import dataclass
from typing import List
import pytest
# User's name != '' and age > 0 and hobbies > []
# and a none empty list of hobbies
# example: {'name': 'John', 'age': 30, hobbies: ['Rock Climbing', 'Books']}