python - How to catch an exception in a decorator -


i have function cause exception , want decorator. code follow:

def des(i):     def new_func(func):         if == 1:             raise exception         else:             return func     return new_func   @des(1) def func():     print "!!"   if __name__ == '__main__':     try:         func()     except exception:         print 'error' 

but output is:

traceback (most recent call last):   file "d:/des.py", line 10, in <module>     @des(1)   file "d:/des.py", line 4, in new_func     raise exception exception 

so, how can catch exception?

as other answers have explained, current issue you're getting exception raised when decorator applied function, not when function called.

to fix this, need make decorator return function exception raising. here's how work:

import functools  def des(i):     def decorator(func):         if != 1:             return func # no wrapper needed          @functools.wraps(func)         def raiser(*args, **kwargs):             raise exception          return raiser      return decorator 

the des function "decorator factory". doesn't doesn't other providing scope hold i parameter decorator returns.

the decorator function check see if special needs done. if not, returns decorated function unmodified. if i==1, returns custom function.

the raiser function decorator's return value if i==1. raises exception when called. functools.wraps decorator applied not strictly necessary, makes more original function (same __name__, __doc__, etc).


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -