Functions that raise exceptions.

A

Alex G

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.
 
A

Alex G

whoops! The code should be:

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

class some_class(object):
    @decorator('meaningless string')
    def some_method(self):
        print "An exception should be raised when I'm called, but not
when I'm defined"
 
A

Alex G

I'm sorry about the typos, but that doesn't seem to be what the issue
is (I typed it into the textbox rather carelessly, I apologize :-( ).
It seems to be an issue with passing the decorator an argument:

Given:

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

If you pass the decorator an argument, it doesn't work as expected
(but if you neglect the argument, it works, even though the decorator
_expects_ an argument.

That is,

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.

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

Gets defined, and executing

b = classB()
b.some_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in raise_exception
Exception

works as expected, even though decorator is expecting an argument...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top