Skip to content

Instantly share code, notes, and snippets.

@gidgid
gidgid / traditional_first.py
Created February 2, 2021 12:46
shows how to get the first element of a list and add it
from typing import List
def increment_first_by(values: List[int], add_me: int) -> int:
return values[0] + add_me
def test_increment_first():
assert increment_first_by([1, 2, 3], 5) == 5 + 1
@gidgid
gidgid / map_except_example.py
Last active February 1, 2021 19:47
map_except in more_itertools example
from typing import Dict, Iterable, Set, Tuple
from more_itertools import map_except
def process(
names: Iterable[str], whitelisted_names: Set[str], name_to_email: Dict[str, str]
) -> Iterable[str]:
whitelisted_name_to_email = {
name: email for name, email in name_to_email.items() if name in whitelisted_names
@gidgid
gidgid / flatten.py
Created January 30, 2021 12:48
we use more_itertools flatten to do a much better job
from typing import Dict, Set
from more_itertools import flatten
def flatten_multivalues(key_to_values: Dict[str, Set[int]]) -> Set[int]:
return set(flatten(key_to_values.values()))
def test_flattens_multivalue_dicts():
# shamelessly taken from: https://www.elastic.co/blog/found-elasticsearch-from-the-bottom-up
@gidgid
gidgid / flatten_manual.py
Last active January 30, 2021 12:52
shows how we can manually run flatten
from typing import Dict, Set
def flatten_multivalues(key_to_values: Dict[str, Set[int]]) -> Set[int]:
all_values = set()
for values in key_to_values.values():
all_values.update(values)
return all_values
@gidgid
gidgid / partition_example.py
Last active April 19, 2023 11:18
shows how to use the more_itertools partition function
from typing import Dict, Iterable, Set, Tuple
from more_itertools import partition
def process(
names: Iterable[str], whitelisted_names: Set[str], name_to_email: Dict[str, str]
) -> Tuple[Iterable[str], Iterable[str]]:
refused_names, approved_names = partition(
lambda name: name in whitelisted_names, names
from adt import Case, adt
@adt
class Expression:
LITERAL: Case[float]
ADD: Case["Expression", "Expression"]
SUBTRACT: Case["Expression", "Expression"]
MULTIPLY: Case["Expression", "Expression"]
DIVIDE: Case["Expression", "Expression"]
from typing import Dict, Generic, TypeVar
import pytest
from adt import Case, adt
T = TypeVar("T")
@adt
class Option(Generic[T]):
@gidgid
gidgid / evaluating_expression_with_type_checking.py
Last active December 15, 2020 14:52
shows a possible but not very useful way to operate on an expression
from dataclasses import dataclass
class Expression:
"""Represents an ADT expression"""
@dataclass
class Literal(Expression):
value: float
from dataclasses import dataclass
class State:
"""Represents a possible Circuit Breaker state"""
@dataclass
class Open(State):
pass
from datetime import datetime
from pydantic import BaseModel
class Event:
"""Represents an event"""
class Login(BaseModel, Event):