enforce

class lunchbox.enforce.Comparator(value)[source]

Bases: Enum

Enum for comparison operators used by Enforce.

Includes:

  • EQ

  • NOT_EQ

  • GT

  • GTE

  • LT

  • LTE

  • SIMILAR

  • NOT_SIMILAR

  • IN

  • NOT_IN

  • INSTANCE_OF

  • NOT_INSTANCE_OF

EQ = ('eq', 'equal', '==', False, '!=', 'not equal to')
GT = ('gt', 'greater', '>', False, '<=', 'not greater than')
GTE = ('gte', 'greater or equal', '>=', False, '<', 'less than')
IN = ('in_', 'in', 'in', False, 'not in', 'not in')
INSTANCE_OF = ('instance_of', 'instance of', 'isinstance', False, 'not isinstance', 'not instance of')
LT = ('lt', 'lesser', '<', False, '>=', 'not less than')
LTE = ('lte', 'lesser or equal', '<=', False, '>', 'greater than')
NOT_EQ = ('eq', 'not equal', '!=', True, '==', 'equal to')
NOT_IN = ('in_', 'not in', 'not in', True, 'in', 'in')
NOT_INSTANCE_OF = ('instance_of', 'not instance of', 'not isinstance', True, 'isinstance', 'instance of')
NOT_SIMILAR = ('similar', 'not similar', '!~', True, '~', 'similar to')
SIMILAR = ('similar', 'similar', '~', False, '!~', 'not similar to')
__init__(function, text, symbol, negation, negation_symbol, message)[source]

Constructs Comparator instance.

Parameters:
  • function (str) – Enforce function name.

  • text (str) – Comparator as text.

  • symbol (str) – Comparator as symbol.

  • negation (bool) – Function is a negation.

  • negation_symbol (str) – Negated comparator as symbol.

  • message (str) – Error message fragment.

__module__ = 'lunchbox.enforce'
property canonical

Canonical name of Comparator

Type:

str

static from_string(string)[source]

Constructs Comparator from given string.

Parameters:

string (str) – Comparator name.

Returns:

Comparator.

Return type:

Comparator

class lunchbox.enforce.Enforce(a, comparator, b, attribute=None, message=None, epsilon=0.01)[source]

Bases: object

Faciltates inline testing. Super class for Enforcer subclasses.

Example

>>> class Foo:
        def __init__(self, value):
            self.value = value
        def __repr__(self):
            return '<Foo>'
>>> class Bar:
        def __init__(self, value):
            self.value = value
        def __repr__(self):
            return '<Bar>'
>>> Enforce(Foo(1), '==', Foo(2), 'type_name')
>>> Enforce(Foo(1), '==', Bar(2), 'type_name')
EnforceError: type_name of <Foo> is not equal to type_name of <Bar>. Foo != Bar.
>>> class EnforceFooBar(Enforce):
    def get_value(self, item):
        return item.value
>>> EnforceFooBar(Foo(1), '==', Bar(1), 'value')
>>> EnforceFooBar(Foo(1), '==', Bar(2), 'value')
EnforceError: value of <Foo> is not equal to value of <Bar>. 1 != 2.
>>> EnforceFooBar(Foo(1), '~', Bar(5), 'value', epsilon=2)
EnforceError: value of <Foo> is not similar to value of <Bar>. Delta 4 is greater than epsilon 2.
>>> msg = '{a} is not like {b}. Please adjust your epsilon,: {epsilon}, '
>>> msg += 'to be higher than {delta}. '
>>> msg += 'A value: {a_val}. B value: {b_val}.'
>>> EnforceFooBar(Foo(1), '~', Bar(5), 'value', epsilon=2, message=msg)
<Foo> is not like <Bar>. Please adjust your epsilon: 2, to be higher than 4. A value: 1. B value: 5.
__dict__ = mappingproxy({'__module__': 'lunchbox.enforce', '__doc__': "\n    Faciltates inline testing. Super class for Enforcer subclasses.\n\n    Example:\n\n        >>> class Foo:\n                def __init__(self, value):\n                    self.value = value\n                def __repr__(self):\n                    return '<Foo>'\n        >>> class Bar:\n                def __init__(self, value):\n                    self.value = value\n                def __repr__(self):\n                    return '<Bar>'\n\n        >>> Enforce(Foo(1), '==', Foo(2), 'type_name')\n        >>> Enforce(Foo(1), '==', Bar(2), 'type_name')\n        EnforceError: type_name of <Foo> is not equal to type_name of <Bar>. Foo != Bar.\n\n        >>> class EnforceFooBar(Enforce):\n            def get_value(self, item):\n                return item.value\n        >>> EnforceFooBar(Foo(1), '==', Bar(1), 'value')\n        >>> EnforceFooBar(Foo(1), '==', Bar(2), 'value')\n        EnforceError: value of <Foo> is not equal to value of <Bar>. 1 != 2.\n        >>> EnforceFooBar(Foo(1), '~', Bar(5), 'value', epsilon=2)\n        EnforceError: value of <Foo> is not similar to value of <Bar>. Delta 4 is greater than epsilon 2.\n\n        >>> msg = '{a} is not like {b}. Please adjust your epsilon,: {epsilon}, '\n        >>> msg += 'to be higher than {delta}. '\n        >>> msg += 'A value: {a_val}. B value: {b_val}.'\n        >>> EnforceFooBar(Foo(1), '~', Bar(5), 'value', epsilon=2, message=msg)\n        <Foo> is not like <Bar>. Please adjust your epsilon: 2, to be higher than 4. A value: 1. B value: 5.\n    ", '__init__': <function Enforce.__init__>, '_get_message': <function Enforce._get_message>, 'eq': <function Enforce.eq>, 'gt': <function Enforce.gt>, 'gte': <function Enforce.gte>, 'lt': <function Enforce.lt>, 'lte': <function Enforce.lte>, 'similar': <function Enforce.similar>, 'in_': <function Enforce.in_>, 'instance_of': <function Enforce.instance_of>, 'difference': <function Enforce.difference>, 'get_type_name': <function Enforce.get_type_name>, '__dict__': <attribute '__dict__' of 'Enforce' objects>, '__weakref__': <attribute '__weakref__' of 'Enforce' objects>, '__annotations__': {}})
__init__(a, comparator, b, attribute=None, message=None, epsilon=0.01)[source]

Validates predicate specified in constructor.

Parameters:
  • a (object) – First object to be tested.

  • comparator (str) – String representation of Comparator.

  • b (object) – Second object.

  • attribute (str, optional) – Attribute name of a and b. Default: None.

  • message (str, optional) – Custom error message. Default: None.

  • epsilon (float, optional) – Error threshold for a/b difference. Default: 0.01.

Raises:

EnforceError – If predicate fails.

Returns:

Enforce instance.

Return type:

Enforce

__module__ = 'lunchbox.enforce'
__weakref__

list of weak references to the object (if defined)

_get_message(attribute, comparator)[source]

Creates an unformatted error message given an attribute name and comparator.

Parameters:
  • attribute (str or None) – Attribute name.

  • comparator (Comparator) – Comparator instance.

Returns:

Error message.

Return type:

str

difference(a, b)[source]

Calculates difference between a and b.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

Difference between a and b.

Return type:

float

eq(a, b)[source]

Determines if a and b are equal.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

True if a equals b.

Return type:

bool

get_type_name(item)[source]

Gets __class__.__name__ of given item.

Parameters:

item (object) – Item.

Returns:

item.__class__.__name__

Return type:

str

gt(a, b)[source]

Determines if a is greater than b.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

True if a is greater than b.

Return type:

bool

gte(a, b)[source]

Determines if a is greater than or equal to b.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

True if a is greater than or equal to b.

Return type:

bool

in_(a, b)[source]

Determines if a is in b.

Parameters:
  • a (object) – Member object.

  • b (list or set or tuple) – Container object.

Returns:

True if a is in b.

Return type:

bool

instance_of(a, b)[source]

Determines if a is instance of b.

Parameters:
  • a (type or list[type]) – Instance object.

  • b (object) – Class object.

Returns:

True if a is instance of b.

Return type:

bool

lt(a, b)[source]

Determines if a is lesser than b.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

True if a is lesser than b.

Return type:

bool

lte(a, b)[source]

Determines if a is lesser than or equal to b.

Parameters:
  • a (object) – First object.

  • b (object) – Second object.

Returns:

True if a is lesser than or equal to b.

Return type:

bool

similar(difference, epsilon=0.01)[source]

Determines if a/b difference given error threshold episilon.

Parameters:
  • difference (int or float) – Difference between a and b.

  • epsilon (float, optional) – Error threshold. Default: 0.01.

Returns:

True if difference is less than epsilon.

Return type:

bool

exception lunchbox.enforce.EnforceError[source]

Bases: Exception

Enforce error class.

__module__ = 'lunchbox.enforce'
__weakref__

list of weak references to the object (if defined)

singleton

class lunchbox.singleton.Singleton(*args, **kwargs)[source]

Bases: object

A super class for creating singleton classes.

__dict__ = mappingproxy({'__module__': 'lunchbox.singleton', '__doc__': '\n    A super class for creating singleton classes.\n    ', '__new__': <staticmethod(<function Singleton.__new__>)>, '__dict__': <attribute '__dict__' of 'Singleton' objects>, '__weakref__': <attribute '__weakref__' of 'Singleton' objects>, '__annotations__': {}})
__module__ = 'lunchbox.singleton'
static __new__(cls, *args, **kwargs)[source]

__new__ is called before __init__. Normaly __new__ fetches an object and __init__ initilaizes it.

In this class, __new__ checks the class body for an instance of a class, returns it if it already exists, and creates, assigns and returns it if it does not.

Returns:

Singular instance of class.

Return type:

object

__weakref__

list of weak references to the object (if defined)

stopwatch

class lunchbox.stopwatch.StopWatch[source]

Bases: object

StopWatch is used for timing blocks of code.

__dict__ = mappingproxy({'__module__': 'lunchbox.stopwatch', '__doc__': '\n    StopWatch is used for timing blocks of code.\n    ', '__init__': <function StopWatch.__init__>, 'start': <function StopWatch.start>, 'stop': <function StopWatch.stop>, 'delta': <property object>, 'human_readable_delta': <property object>, '__dict__': <attribute '__dict__' of 'StopWatch' objects>, '__weakref__': <attribute '__weakref__' of 'StopWatch' objects>, '__annotations__': {'_delta': 'Optional[datetime.timedelta]', '_start_time': 'Optional[datetime.datetime]', '_stop_time': 'Optional[datetime.datetime]'}})
__init__()[source]
__module__ = 'lunchbox.stopwatch'
__weakref__

list of weak references to the object (if defined)

property delta

Time delta of stop - start.

property human_readable_delta

Time delta in human readable format.

start()[source]

Call this method directly before the code you wish to time.

Return type:

None

stop()[source]

Call this method directly after the code you wish to time.

Return type:

None

tools

lunchbox.tools.LOGGER = <Logger lunchbox.tools (WARNING)>

A library of miscellaneous tools.

class lunchbox.tools.LogRuntime(message='', name='LogRuntime', level='info', suppress=False, message_func=None, callback=None)[source]

Bases: object

LogRuntime is a class for logging the runtime of arbitrary code.

message

Logging message with runtime line.

Type:

str

delta

Runtime.

Type:

datetime.timedelta

human_readable_delta

Runtime in human readable format.

Type:

str

Example

>>> import time
>>> def foobar():
        time.sleep(1)
>>> with LogRuntime('Foo the bars', name=foobar.__name__, level='debug'):
        foobar()
DEBUG:foobar:Foo the bars - Runtime: 0:00:01.001069 (1 second)
>>> with LogRuntime(message='Fooing all the bars', suppress=True) as log:
        foobar()
>>> print(log.message)
Fooing all the bars - Runtime: 0:00:01.001069 (1 second)
__dict__ = mappingproxy({'__module__': 'lunchbox.tools', '__doc__': "\n    LogRuntime is a class for logging the runtime of arbitrary code.\n\n    Attributes:\n        message (str): Logging message with runtime line.\n        delta (datetime.timedelta): Runtime.\n        human_readable_delta (str): Runtime in human readable format.\n\n    Example:\n\n        >>> import time\n        >>> def foobar():\n                time.sleep(1)\n\n        >>> with LogRuntime('Foo the bars', name=foobar.__name__, level='debug'):\n                foobar()\n        DEBUG:foobar:Foo the bars - Runtime: 0:00:01.001069 (1 second)\n\n        >>> with LogRuntime(message='Fooing all the bars', suppress=True) as log:\n                foobar()\n        >>> print(log.message)\n        Fooing all the bars - Runtime: 0:00:01.001069 (1 second)\n    ", '__init__': <function LogRuntime.__init__>, '_default_message_func': <staticmethod(<function LogRuntime._default_message_func>)>, '__enter__': <function LogRuntime.__enter__>, '__exit__': <function LogRuntime.__exit__>, '__dict__': <attribute '__dict__' of 'LogRuntime' objects>, '__weakref__': <attribute '__weakref__' of 'LogRuntime' objects>, '__annotations__': {}})
__enter__()[source]

Starts stopwatch.

Returns:

self.

Return type:

LogRuntime

__exit__(*args)[source]

Stops stopwatch and logs message.

Return type:

None

__init__(message='', name='LogRuntime', level='info', suppress=False, message_func=None, callback=None)[source]

Constructs a LogRuntime instance.

Parameters:
  • message (str, optional) – Logging message. Default: ‘’.

  • name (str, optional) – Name of logger. Default: ‘LogRuntime’.

  • level (str or int, optional) – Log level. Default: info.

  • suppress (bool, optional) – Whether to suppress logging. Default: False.

  • message_func (function, optional) – Custom message function of the signature (message, StopWatch) -> str. Default: None.

  • callback (function, optional) – Callback function of the signature (message) -> Any. Default: None.

Raises:
__module__ = 'lunchbox.tools'
__weakref__

list of weak references to the object (if defined)

static _default_message_func(message, stopwatch)[source]

Add runtime information to message given StopWatch instance.

Parameters:
  • message (str) – Message.

  • stopwatch (StopWatch) – StopWatch instance.

Raises:
  • EnforeceError – If Message is not a string.

  • EnforceError – If stopwatch is not a StopWatch instance.

Returns:

Message with runtime information.

Return type:

str

lunchbox.tools._dir_table(obj, public=True, semiprivate=True, private=False, max_width=100)[source]

Create a table from results of calling dir(obj).

Parameters:
  • obj (object) – Object to call dir on.

  • public (bool, optional) – Include public attributes in table. Default: True.

  • semiprivate (bool, optional) – Include semiprivate attributes in table. Default: True.

  • private (bool, optional) – Include private attributes in table. Default: False.

  • max_width (int, optional) – Maximum table width: Default: 100.

Returns:

Table.

Return type:

str

lunchbox.tools.api_function(wrapped=None, **kwargs)[source]

A decorator that enforces keyword argument only function signatures and required keyword argument values when called.

Parameters:
  • wrapped (function) – For dev use. Default: None.

  • **kwargs (dict) – Keyword arguments. # noqa: W605

Raises:
  • TypeError – If non-keyword argument found in functionn signature.

  • ValueError – If keyword arg with value of ‘<required>’ is found.

Return type:

Callable

Returns:

api function.

lunchbox.tools.dir_table(obj, public=True, semiprivate=True, private=False, max_width=100)[source]

Prints a table from results of calling dir(obj).

Parameters:
  • obj (object) – Object to call dir on.

  • public (bool, optional) – Include public attributes in table. Default: True.

  • semiprivate (bool, optional) – Include semiprivate attributes in table. Default: True.

  • private (bool, optional) – Include private attributes in table. Default: False.

  • max_width (int, optional) – Maximum table width: Default: 100.

Return type:

None

lunchbox.tools.get_function_signature(function)[source]

Inspect a given function and return its arguments as a list and its keyword arguments as a dict.

Parameters:

function (function) – Function to be inspected.

Returns:

args and kwargs.

Return type:

dict

lunchbox.tools.get_ordered_unique(items)[source]

Generates a unique list of items in same order they were received in.

Parameters:

items (list) – List of items.

Returns:

Unique ordered list.

Return type:

list

lunchbox.tools.is_standard_module(name)[source]

Determines if given module name is a python builtin.

Parameters:

name (str) – Python module name.

Returns:

Whether string names a python module.

Return type:

bool

lunchbox.tools.log_level_to_int(level)[source]

Convert a given string or integer into a log level integer.

Parameters:

level (str or int) – Log level.

Raises:

EnforceError – If level is illegal.

Returns:

Log level as integer.

Return type:

int

lunchbox.tools.log_runtime(function, *args, message_=None, _testing=False, log_level='info', **kwargs)[source]

Logs the duration of given function called with given arguments.

Parameters:
  • function (function) – Function to be called.

  • *args (object, optional) – Arguments.

  • message (str, optional) – Message to be returned. Default: None.

  • _testing (bool, optional) – Returns message if True. Default: False.

  • log_level (str, optional) – Log level. Default: info.

  • **kwargs (object, optional) – Keyword arguments.

Raises:

EnforceError – If log level is illegal.

Returns:

function(*args, **kwargs).

Return type:

object

lunchbox.tools.post_to_slack(url, channel, message)[source]

Post a given message to a given slack channel.

Parameters:
Raises:
Returns:

Response.

Return type:

HTTPResponse

lunchbox.tools.relative_path(module, path)[source]

Resolve path given current module’s file path and given suffix.

Parameters:
  • module (str or Path) – Always __file__ of current module.

  • path (str or Path) – Path relative to __file__.

Returns:

Resolved Path object.

Return type:

Path

lunchbox.tools.runtime(wrapper=None, enabled=None, adapter=None, proxy=<class 'FunctionWrapper'>)[source]

Decorator for logging the duration of given function called with given arguments.

Parameters:
  • wrapped (function) – Function to be called.

  • instance (object) – Needed by wrapt.

  • *args (object, optional) – Arguments.

  • **kwargs (object, optional) – Keyword arguments.

Returns:

Wrapped function.

Return type:

function

lunchbox.tools.to_snakecase(string)[source]

Converts a given string to snake_case.

Parameters:

string (str) – String to be converted.

Returns:

snake_case string.

Return type:

str

lunchbox.tools.truncate_blob_lists(blob, size=3)[source]

Truncates lists inside given JSON blob to a given size.

Parameters:
  • blob (dict) – Blob to be truncated.

  • size (int, optional) – Size of lists. Default 3.

Raises:

EnforceError – If blob is not a dict.

Returns:

Truncated blob.

Return type:

dict

lunchbox.tools.truncate_list(items, size=3)[source]

Truncates a given list to a given size, replaces the middle contents with “…”.

Parameters:
  • items (list) – List of objects.

  • size (int, optional) – Size of output list.

Raises:
Returns:

List of given size.

Return type:

list

lunchbox.tools.try_(function, item, return_item='item')[source]

Call given function on given item, catch any exceptions and return given return item.

Parameters:
  • function (function) – Function of signature lambda x: x.

  • item (object) – Item used to call function.

  • return_item (object, optional) – Item to be returned. Default: “item”.

Returns:

Original item if return_item is “item”. Exception: If return_item is “error”. object: Object return by function call if return_item is not “item” or

”error”.

Return type:

object