Skip to content

Instantly share code, notes, and snippets.

@davidbgk

davidbgk/utils.py

Last active Oct 1, 2020
Embed
What would you like to do?
Let's start to reference some Python utils
def neighborhood(iterable, first=None, last=None):
"""
Yield the (previous, current, next) items given an iterable.
You can specify a `first` and/or `last` item for bounds.
"""
iterator = iter(iterable)
previous = first
current = next(iterator) # Throws StopIteration if empty.
for next_ in iterator:
yield (previous, current, next_)
previous = current
current = next_
yield (previous, current, last)
import fnmatch
import os
def each_folder_from(source_dir, exclude=None):
"""Walk across the `source_dir` and return the folder paths."""
for direntry in os.scandir(source_dir):
if direntry.is_dir():
if exclude is not None and direntry.name in exclude:
continue
yield direntry
def each_file_from(source_dir, pattern="*", exclude=None):
"""Walk across the `source_dir` and return the matching `pattern` file paths."""
for filename in fnmatch.filter(sorted(os.listdir(source_dir)), pattern):
if exclude is not None and filename in exclude:
continue
yield source_dir / filename
import hashlib
def generate_md5(content):
return hashlib.md5(content.encode()).hexdigest()
# https://github.com/pyrates/minicli
from minicli import cli, run, wrap
@cli
def blah():
...
@wrap
def perf_wrapper():
start = perf_counter()
yield
elapsed = perf_counter() - start
print(f"Done in {elapsed:.5f} seconds.")
if __name__ == "__main__":
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.