Package: tolerance
AuthorAlisue <lambdalisue@hashnote.net>Supported python versions2.6, 2.7, 3.2, 3.3, 3.4Do you often write the fail silent codes like below?try:# do what ever you need...return"foo"except:# fail silentlyreturn""This kind of codes are often found inDjangoprojects or programs which should
not raise any exceptions in product mode.toleranceis 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 orprefer_inttypes
of code described in Usage section.Checkonline documentationfor more details.FeaturesConvert a function to a tolerant functionThe decorated function returnssubstitute(Default isNone) when it
is not callable.
The function returns a “returned value” fromsubstitutefunction when
it is callable.Ignoreing exceptions can be specified as a exception class list withexceptionsargument.Whenfail_silently=Falseis passed to the decorated function,
the function does not ignore exceptions (the argument name can be changed
with making switch function viaargument_switch_generatorfunction).InstallationUsepiplike:$ pip install toleranceUsageAssume that you need a function which convert a string to an integer when it is
possible.
Without tolerance, you need to write a code like below>>># without tolerance>>>defprefer_int_withot_tolerance(x):...try:...returnint(x)...except:...# fail silently...returnx>>>prefer_int_withot_tolerance(0)0>>>prefer_int_withot_tolerance('0')0>>>prefer_int_withot_tolerance('zero')'zero'However, with tolerance, you just need to write a single line code like>>>fromtoleranceimporttolerate>>>prefer_int=tolerate(lambdax:x)(int)>>>prefer_int(0)0>>>prefer_int('0')0>>>prefer_int('zero')'zero'Or you can usetolerateas a function decorator described inPEP-318>>>fromtoleranceimporttolerate>>>@tolerate(lambdax:x)...defprefer_int_318(x):...returnint(x)>>>prefer_int_318(0)0>>>prefer_int_318('0')0>>>prefer_int_318('zero')'zero'The example codes above  specifysubstituteargument oftoleratefunction to specify the returning value when the function has failed (lambda x: xpart).toleratefunction takes several arguments to configure the function
behavior.
These arguments are explained in Case study and detailed in API documentation.Change logVersion 0.1.0Initial developmentManually tested with Python 2.4, 2.5, 2.7, 3.2, 3.3Version 0.1.1switchshortcut feature is addedDrop off supporting Python 2.4 and 2.5Support Python 3.2 and 3.3 via 2to3Usetoxfor testingCase studyQ. How can I return the default value when the function fail?Usesubstituteargument to specify the default value like>>>fromtoleranceimporttolerate>>>@tolerate(substitute='foo')...defraise_exception():...raiseException>>>raise_exception()'foo'Q. How can I change the default value depends on passed arguments?Specifysubstituteargument as a function>>>fromtoleranceimporttolerate>>>defsubstitute_function(*args,**kwargs):...# do what ever you need, this example simply return 1st argument...returnargs[0]>>>@tolerate(substitute=substitute_function)...defraise_exception(*args):...raiseException>>>raise_exception('bar','hoge')'bar'Q. How can I make the function to ignore only several exceptions?Useexceptionsargument to specify exceptions which will be ignored.>>>fromtoleranceimporttolerate>>>exceptions_ignored=(...AttributeError,...ValueError,...)>>>@tolerate(exceptions=exceptions_ignored)...defraise_exception(x):...ifx==0:...raiseAttributeError...elifx==1:...raiseValueError...else:...raiseKeyError>>>raise_exception(0)isNoneTrue>>>raise_exception(1)isNoneTrue>>>raise_exception(2)Traceback(mostrecentcalllast):...KeyErrorQ. How can I disable ignoreing exceptions in the decorated function?Passfail_silently=Falseto the decorated function.>>>fromtoleranceimporttolerate>>>@tolerate()...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>raise_exception(fail_silently=False)Traceback(mostrecentcalllast):...KeyErrorYou can change the attribute name with specifing new switch function.
It will be explained below.Q. How can I disable ignoreing exceptions globally?Settolerate.disabled = Trueto disable tolerance globally.>>>fromtoleranceimporttolerate>>>@tolerate()...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>tolerate.disabled=True>>>raise_exception()Traceback(mostrecentcalllast):...KeyError>>># rollback>>>tolerate.disabled=FalseQ. How can I disable ignoreing exceptions in complex mannar?Useswitchargument to specify switch function.>>>fromtoleranceimporttolerate>>>DEBUG=False>>>defswitch_function(*args,**kwargs):...# do what ever you need, this sample check kwargs and DEBUG...# remove 'fail_silently' attribute and store...fail_silently=kwargs.pop('fail_silently',True)...ifDEBUGornotfail_silently:...# do not ignore exceptions. note that kwargs which does not...# have 'fail_silently' is returned back....returnFalse,args,kwargs...# do ignore exceptions. note that kwargs which does not have...# 'fail_silently' is returned back....returnTrue,args,kwargs>>>@tolerate(switch=switch_function)...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>raise_exception(fail_silently=False)Traceback(mostrecentcalllast):...KeyError>>>DEBUG=True>>>raise_exception()Traceback(mostrecentcalllast):...KeyErrorQ. I just want to change the attribute name, making switch function is too complicatedUseargument_switch_generatorto make switch function.>>>fromtoleranceimporttolerate>>>fromtoleranceimportargument_switch_generator>>>switch_function=argument_switch_generator('quiet')>>>@tolerate(switch=switch_function)...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>># you can use `quiet=False` instead of `fail_silently`>>>raise_exception(quiet=False)Traceback(mostrecentcalllast):...KeyError>>># raise_exception does not know fail_silently so ignore>>>raise_exception(fail_silently=False)isNoneTrue>>>#>>># From Version 0.1.1>>>#>>>@tolerate(switch='quiet')...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>raise_exception(quiet=False)Traceback(mostrecentcalllast):...KeyError>>>raise_exception(fail_silently=False)isNoneTrueNoteFrom Version 0.1.1, you can simply specify the argument name toswitchargument and thentolerantfunction will callargument_switch_generatorinternally with the specified name.See detailed informations on API documentationQ. I want to make the function ignoreing exceptions only whenfail_silently=Trueis passedUsedefaultargument to tellargument_switch_generatorfunction>>>fromtoleranceimporttolerate>>>fromtoleranceimportargument_switch_generator>>>switch_function=argument_switch_generator('fail_silently',default=False)>>>@tolerate(switch=switch_function)...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTraceback(mostrecentcalllast):...KeyError>>>raise_exception(fail_silently=True)isNoneTrue>>>#>>># From Version 0.1.1>>>#>>>@tolerate(switch=[None,False])...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTraceback(mostrecentcalllast):...KeyError>>>@tolerate(switch={'default':False})...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTraceback(mostrecentcalllast):...KeyErrorNoteFrom Version 0.1.1, you can simply specify*argsor**kwargsofargument_switch_generatortoswitchargument andtolerantfunction will callargument_switch_generatorinternally with the
specified arguments.See detailed informations on API documentationQ. I want to disable the ignoreing exceptions whenverbose=Falseis passedUsereverseargument to tellargument_switch_generatorfunction>>>fromtoleranceimporttolerate>>>fromtoleranceimportargument_switch_generator>>>switch_function=argument_switch_generator('verbose',reverse=True)>>>@tolerate(switch=switch_function)...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>raise_exception(verbose=True)Traceback(mostrecentcalllast):...KeyError>>>#>>># From Version 0.1.1>>>#>>>@tolerate(switch={'argument_name':'verbose','reverse':True})...defraise_exception():...raiseKeyError>>>raise_exception()isNoneTrue>>>raise_exception(verbose=True)Traceback(mostrecentcalllast):...KeyErrorQ. I want to usefail_silentlyargument even in decorated functionUsekeepargument to tellargument_switch_generatorfunction>>>fromtoleranceimporttolerate>>>fromtoleranceimportargument_switch_generator>>>switch_function=argument_switch_generator('fail_silently',keep=True)>>>@tolerate(switch=switch_function)...defraise_exception(**kwargs):...if'fail_silently'inkwargs:...raiseKeyError...return'Failed!'>>>raise_exception(fail_silently=True)isNoneTrue>>>raise_exception(fail_silently=False)Traceback(mostrecentcalllast):...KeyError>>>#>>># From Version 0.1.1>>>#>>>@tolerate(switch={'keep':True})...defraise_exception(**kwargs):...if'fail_silently'inkwargs:...raiseKeyError...return'Failed!'>>>raise_exception(fail_silently=True)isNoneTrue>>>raise_exception(fail_silently=False)Traceback(mostrecentcalllast):...KeyError