Functions that raise exceptions.

Duncan Booth duncan.booth at invalid.invalid
Wed Jun 25 17:00:38 EDT 2008


Alex G <alexander.girman at gmail.com> wrote:

> class classA(object):
>     @decorator('argument')
>     def some_method(self):
>         print "An exception should be raised when I'm called, but not
> when I'm defined"
> 
> Will result in an exception on definition.

Well, yes it would. That's because what you defined a decorator. i.e. a 
function which wraps the method in another function. A decorator is called 
with a single argument: the function/method to be wrapped.

What you have done in the code above is to call something named 'decorator' 
which isn't a decorator at all, it's a function that you expect to return a 
decorator (a decorator factory if you wish). If you make it return a 
decorator then it will all work fine:

>>> def decoratorfactory(s):
    def decorator(arg):
        def raise_exception(fn):
            raise Exception
        return raise_exception
    return decorator

>>> class some_class(object):
    @decoratorfactory('somestring')
    def some_method(self):
        print "An exception should be raised when I'm called, but not when 
I'm defined"

        
>>> some_class().some_method()

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    some_class().some_method()
  File "<pyshell#21>", line 4, in raise_exception
    raise Exception
Exception
>>> 



More information about the Python-list mailing list