Skip to content

Instantly share code, notes, and snippets.

View adammartinez271828's full-sized avatar

Adam Martinez adammartinez271828

View GitHub Profile
@adammartinez271828
adammartinez271828 / multi_mock_open.py
Last active February 28, 2024 18:52
Create a mock "open" that will mock open multiple files in sequence
from unittest.mock import mock_open
def multi_mock_open(*file_contents):
"""Create a mock "open" that will mock open multiple files in sequence
Args:
*file_contents ([str]): a list of file contents to be returned by open
Returns:
@adammartinez271828
adammartinez271828 / borg.py
Created November 16, 2016 21:06
Borg Class Implementation
class Borg(object):
"""A Borg class object
This object forces all instances of it to share the same internal state.
It is subclassable. Each subclass only shares monostate with itself, i.e.:
Borg classes do not share internal state with their subclasses.
"""
__monostate = None
def yieldwhile(predicate, iterable):
"""Yield every element from the iterable as long as the predicate is True
This is a counterpart to itertools.dropwhile.
Args:
predicate (function): a function taking a single item from iterable as an argument,
and returning a boolean
iterable (iterable): an iterable
@adammartinez271828
adammartinez271828 / sliding_window.py
Created August 16, 2016 17:02
Sliding window operator
from itertools import tee
def sliding_window(iterable, size=2):
"""Move a sliding window across iterable
A sliding window is a subselection of iterable of length size.
Args:
iterable (iterable): an iterable
@adammartinez271828
adammartinez271828 / compose.py
Last active August 15, 2016 15:44
Compose functions functionally.
from functools import reduce
def compose(*functions, forward=False):
"""Compose many (single-argument) functions into a single function
Evalutates the fuctions last-to-first by default. Use functools.partial
with this for multiargument functions.
Also, it is magic. Don't play with it or you'll let the magic out.
@adammartinez271828
adammartinez271828 / flatten.py
Last active August 3, 2016 01:08
Flatten arbitrary nested lists
def flatten(iterable):
"""Return a generator that flattens an iterable
Safe to use on nested iterables.
Args:
iterable: any iterable.
Returns:
generator of all items in iterable
@adammartinez271828
adammartinez271828 / dict-reduce.py
Last active August 3, 2016 01:07
Keywise dictionary reduction operator.
def dict_reduce(f, *dicts):
"""
Apply a function f to the values of an iterable of dictionaries by key
Gets a complete set of keys across all dictionaries, then, for each key,
applies f to the list of values of each dictionary for that key.
Args:
f (function): a function that takes an iterable
*dicts: an iterable of dictionaries