enforce

class lunchbox.enforce.Comparator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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: str

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', '__firstlineno__': 102, '__doc__': "\nFaciltates inline testing. Super class for Enforcer subclasses.\n\nExample:\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>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'Enforce' objects>, '__weakref__': <attribute '__weakref__' of 'Enforce' objects>, '__annotations__': {}})
__firstlineno__ = 102
__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'
__static_attributes__ = ()
__weakref__

list of weak references to the object

_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.

__firstlineno__ = 94
__module__ = 'lunchbox.enforce'
__static_attributes__ = ()
__weakref__

list of weak references to the object

lunchbox.enforce.enforce_homogenous_type(iterable, name='Iterable')[source]

Ensures that iterable only contains only one type of object.

Parameters:
  • items (iterable) – Iterable.

  • name (str, optional) – First word in error message. Default: Iterable.

Raises:

EnforceError – If iterable contains more than one type of object.

Return type:

None

enum

class lunchbox.enum.EnumBase(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Base class for enums.

__module__ = 'lunchbox.enum'
__repr__()[source]

str: String representation.

Return type:

str

classmethod from_string(string)[source]

Returns enum from a given string.

Parameters:

string (str) – String.

Raises:

ValueError – If illegal string is given.

Returns:

Enum.

Return type:

enum

classmethod members()[source]

Returns list of enum members.

Returns:

List of enum members.

Return type:

list[Any]

classmethod options()[source]

Returns list of enum options.

Returns:

List of enum options.

Return type:

list[Any]

classmethod to_dict()[source]

Convert enum to a dictionary.

Returns:

(name, value) dictionary.

Return type:

dict

class lunchbox.enum.EnumBaseMeta(cls, bases, classdict, *, boundary=None, _simple=False, **kwds)[source]

Bases: EnumType

__annotations__ = {}
__firstlineno__ = 7
__module__ = 'lunchbox.enum'
__repr__()[source]

str: String representation.

__static_attributes__ = ()

infix

class lunchbox.infix.AllInfix(*args, **kwargs)[source]

Bases: ArithmeticInfix, MathInfix, LogicInfix, ComparisonInfix, BitwiseInfix, ItemInfix, UnaryInfix, EqualityInfix, AssignmentInfix, MiscInfix

Infix class for all of the following operators:

Key

Function

From Class

+

add

ArithmeticInfix

r+

add (right)

ArithmeticInfix

-

subtract

ArithmeticInfix

r-

subtract (right)

ArithmeticInfix

*

multiply

ArithmeticInfix

r*

multiply (right)

ArithmeticInfix

/

divide

ArithmeticInfix

r/

divide (right)

ArithmeticInfix

%

modulo

MathInfix

r%

modulo (right)

MathInfix

//

floor divide

MathInfix

r//

floor divide (right)

MathInfix

**

exponentiate

MathInfix

r**

exponentiate (right)

MathInfix

@

matrix multiply

MathInfix

r@

matrix multiply (right)

MathInfix

&

and

LogicInfix

r&

and (right)

LogicInfix

|

or

LogicInfix

r|

or (right)

LogicInfix

^

exclusive or

LogicInfix

r^

exclusive or (right)

LogicInfix

<

less than

ComparisonInfix

<=

less than or equal

ComparisonInfix

>

greater than

ComparisonInfix

>=

greater than or equal

ComparisonInfix

>>

right bit shift

BitwiseInfix

r>>

right bit shift (right)

BitwiseInfix

<<

left bit shift

BitwiseInfix

r<<

left bit shift (right)

BitwiseInfix

[]

get item

ItemInfix

[] =

set item

ItemInfix

[missing]

missing item

ItemInfix

del []

delete item

ItemInfix

~

invert

UnaryInfix

x-

negative

UnaryInfix

x+

positive

UnaryInfix

==

equal

EqualityInfix

!=

not equal

EqualityInfix

+=

add and assign

AssignmentInfix

-=

subtract and assign

AssignmentInfix

*=

multiply and assign

AssignmentInfix

/=

divide and assign

AssignmentInfix

%=

modulo and assign

AssignmentInfix

//=

floor divide and assign

AssignmentInfix

**=

pow and assign

AssignmentInfix

@=

matrix multiply and assign

AssignmentInfix

&=

and and assign

AssignmentInfix

|=

or and assign

AssignmentInfix

^=

exclusive or and assign

AssignmentInfix

>>=

right bit shift and assign

AssignmentInfix

<<=

left bit shift and assign

AssignmentInfix

del .

delete attribute

MiscInfix

in

contains

MiscInfix

__firstlineno__ = 902
__module__ = 'lunchbox.infix'
__static_attributes__ = ()
class lunchbox.infix.ArithmeticInfix(*args, **kwargs)[source]

Bases: InfixBase

Infix class for infix operators: +, -, *, /

__add__(value)[source]

Add (+).

Parameters:

value (object) – Value.

Returns:

Self ADD value.

Return type:

object

__annotations__ = {}
__firstlineno__ = 38
__init__(*args, **kwargs)[source]

Construct ArithmeticInfix instance.

__module__ = 'lunchbox.infix'
__mul__(value)[source]

Multiply (*).

Parameters:

value (object) – Value.

Returns:

Self MULTIPLY value.

Return type:

object

__radd__(value)[source]

Add (+).

Parameters:

value (object) – Value.

Returns:

Value ADD self.

Return type:

object

__rmul__(value)[source]

Multiply (*).

Parameters:

value (object) – Value.

Returns:

Value MULTIPLY self.

Return type:

object

__rsub__(value)[source]

Subtract (-).

Parameters:

value (object) – Value.

Returns:

Value SUBTRACT self.

Return type:

object

__rtruediv__(value)[source]

Divide (/).

Parameters:

value (object) – Value.

Returns:

Value DIVIDE self.

Return type:

object

__static_attributes__ = ()
__sub__(value)[source]

Subtract (-).

Parameters:

value (object) – Value.

Returns:

Self SUBTRACT value.

Return type:

object

__truediv__(value)[source]

Divide (/).

Parameters:

value (object) – Value.

Returns:

Self DIVIDE value.

Return type:

object

class lunchbox.infix.AssignmentInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__firstlineno__ = 669
__iadd__(value)[source]

Add and assign (+=).

Parameters:

value (object) – Value.

Returns:

Assign self ADD value.

Return type:

object

__iand__(value)[source]

And and assign (&=).

Parameters:

value (object) – Value.

Returns:

Assign self AND value.

Return type:

object

__ifloordiv__(value)[source]

Floor divide and assign (//=).

Parameters:

value (object) – Value.

Returns:

Assign self FLOOR value.

Return type:

object

__ilshift__(value)[source]

Left bit shift and assign (<<=).

Parameters:

value (object) – Value.

Returns:

Assign self LEFT value.

Return type:

(<object

__imatmul__(value)[source]

Matrix multiply and assign (@=).

Parameters:

value (object) – Value.

Returns:

Assign self MATRIX MULTIPLY value.

Return type:

n (@object

__imod__(value)[source]

Modulo and assign (%=).

Parameters:

value (object) – Value.

Returns:

Assign self MODULO value.

Return type:

object

__imul__(value)[source]

Multiply and assign (*=)

Parameters:

value (object) – Value.

Returns:

Assign self MULTIPLY value.

Return type:

object

__init__(*args, **kwargs)[source]

Infix class for assignment operators: +=, -=, *=, /=, %=, //=, **=, @=, &=, |=, ^=, >>=, <<=

__ior__(value)[source]

Or and assign (|=).

Parameters:

value (object) – Value.

Returns:

Assign self OR value.

Return type:

object

__ipow__(value)[source]

Exponentiate and assign (**=).

Parameters:

value (object) – Value.

Returns:

Assign self EXPONENTIATE value.

Return type:

object

__irshift__(value)[source]

Right bit shift and assign (>>=).

Parameters:

value (object) – Value.

Returns:

Assign self RIGHT value.

Return type:

n (>>object

__isub__(value)[source]

Subtract and assign (-=).

Parameters:

value (object) – Value.

Returns:

Assign self SUBTRACT value.

Return type:

object

__itruediv__(value)[source]

Divide and assign (/=).

Parameters:

value (object) – Value.

Returns:

Assign self DIVIDE value.

Return type:

object

__ixor__(value)[source]

Exclusive or and assign (^=).

Parameters:

value (object) – Value.

Returns:

Assign self EXCLUSIVE value.

Return type:

n (^object

__module__ = 'lunchbox.infix'
__static_attributes__ = ()
class lunchbox.infix.BitwiseInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__firstlineno__ = 449
__init__(*args, **kwargs)[source]

Infix class for infix operators: <<, >>

__lshift__(value)[source]

Left bit shift (<<).

Parameters:

value (object) – Value.

Returns:

Self LEFT BIT SHIFT value.

Return type:

object

__module__ = 'lunchbox.infix'
__rlshift__(value)[source]

Left bit shift (<<).

Parameters:

value (object) – Value.

Returns:

Value LEFT BIT SHIFT self.

Return type:

object

__rrshift__(value)[source]

Right bit shift (>>).

Parameters:

value (object) – Value.

Returns:

Value RIGHT BIT SHIFT self.

Return type:

object

__rshift__(value)[source]

Right bit shift (>>).

Parameters:

value (object) – Value.

Returns:

Value RIGHT BIT SHIFT self.

Return type:

object

__static_attributes__ = ()
class lunchbox.infix.ComparisonInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__firstlineno__ = 382
__ge__(value)[source]

Greater than or equa.

Parameters:

value (object) – Value.

Returns:

Self GREATER THAN OR EQUAL TO value.

Return type:

object

__gt__(value)[source]

Greater than (>).

Parameters:

value (object) – Value.

Returns:

Self GREATER THAN value.

Return type:

object

__init__(*args, **kwargs)[source]

Infix class for infix operators: <, <=, >, >=

__le__(value)[source]

Less than or equal (.

Parameters:

value (object) – Value.

Returns:

Self LESS THAN OR EQUAL TO value.

Return type:

object

__lt__(value)[source]

Less than (<).

Parameters:

value (object) – Value.

Returns:

Self LESS THAN value.

Return type:

object

__module__ = 'lunchbox.infix'
__static_attributes__ = ()
class lunchbox.infix.EqualityInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__eq__(value)[source]

Equal (==).

Parameters:

value (object) – Value.

Returns:

Self EQUAL value.

Return type:

object

__firstlineno__ = 630
__hash__ = None
__init__(*args, **kwargs)[source]

Infix class for infix operators: ==, !=

__module__ = 'lunchbox.infix'
__ne__(value)[source]

Not equal (!=).

Parameters:

value (object) – Value.

Returns:

Self NOT EQUAL value.

Return type:

object

__static_attributes__ = ()
class lunchbox.infix.InfixBase(*args, **kwargs)[source]

Bases: object

InfixBase is used for declaring a mapping between infix operators and class methods, using _infix_lookup.

__annotations__ = {}
__dict__ = mappingproxy({'__module__': 'lunchbox.infix', '__firstlineno__': 5, '__doc__': '\nInfixBase is used for declaring a mapping between infix operators and class\nmethods, using _infix_lookup.\n', '__init__': <function InfixBase.__init__>, '_get_infix_function': <function InfixBase._get_infix_function>, '__static_attributes__': ('_infix_lookup',), '__dict__': <attribute '__dict__' of 'InfixBase' objects>, '__weakref__': <attribute '__weakref__' of 'InfixBase' objects>, '__annotations__': {'_infix_lookup': 'dict[str, str]'}})
__firstlineno__ = 5
__init__(*args, **kwargs)[source]

Construct Infix instance.

__module__ = 'lunchbox.infix'
__static_attributes__ = ('_infix_lookup',)
__weakref__

list of weak references to the object

_get_infix_function(symbol)[source]

Get infix function from lookup table.

Parameters:

symbol (str) – Lookup table symbol.

Returns:

Infix function.

Return type:

callable

class lunchbox.infix.ItemInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__delitem__(key)[source]

Delete item (del x[key]).

Parameters:

key (object) – Key.

Returns:

Self DELETE key.

Return type:

object

__firstlineno__ = 516
__getitem__(key)[source]

Get item ([]).

Parameters:

key (object) – Key.

Returns:

Self GET ITEM key.

Return type:

object

__init__(*args, **kwargs)[source]

Infix class for infix operators: [], [] =, del [], [missing]

__missing__(key)[source]

Missing item ([]). When __getitem__ looks for a non-existent key.

Parameters:

key (object) – Key.

Returns:

Self MISSING key.

Return type:

object

__module__ = 'lunchbox.infix'
__setitem__(key, value)[source]

Set item (x[key] = value).

Parameters:
  • key (object) – Key.

  • value (object) – Value.

Returns:

Self SET ITEM value.

Return type:

object

__static_attributes__ = ()
class lunchbox.infix.LogicInfix(*args, **kwargs)[source]

Bases: InfixBase

__and__(value)[source]

And (&).

Parameters:

value (object) – Value.

Returns:

Self AND value.

Return type:

object

__annotations__ = {}
__firstlineno__ = 287
__init__(*args, **kwargs)[source]

Infix class for infix operators: &, |, ^

__module__ = 'lunchbox.infix'
__or__(value)[source]

Or (|).

Parameters:

value (object) – Value.

Returns:

Self OR value.

Return type:

object

__rand__(value)[source]

And (&).

Parameters:

value (object) – Value.

Returns:

Value AND self.

Return type:

object

__ror__(value)[source]

Or (|).

Parameters:

value (object) – Value.

Returns:

Value OR self.

Return type:

object

__rxor__(value)[source]

Exclusive or (^).

Parameters:

value (object) – Value.

Returns:

Value EXCLUSIVE self.

Return type:

object

__static_attributes__ = ()
__xor__(value)[source]

Exclusive or (^).

Parameters:

value (object) – Value.

Returns:

Self EXCLUSIVE value.

Return type:

object

class lunchbox.infix.MathInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__firstlineno__ = 164
__floordiv__(value)[source]

Floor divide (//).

Parameters:

value (object) – Value.

Returns:

Self FLOOR DIVIDE value.

Return type:

object

__init__(*args, **kwargs)[source]

Infix class for infix operators: %, //, **, @

__matmul__(value)[source]

Matrix multiply (@).

Parameters:

value (object) – Value.

Returns:

Self MATRIX MULTIPLY value.

Return type:

object

__mod__(value)[source]

Modulo (%).

Parameters:

value (object) – Value.

Returns:

Self MODULO value.

Return type:

object

__module__ = 'lunchbox.infix'
__pow__(value)[source]

Exponentiate (**).

Parameters:

value (object) – Value.

Returns:

Self EXPONENTIATE value.

Return type:

object

__rfloordiv__(value)[source]

Floor divide (//).

Parameters:

value (object) – Value.

Returns:

Value FLOOR DIVIDE self.

Return type:

object

__rmatmul__(value)[source]

Matrix multiply (@).

Parameters:

value (object) – Value.

Returns:

Value MATRIX MULTIPLY self.

Return type:

object

__rmod__(value)[source]

Modulo (%).

Parameters:

value (object) – Value.

Returns:

Value MODULO self.

Return type:

object

__rpow__(value)[source]

Exponentiate (**).

Parameters:

value (object) – Value.

Returns:

Value EXPONENTIATE self.

Return type:

object

__static_attributes__ = ()
class lunchbox.infix.MiscInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__contains__(value)[source]

Contains (in).

Parameters:

value (object) – Value.

Returns:

Value CONTAINS self.

Return type:

object

__delattr__(value)[source]

Delete attribute (del x.attr).

Parameters:

value (object) – Value.

Returns:

Self DELETE value.

Return type:

object

__firstlineno__ = 863
__init__(*args, **kwargs)[source]

Infix class for operators: del x.attr, in

__module__ = 'lunchbox.infix'
__static_attributes__ = ()
class lunchbox.infix.UnaryInfix(*args, **kwargs)[source]

Bases: InfixBase

__annotations__ = {}
__firstlineno__ = 587
__init__(*args, **kwargs)[source]

Infix class for unary operators: ~, -, +

__invert__()[source]

Invert (~).

Returns:

INVERT self.

Return type:

object

__module__ = 'lunchbox.infix'
__neg__()[source]

Negative (-).

Returns:

NEGATIVE self.

Return type:

object

__pos__()[source]

Positive (+).

Returns:

POSITIVE self.

Return type:

object

__static_attributes__ = ()
class lunchbox.infix.UtiltyInfix(*args, **kwargs)[source]

Bases: ArithmeticInfix, MathInfix, LogicInfix, ComparisonInfix, BitwiseInfix, ItemInfix, UnaryInfix

Infix class for all of the following operators:

Key

Function

From Class

+

add

ArithmeticInfix

r+

add (right)

ArithmeticInfix

-

subtract

ArithmeticInfix

r-

subtract (right)

ArithmeticInfix

*

multiply

ArithmeticInfix

r*

multiply (right)

ArithmeticInfix

/

divide

ArithmeticInfix

r/

divide (right)

ArithmeticInfix

%

modulo

MathInfix

r%

modulo (right)

MathInfix

//

floor divide

MathInfix

r//

floor divide (right)

MathInfix

**

exponentiate

MathInfix

r**

exponentiate (right)

MathInfix

@

matrix multiply

MathInfix

r@

matrix multiply (right)

MathInfix

&

and

LogicInfix

r&

and (right)

LogicInfix

|

or

LogicInfix

r|

or (right)

LogicInfix

^

exclusive or

LogicInfix

r^

exclusive or (right)

LogicInfix

<

less than

ComparisonInfix

<=

less than or equal

ComparisonInfix

>

greater than

ComparisonInfix

>=

greater than or equal

ComparisonInfix

>>

right bit shift

BitwiseInfix

r>>

right bit shift (right)

BitwiseInfix

<<

left bit shift

BitwiseInfix

r<<

left bit shift (right)

BitwiseInfix

[]

get item

ItemInfix

[] =

set item

ItemInfix

[missing]

missing item

ItemInfix

del []

delete item

ItemInfix

~

invert

UnaryInfix

x-

negative

UnaryInfix

x+

positive

UnaryInfix

__annotations__ = {}
__firstlineno__ = 979
__module__ = 'lunchbox.infix'
__static_attributes__ = ()

singleton

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

Bases: object

A super class for creating singleton classes.

__dict__ = mappingproxy({'__module__': 'lunchbox.singleton', '__firstlineno__': 1, '__doc__': '\nA super class for creating singleton classes.\n', '__new__': <staticmethod(<function Singleton.__new__>)>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'Singleton' objects>, '__weakref__': <attribute '__weakref__' of 'Singleton' objects>, '__annotations__': {}})
__firstlineno__ = 1
__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

__static_attributes__ = ()
__weakref__

list of weak references to the object

stopwatch

class lunchbox.stopwatch.StopWatch[source]

Bases: object

StopWatch is used for timing blocks of code.

__dict__ = mappingproxy({'__module__': 'lunchbox.stopwatch', '__firstlineno__': 8, '__doc__': '\nStopWatch 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>, '__static_attributes__': ('_delta', '_start_time', '_stop_time'), '__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]'}})
__firstlineno__ = 8
__init__()[source]
__module__ = 'lunchbox.stopwatch'
__static_attributes__ = ('_delta', '_start_time', '_stop_time')
__weakref__

list of weak references to the object

property delta: timedelta

Time delta of stop - start.

property human_readable_delta: str

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

theme

class lunchbox.theme.Colorscheme(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Henanigans color scheme.

BG = '#242424'
BLUE1 = '#5F95DE'
BLUE2 = '#93B6E6'
CYAN1 = '#7EC4CF'
CYAN2 = '#B6ECF3'
DARK1 = '#040404'
DARK2 = '#181818'
DIALOG1 = '#444459'
DIALOG2 = '#5D5D7A'
GREEN1 = '#8BD155'
GREEN2 = '#A0D17B'
GREY1 = '#343434'
GREY2 = '#444444'
LIGHT1 = '#A4A4A4'
LIGHT2 = '#F4F4F4'
ORANGE1 = '#EB9E58'
ORANGE2 = '#EBB483'
PURPLE1 = '#C98FDE'
PURPLE2 = '#AC92DE'
RED1 = '#F77E70'
RED2 = '#DE958E'
YELLOW1 = '#E8EA7E'
YELLOW2 = '#E9EABE'
__module__ = 'lunchbox.theme'
class lunchbox.theme.TerminalColorscheme(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: EnumBase

Terminal color scheme.

BLUE1 = '\x1b[0;34m'
BLUE2 = '\x1b[0;94m'
CLEAR = '\x1b[0m'
CYAN1 = '\x1b[0;36m'
CYAN2 = '\x1b[0;96m'
GREEN1 = '\x1b[0;32m'
GREEN2 = '\x1b[0;92m'
GREY1 = '\x1b[0;90m'
GREY2 = '\x1b[0;37m'
PURPLE1 = '\x1b[0;35m'
PURPLE2 = '\x1b[0;95m'
RED1 = '\x1b[0;31m'
RED2 = '\x1b[0;91m'
WHITE = '\x1b[1;97m'
YELLOW1 = '\x1b[0;33m'
YELLOW2 = '\x1b[0;93m'
__module__ = 'lunchbox.theme'
__new__(value)
class lunchbox.theme.ThemeFormatter(*args, heading_color='blue2', command_color='cyan2', flag_color='green2', grayscale=False, **kwargs)[source]

Bases: HelpFormatter

ThemeFormatter makes click CLI output prettier.

Include the following code to add it to click:

import lunchbox.theme as lbc
click.Context.formatter_class = lbc.ThemeFormatter
__firstlineno__ = 132
__init__(*args, heading_color='blue2', command_color='cyan2', flag_color='green2', grayscale=False, **kwargs)[source]

Constructs a ThemeFormatter instance for use with click.

Parameters:
  • *args (optional) – Positional arguments.

  • heading_color (str, optional) – Heading color. Default: blue2.

  • command_color (str, optional) – Command color. Default: cyan2.

  • flag_color (str, optional) – Flag color. Default: green2.

  • grayscale (bool, optional) – Grayscale colors only. Default: False.

  • **kwargs (optional) – Keyword arguments.

__module__ = 'lunchbox.theme'
__static_attributes__ = ('_colors', '_command_color', '_flag_color', '_heading_color', '_line_width', '_sep', '_write_calls', 'current_indent')
write_dl(rows, col_max=30, col_spacing=2)[source]

Writes a definition list into the buffer. This is how options and commands are usually formatted.

Parameters:
  • rows (list) – List of (term, value) tuples.

  • col_max (int, optional) – Maximum width of first column. Default: 30.

  • col_spacing (int, optional) – Spacing between first and second columns. Default: 2.

Return type:

None

write_heading(heading)[source]

Write section heading into buffer.

Commands is converted to COMMANDS. Options is converted to FLAGS.

Parameters:

heading (str) – Heading text.

Return type:

None

write_text(text)[source]

Writes re-indented text into the buffer. This rewraps and preserves paragraphs.

Parameters:

text (str) – Text to write.

Return type:

None

write_usage(prog, *args, **kwargs)[source]

Writes a usage line into the buffer.

Parameters:
  • prog (str) – Program name.

  • *args (optional) – Positional arguments.

  • **kwargs (optional) – Keyword arguments.

Return type:

None

lunchbox.theme.get_plotly_template(colorscheme=<enum 'Colorscheme'>)[source]

Create a plotly template from a given color scheme.

Parameters:

colorscheme (colorscheme) – colorscheme enum.

Returns:

Plotly template.

Return type:

dict

tools

lunchbox.tools.FilePath = pathlib._local.Path | str

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', '__firstlineno__': 305, '__doc__': "\nLogRuntime is a class for logging the runtime of arbitrary code.\n\nAttributes:\n    message (str): Logging message with runtime line.\n    delta (datetime.timedelta): Runtime.\n    human_readable_delta (str): Runtime in human readable format.\n\nExample:\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__>, '__static_attributes__': ('_callback', '_level', '_logger', '_message', '_message_func', '_stopwatch', '_suppress', 'delta', 'human_readable_delta', 'message'), '__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

__firstlineno__ = 305
__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'
__static_attributes__ = ('_callback', '_level', '_logger', '_message', '_message_func', '_stopwatch', '_suppress', 'delta', 'human_readable_delta', 'message')
__weakref__

list of weak references to the object

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

class lunchbox.tools.RegexMatch(string)[source]

Bases: object

A convenience class for using regular expressions in match statements.

__dict__ = mappingproxy({'__module__': 'lunchbox.tools', '__firstlineno__': 730, '__doc__': '\nA convenience class for using regular expressions in match statements.\n', '__init__': <function RegexMatch.__init__>, '__eq__': <function RegexMatch.__eq__>, '__static_attributes__': ('string',), '__dict__': <attribute '__dict__' of 'RegexMatch' objects>, '__weakref__': <attribute '__weakref__' of 'RegexMatch' objects>, '__hash__': None, '__annotations__': {}})
__eq__(pattern)[source]

Check if string matches pattern.

Parameters:

pattern (str) – Regular expression pattern.

Returns:

True if string matches pattern.

Return type:

bool

__firstlineno__ = 730
__hash__ = None
__init__(string)[source]

Construct a RegexMatch instance.

Parameters:

string (str) – String to match pattern against.

__module__ = 'lunchbox.tools'
__static_attributes__ = ('string',)
__weakref__

list of weak references to the object

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.

Returns:

api function.

lunchbox.tools.autoformat_block(text)[source]

Determine block indentation and format text block with 0 indentation.

Parameters:

text (str) – Text.

Returns:

Dedented text.

Return type:

str

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.format_block(text, dedent=0, indent=0, collapse=True)[source]

Format text block by a given indent. Also strips leading and trailing newlines.

Parameters:
  • text (str) – Text to be indented.

  • dedent (int, optional) – Amount of indent to be removed. Default: 0.

  • indent (int, optional) – Amount of indent. Default: 0.

  • collapse (bool, optional) – If text is just whitespace, return a null string. Default: True.

Returns:

Indented text.

Return type:

str

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.str_to_bool(string)[source]

Converts a string to a boolean value.

Parameters:

string (str) – String to be converted.

Returns:

Boolean

Return type:

bool

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.traverse_directory(directory, include_regex='', exclude_regex='', entry_type='file')[source]

Recusively list all files or directories within a given directory.

Parameters:
  • directory (str or Path) – Directory to walk.

  • include_regex (str, optional) – Include filenames that match this regex. Default: ‘’.

  • exclude_regex (str, optional) – Exclude filenames that match this regex. Default: ‘’.

  • entry_type (str, optional) – Kind of directory entry to return. Options include: file, directory. Default: file.

Raises:
  • FileNotFoundError – If argument is not a directory or does not exist.

  • EnforceError – If entry_type is not file or directory.

Yields:

Path – File.

Return type:

Generator[Path, None, None]

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