Functions that raise exceptions.
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):
> 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):
>>> class some_class(object):
print "An exception should be raised when I'm called, but not when
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
File "<pyshell#11>", line 3, in raise_exception
More information about the Python-list