Some ideas how and for what to use function decorator part one:
the problem:
def one( *args, **kwargs ):
if kwargs['goodone'] == 1:
return 1
else:
return 0
a lot of code rely on exception handling and you must surround it with try catch...
one(123)
will raise KeyError
Do you know the tale: " Ask the lazy man to do work in and he will teach you! " или на български: Накарай мързеливия да работи за да те научи на акъл!
And here decoration or wrap will save us a lot of try-except-try-excpet spaghetti code:
# our reusable error handling function:
def error_handle( args,kwargs,e ):
print "handling error: ",repr(e)
# the make-up artist: try except python decorator
def try_wrap( func, exception_class, exception_handle ):
def wrap(*args, **kwargs):
try:
return func( *args, **kwargs )
except exception_class, e:
return exception_handle(args, kwargs, e )
return wrap
# apply the make up:
one = try_wrap(one, KeyError, error_handle)
one(123)
Няма коментари:
Публикуване на коментар