473,406 Members | 2,769 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Functions that raise exceptions.

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.
Jun 27 '08 #1
4 1556
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"
Jun 27 '08 #2
Alex G <al**************@gmail.comwrote:
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
>>>
Jun 27 '08 #3
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 "<stdin>", line 1, in <module>
File "<stdin>", line 3, in raise_exception
Exception

works as expected, even though decorator is expecting an argument...
Jun 27 '08 #4
Alex G <al**************@gmail.comwrote:
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.
Well, yes it would. That's because what you defined a decorator. i.e. a
function which wraps the method in another function. A decorator is called
with a single argument: the function/method to be wrapped.

What you have done in the code above is to call something named 'decorator'
which isn't a decorator at all, it's a function that you expect to return a
decorator (a decorator factory if you wish). If you make it return a
decorator then it will all work fine:
>>def decoratorfactory(s):
def decorator(arg):
def raise_exception(fn):
raise Exception
return raise_exception
return decorator
>>class some_class(object):
@decoratorfactory('somestring')
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#24>", line 1, in <module>
some_class().some_method()
File "<pyshell#21>", line 4, in raise_exception
raise Exception
Exception
>>>
Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Prabu | last post by:
Hi, I'm new to python, so excuse me if i'm asking something dumb. Does python provide a mechanism to implement virtual functions? Can you please give a code snippet also...:) Thanx in advance...
1
by: Dominic | last post by:
Just in case someone is interested. I came up with this solution since my previous posting. Maybe you've got some other ideas or critcism. I'll listen ;-) Ciao, Dominic P.S. Python is...
3
by: Tim Chase | last post by:
Are there existing "quiet" conversion functions? Kin of int() and float()? My aim would be to call a function that would guarntee that the result was of the defined type, choosing sensible...
3
by: Dmitry Prokoptsev | last post by:
Hello, I need to write a class for exceptions which can be thrown, caught, stored and thrown once again. I have written the following code: --- begin --- #include <string> class Exception...
15
by: Ant | last post by:
Hi all, In a framework I've written to test out website, I use something like the following to add functionality at various points: #----------------------------------- def do_work(callable,...
5
by: Ed Jensen | last post by:
I'm really enjoying using the Python interactive interpreter to learn more about the language. It's fantastic you can get method help right in there as well. It saves a lot of time. With that...
7
by: Steven W. Orr | last post by:
In my class I have class Error(Exception): """Base class for exceptions in this module.""" pass class TransitionError(Error): """Raised when an operation attempts a state transition that's...
9
by: ssecorp | last post by:
Is this correct use of exceptions? to raise an indexerror and add my own string insetad of just letting it raise a IndexError by itself and "blaming" it on list.pop? class Stack(object): def...
14
by: Rafe | last post by:
Hi, I've encountered a problem which is making debugging less obvious than it should be. The @property decorator doesn't always raise exceptions. It seems like it is bound to the class but...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.