Functions that raise exceptions.

Alex G alexander.girman at gmail.com
Wed Jun 25 15:43:20 EDT 2008


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?

Thank you in advance,

Alex.



More information about the Python-list mailing list