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
- 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:
- __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
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
- __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.
theme
- class lunchbox.theme.Colorscheme(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
EnumBase
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'
- __new__(value)
- class lunchbox.theme.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.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__ = 146
- __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
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', '__firstlineno__': 303, '__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__': {}})
- __firstlineno__ = 303
- __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:
EnforceError – If message is not a string.
EnforceError – If name is not a string.
EnforceError – If level is not legal logging level.
EnforceError – If suppress is not a boolean.
- __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
- 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:
- Return type:
object
- lunchbox.tools.post_to_slack(url, channel, message)[source]
Post a given message to a given slack channel.
- Parameters:
url (str) – https://hooks.slack.com/services URL.
channel (str) – Channel name.
message (str) – Message to be posted.
- Raises:
EnforceError – If URL is not a string.
EnforceError – If URL does not start with https://hooks.slack.com/services
EnforceError – If channel is not a string.
EnforceError – If message is not a string.
- 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:
EnforceError – If item is not a list.
EnforceError – If size is not an integer greater than -1.
- 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