tolerance Package

tolerance Package

tolerance

tolerance is a function decorator to make a tolerant function; a function which does not raise any exceptions even there are exceptions. This concept is quite useful for making stable product or prefer_int types of code described in Usage section.

tolerance.tolerate(substitute=None, exceptions=None, switch=<function switch_function>)[source]

A function decorator which makes a function fail silently

To disable fail silently in a decorated function, specify fail_silently=False. To disable fail silenlty in decorated functions globally, specify tolerate.disabled.

Parameters:

fn : function

A function which will be decorated.

substitute : function or returning value

A function used instead of fn or returning value when fn failed.

exceptions : list of exceptions or None

A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed.

switch : string, list/tuple, dict, function or None

A switch function which determine whether silent the function failar. The function receive *args and **kwargs which will specified to fn and should return status (bool), args, and kwargs. If the function return False then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by argument_switch_generator() with argument_switch_generator('fail_silently') so if fail_silently=False is specified to the function, the function works as noramlly.

From Version 0.1.1, when switch is specified as non functional value, argument_switch_generator() will be called with switch as arguments. If string is specified, the switch generator will be called as argument_switch_generator(switch). If list or tuple is specified, the switch generator will be called as argument_switch_generator(*switch). If dict is specified, the switch generator will be called as argument_switch_generator(**switch).

Returns:

function

A decorated function

Examples

>>> #
>>> # use tolerate as a function wrapper
>>> #
>>> parse_int = tolerate()(int)
>>> parse_int(0)
0
>>> parse_int("0")
0
>>> parse_int("zero") is None
True
>>> #
>>> # use tolerate as a function decorator (PIP-318)
>>> #
>>> @tolerate(lambda x: x)
... def prefer_int(x):
...     return int(x)
>>> prefer_int(0)
0
>>> prefer_int("0")
0
>>> prefer_int("zero")
'zero'
>>> #
>>> # filter exceptions be ignored
>>> #
>>> @tolerate(exceptions=(KeyError, ValueError))
... def force_int(x):
...     string_numbers = {
...         'zero': 0,
...         'one': 1,
...         'two': 2,
...         'three': 3,
...         'four': 4,
...         'five': 5,
...         'six': 6,
...         'seven': 7,
...         'eight': 8,
...         'nine': 9
...     }
...     if isinstance(x, (int, float)):
...         return int(x)
...     elif isinstance(x, str):
...         if x in string_numbers:
...             return string_numbers[x]
...         elif x in ('ten', 'hundred', 'thousand'):
...             raise KeyError
...         raise ValueError
...     else:
...         raise AttributeError
>>> force_int('zero')
0
>>> force_int('ten') is None    # KeyError
True
>>> force_int('foo') is None    # ValueError
True
>>> force_int(object)           # AttributeError
Traceback (most recent call last):
    ...
AttributeError
>>> #
>>> # disable tolerance by passing `fail_silently=False`
>>> #
>>> force_int('ten', fail_silently=False)   # KeyError
Traceback (most recent call last):
    ...
KeyError
>>> #
>>> # disable tolerance globally by setting `tolerate.disabled=True`
>>> #
>>> tolerate.disabled = True
>>> force_int('foo')    # ValueError
Traceback (most recent call last):
    ...
ValueError
>>> tolerate.disabled = False   # rollback
>>> #
>>> # Features from Version 0.1.1
>>> # 
>>> # specify switch as a string
>>> parse_int_string = tolerate(switch='patient')(int)
>>> parse_int_string('zero') is None
True
>>> parse_int_string('zero', patient=False)
Traceback (most recent call last):
    ...
ValueError: ...
>>> # specify switch as a list
>>> parse_int_list = tolerate(switch=['fail_silently', False])(int)
>>> parse_int_list('zero')
Traceback (most recent call last):
    ...
ValueError: ...
>>> parse_int_string('zero', fail_silently=True) is None
True
>>> # specify switch as a dict
>>> parse_int_dict = tolerate(switch={'argument_name': 'aggressive',
...                                   'reverse': True})(int)
>>> parse_int_dict('zero') is None
True
>>> parse_int_dict('zero', aggressive=False) is None
True
>>> parse_int_dict('zero', aggressive=True) is None
Traceback (most recent call last):
    ...
ValueError: ...
tolerance.argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False)[source]

Create switch function which return the status from specified named argument

Parameters:

argument_name : string or None

An argument name which is used to judge the status. If None is specified, the value of tolerance.utils.DEFAULT_ARGUMENT_NAME will be used instead.

default : boolean

A default value of this switch function. It is used when specifid **kwargs does not have named argument

reverse : boolean

Reverse the status (Default: False)

keep : boolean

If it is True, keep named argument in **kwargs.

Returns:

function

A switch function which return status, args, and kwargs respectively.

Examples

>>> #
>>> # generate switch function with default parameters
>>> #
>>> fn = argument_switch_generator('fail_silently')
>>> # return `default` value and specified *args and **kwargs when
>>> # `fail_silently` is not specified in **kwargs
>>> fn() == (True, tuple(), {})
True
>>> # return `fail_silently` value when it is specified
>>> fn(fail_silently=True) == (True, tuple(), {})
True
>>> fn(fail_silently=False) == (False, tuple(), {})
True
>>> #
>>> # generate switch function with `default=False`
>>> #
>>> fn = argument_switch_generator('fail_silently', default=False)
>>> # return `default` value so `False` is returned back
>>> fn() == (False, tuple(), {})
True
>>> #
>>> # generate switch function with `reverse=True`
>>> #
>>> fn = argument_switch_generator('fail_silently', reverse=True)
>>> # `default` value is independent from `reverse=True`
>>> fn() == (True, tuple(), {})
True
>>> # `fail_silently` value is influenced by `reverse=True`
>>> fn(fail_silently=True) == (False, tuple(), {})
True
>>> fn(fail_silently=False) == (True, tuple(), {})
True
>>> #
>>> # generate switch function with `keep=True`
>>> #
>>> fn = argument_switch_generator('fail_silently', keep=True)
>>> # `fail_silently` attribute remains even in returned back kwargs
>>> status, args, kwargs = fn(fail_silently=True)
>>> 'fail_silently' in kwargs
True

decorators Module

tolerance decorator module

tolerance.decorators.DEFAULT_TOLERATE_SWITCH(*args, **kwargs)

Default tolerate switch function

tolerance.decorators.tolerate(substitute=None, exceptions=None, switch=<function switch_function>)[source]

A function decorator which makes a function fail silently

To disable fail silently in a decorated function, specify fail_silently=False. To disable fail silenlty in decorated functions globally, specify tolerate.disabled.

Parameters:

fn : function

A function which will be decorated.

substitute : function or returning value

A function used instead of fn or returning value when fn failed.

exceptions : list of exceptions or None

A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed.

switch : string, list/tuple, dict, function or None

A switch function which determine whether silent the function failar. The function receive *args and **kwargs which will specified to fn and should return status (bool), args, and kwargs. If the function return False then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by argument_switch_generator() with argument_switch_generator('fail_silently') so if fail_silently=False is specified to the function, the function works as noramlly.

From Version 0.1.1, when switch is specified as non functional value, argument_switch_generator() will be called with switch as arguments. If string is specified, the switch generator will be called as argument_switch_generator(switch). If list or tuple is specified, the switch generator will be called as argument_switch_generator(*switch). If dict is specified, the switch generator will be called as argument_switch_generator(**switch).

Returns:

function

A decorated function

Examples

>>> #
>>> # use tolerate as a function wrapper
>>> #
>>> parse_int = tolerate()(int)
>>> parse_int(0)
0
>>> parse_int("0")
0
>>> parse_int("zero") is None
True
>>> #
>>> # use tolerate as a function decorator (PIP-318)
>>> #
>>> @tolerate(lambda x: x)
... def prefer_int(x):
...     return int(x)
>>> prefer_int(0)
0
>>> prefer_int("0")
0
>>> prefer_int("zero")
'zero'
>>> #
>>> # filter exceptions be ignored
>>> #
>>> @tolerate(exceptions=(KeyError, ValueError))
... def force_int(x):
...     string_numbers = {
...         'zero': 0,
...         'one': 1,
...         'two': 2,
...         'three': 3,
...         'four': 4,
...         'five': 5,
...         'six': 6,
...         'seven': 7,
...         'eight': 8,
...         'nine': 9
...     }
...     if isinstance(x, (int, float)):
...         return int(x)
...     elif isinstance(x, str):
...         if x in string_numbers:
...             return string_numbers[x]
...         elif x in ('ten', 'hundred', 'thousand'):
...             raise KeyError
...         raise ValueError
...     else:
...         raise AttributeError
>>> force_int('zero')
0
>>> force_int('ten') is None    # KeyError
True
>>> force_int('foo') is None    # ValueError
True
>>> force_int(object)           # AttributeError
Traceback (most recent call last):
    ...
AttributeError
>>> #
>>> # disable tolerance by passing `fail_silently=False`
>>> #
>>> force_int('ten', fail_silently=False)   # KeyError
Traceback (most recent call last):
    ...
KeyError
>>> #
>>> # disable tolerance globally by setting `tolerate.disabled=True`
>>> #
>>> tolerate.disabled = True
>>> force_int('foo')    # ValueError
Traceback (most recent call last):
    ...
ValueError
>>> tolerate.disabled = False   # rollback
>>> #
>>> # Features from Version 0.1.1
>>> # 
>>> # specify switch as a string
>>> parse_int_string = tolerate(switch='patient')(int)
>>> parse_int_string('zero') is None
True
>>> parse_int_string('zero', patient=False)
Traceback (most recent call last):
    ...
ValueError: ...
>>> # specify switch as a list
>>> parse_int_list = tolerate(switch=['fail_silently', False])(int)
>>> parse_int_list('zero')
Traceback (most recent call last):
    ...
ValueError: ...
>>> parse_int_string('zero', fail_silently=True) is None
True
>>> # specify switch as a dict
>>> parse_int_dict = tolerate(switch={'argument_name': 'aggressive',
...                                   'reverse': True})(int)
>>> parse_int_dict('zero') is None
True
>>> parse_int_dict('zero', aggressive=False) is None
True
>>> parse_int_dict('zero', aggressive=True) is None
Traceback (most recent call last):
    ...
ValueError: ...

functional Module

utils Module

tolerance utility module

tolerance.utils.argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False)[source]

Create switch function which return the status from specified named argument

Parameters:

argument_name : string or None

An argument name which is used to judge the status. If None is specified, the value of tolerance.utils.DEFAULT_ARGUMENT_NAME will be used instead.

default : boolean

A default value of this switch function. It is used when specifid **kwargs does not have named argument

reverse : boolean

Reverse the status (Default: False)

keep : boolean

If it is True, keep named argument in **kwargs.

Returns:

function

A switch function which return status, args, and kwargs respectively.

Examples

>>> #
>>> # generate switch function with default parameters
>>> #
>>> fn = argument_switch_generator('fail_silently')
>>> # return `default` value and specified *args and **kwargs when
>>> # `fail_silently` is not specified in **kwargs
>>> fn() == (True, tuple(), {})
True
>>> # return `fail_silently` value when it is specified
>>> fn(fail_silently=True) == (True, tuple(), {})
True
>>> fn(fail_silently=False) == (False, tuple(), {})
True
>>> #
>>> # generate switch function with `default=False`
>>> #
>>> fn = argument_switch_generator('fail_silently', default=False)
>>> # return `default` value so `False` is returned back
>>> fn() == (False, tuple(), {})
True
>>> #
>>> # generate switch function with `reverse=True`
>>> #
>>> fn = argument_switch_generator('fail_silently', reverse=True)
>>> # `default` value is independent from `reverse=True`
>>> fn() == (True, tuple(), {})
True
>>> # `fail_silently` value is influenced by `reverse=True`
>>> fn(fail_silently=True) == (False, tuple(), {})
True
>>> fn(fail_silently=False) == (True, tuple(), {})
True
>>> #
>>> # generate switch function with `keep=True`
>>> #
>>> fn = argument_switch_generator('fail_silently', keep=True)
>>> # `fail_silently` attribute remains even in returned back kwargs
>>> status, args, kwargs = fn(fail_silently=True)
>>> 'fail_silently' in kwargs
True