Skip to content

Instantly share code, notes, and snippets.

View Shuhala's full-sized avatar

Sophie Bernadin-Mercier Shuhala

  • Montreal
View GitHub Profile
@Shuhala
Shuhala / base_dataclass.py
Created March 20, 2021 21:42
DataClass that can be converted to / from a dict
from dataclasses import asdict, dataclass, fields, is_dataclass
@dataclass
class BaseDataClass:
def __post_init__(self):
"""
Convert all fields of type `dataclass` into an instance of the
specified data class if the current value is of type dict.
"""
@Shuhala
Shuhala / .zshrc
Last active February 14, 2021 01:46
thor zsh completion
export PATH="$DOTFILES/zsh/scripts/bin:$PATH"
fpath=( $DOTFILES/zsh/scripts/completions $fpath )
autoload -U compinit && compinit
@Shuhala
Shuhala / profile.py
Created November 28, 2019 14:57
Profile a code block
import cProfile
import contextlib
import io
import pstats
@contextlib.contextmanager
def profile(max_results=-1, pattern="*"):
"""
Profile a code block
import traceback
from typing import Optional, Union
def format_exception(exception: Optional[Union[Exception, BaseException]]) -> str:
""" Format a prettier exception trace """
if exception:
return f"\n{type(exception).__name__} Exception: {exception}" f"\n{''.join(traceback.format_tb(exception.__traceback__))}"
return " Exception."
import traceback
from typing import Optional, Union
def format_exception(exception: Optional[Union[Exception, BaseException]]) -> str:
""" Format a prettier exception trace """
if exception:
return f"\n{type(exception).__name__} Exception: {exception}" f"\n{''.join(traceback.format_tb(exception.__traceback__))}"
return " Exception."
@Shuhala
Shuhala / alembic_migrations.py
Created November 20, 2019 19:37
Scripts for alembic to assert that the database is up to date, migrations are up to date and to run migrations programmatically
from alembic import config
from alembic import script
from alembic.autogenerate import compare_metadata
from alembic.runtime import migration
from alembic.runtime.environment import EnvironmentContext
# other imports ...
def assert_database_is_up_to_date():
""" Database is up to date with migration head version """
@Shuhala
Shuhala / find_all.py
Created May 20, 2019 22:20
SQLAlchemy findall
def find_all(session: Session, offset: int, limit: int, order_by: str = "", filters: Optional[list] = None, joins: Optional[list] = None):
if not filters:
filters = []
if not joins:
joins = []
query = session.query(self._model_type)
if joins:
query = query.join(*joins)
@Shuhala
Shuhala / argparse_dict.py
Created March 25, 2019 12:33
Dictionary type for argparse argument
parser = argparse.ArgumentParser(description="input `a=b&c=d` becomes `dict({'a':'b', 'c':'d'})`")
parser.add_argument(
"-p", "--params",
help="Convert parameters in the form `--params a=b&c=d` to a dictionary",
action=type('', (argparse.Action,), dict(
__call__=lambda a, _, n, v, __: setattr(n, a.dest, dict([kv.split('=') for kv in v.split('&')]))
)),
default={},
)
@Shuhala
Shuhala / property_type_mixin.py
Created February 20, 2019 19:58
PropertyTypeMixin
from typing import Any, Dict
class PropertyTypeMixin:
"""
Enforce type checking of attributes at runtime
"""
_properties_type: Dict[str, Any] = {}
def __setattr__(self, key, value):
@Shuhala
Shuhala / outdated-requirements.sh
Created July 25, 2017 13:31
Output latest outdated pip dependencies version in requirements.txt format
pip list --outdated | sed 's/ (.*Latest: /==/g;s/ \[.*//g'