Functions that raise exceptions.

2008-06-25 Thread 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.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Functions that raise exceptions.

2008-06-25 Thread 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"


--
http://mail.python.org/mailman/listinfo/python-list


Re: Functions that raise exceptions.

2008-06-25 Thread 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()

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

works as expected, even though decorator is expecting an argument...
--
http://mail.python.org/mailman/listinfo/python-list