Functions that raise exceptions.

Duncan Booth duncan.booth at invalid.invalid
Wed Jun 25 22:21:27 CEST 2008


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

> Does anyone know how I would go about conditionally raising an
> exception in a decorator (or any returned function for that matter)?
> For example:
> 
> def decorator(arg):
>     def raise_exception(fn):
>         raise Exception
>     return raise_exception
> 
> class some_class(object):
>     @raise_exception
>     def some_method(self)
>         print "An exception should be raised when I'm called, but not
> when I'm defined"
> 
> The intent of the above code is that an exception should be raised if
> some_method is ever called.  It seems, however, since the decorator
> function is executed on import, the raise statement is executed, and I
> the exception gets thrown whenever the module is imported, rather than
> when the method is called.  Does anyone have a clue how I might go
> about doing this?

Well, the simplest way would be to correct the syntax error in your class 
definition and to try calling the decorator you defined instead of calling 
the undefined 'raise_exception'. Fix both of those and the code you posted 
works 'as is'.

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

>>> class some_class(object):
    @decorator
    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#14>", line 1, in <module>
    some_class().some_method()
  File "<pyshell#11>", line 3, in raise_exception
    raise Exception
Exception
>>> 



More information about the Python-list mailing list