473,785 Members | 2,188 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exceptions as a Control Structure

Hi all,

I am new to Python (I just finished Guido's tutorial).
I was very surprised to learn there that the StopIteration
is used to end for loops in a standard iterator setting.

I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.

What is the Python canon on this topic ? Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?

Regards,
Olivier.

Jul 18 '05 #1
10 1726
Olivier Parisy wrote:
I am new to Python (I just finished Guido's tutorial).
I was very surprised to learn there that the StopIteration
is used to end for loops in a standard iterator setting.

I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.
In Python, very little is frowned upon solely for efficiency
reasons. There are some examples, including using +=
repeatedly to grow a string, and some fields where efficiency
is of course critical, but in Python one almost always looks
for the most pragmatic approach (which is often the most
elegant, too, for some people's definition of elegant)
rather than obsessing about speed.
What is the Python canon on this topic ?
The only Python "canon" can be found by typing "import this"
at the interpreter prompt. ;-)
Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?


Catching an exception is considered a reasonable approach
to flow control for various problems. One, for example,
is in deeply nested loops, where rather than going out of
one's way to avoid exceptions in favour of a flag and lots
of awkward testing, one just raises a custom exception
(or perhaps a standard one) and catches it outside the
loops.

Exceptions are also used by some as a mechanism for
returning information from subroutines, though it's
very likely the information will still be considered
"exceptiona l" in some way (think of it as an out-of-band
mechanism for returning special info).

While some people object on stylistic grounds (or even
performance ones, in some cases) to such things, you
will likely find that exceptions are thrown around
by Python programmers more readily than you are used to.

Note also that in many cases other than algorithmic
complexity, what you have learned about efficiency in
C++ should be considered suspect info when it comes
to Python. Function calls, for example, are much more
expensive in Python than in C++ because of the time
required to set up the call frame. Exceptions, on the
other hand, are as I recall much more efficient.
Some Google Group searches in c.l.p would probably
lead to many past discussions of these things.

-Peter
Jul 18 '05 #2
In article <41************ ***********@new s.free.fr>,
Olivier Parisy <ol************ @free.fr> wrote:
Hi all,

I am new to Python (I just finished Guido's tutorial).
I was very surprised to learn there that the StopIteration
is used to end for loops in a standard iterator setting.

I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.

What is the Python canon on this topic ? Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?


Lots of things you do in C++ are frowned upon in Python. Lots of things
you do in Python are frowned upon in C++.

Specifically, exceptions in C++ are generally considered fairly
heavy-weight, but not so in Python. Here's another common python idiom
that uses exceptions in a way which would probably horrify most C++
people:

for key in sequence:
try:
foo = dictionary [key]
except KeyError
foo = "not found"

instead of:

for key in sequence:
if dictionary.has_ key (key):
foo = dictionary [key]
else
foo = "not found"

If you're reasonably sure that most of the keys will be found in the
dictionary, it's probably faster to just try them all and handle the
occasional exception than to test each key to see if it exists.
Jul 18 '05 #3
Peter Hansen wrote:
In Python, very little is frowned upon solely for efficiency
reasons. There are some examples, including using +=
repeatedly to grow a string, and some fields where efficiency
is of course critical, but in Python one almost always looks
for the most pragmatic approach (which is often the most
elegant, too, for some people's definition of elegant)
rather than obsessing about speed.
I understand this. That's one of the reasons I am learning
Python (I am more interested in improving my development time
than my programs' execution time).

Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?

Catching an exception is considered a reasonable approach
to flow control for various problems. One, for example,
is in deeply nested loops, where rather than going out of
one's way to avoid exceptions in favour of a flag and lots
of awkward testing, one just raises a custom exception
(or perhaps a standard one) and catches it outside the
loops.


OK. Definitely not something I'd do in C++.
Exceptions are also used by some as a mechanism for
returning information from subroutines, though it's
very likely the information will still be considered
"exceptiona l" in some way (think of it as an out-of-band
mechanism for returning special info).
Do you have some example of this in the standard library ?
While some people object on stylistic grounds (or even
performance ones, in some cases) to such things, you
will likely find that exceptions are thrown around
by Python programmers more readily than you are used to.
That's what I wanted to know. OK.
Note also that in many cases other than algorithmic
complexity, what you have learned about efficiency in
C++ should be considered suspect info when it comes
to Python. Function calls, for example, are much more
expensive in Python than in C++ because of the time
required to set up the call frame. Exceptions, on the
other hand, are as I recall much more efficient.
So I suppose I just won't concern myself with efficiency
questions and concentrate on prope style, then.
Some Google Group searches in c.l.p would probably
lead to many past discussions of these things.


I must admit I probably didn't do my homework...
BTW, thanks for your reactivity !

Regards,
Olivier.

Jul 18 '05 #4
And don't forget about:

for key in sequence:
foo = dictionary.get( key, "not found")

:)

Chris

On Mon, 09 Aug 2004 09:16:28 -0400, Roy Smith <ro*@panix.co m> wrote:
In article <41************ ***********@new s.free.fr>,
Olivier Parisy <ol************ @free.fr> wrote:
Hi all,

I am new to Python (I just finished Guido's tutorial).
I was very surprised to learn there that the StopIteration
is used to end for loops in a standard iterator setting.

I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.

What is the Python canon on this topic ? Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?


Lots of things you do in C++ are frowned upon in Python. Lots of things
you do in Python are frowned upon in C++.

Specifically, exceptions in C++ are generally considered fairly
heavy-weight, but not so in Python. Here's another common python idiom
that uses exceptions in a way which would probably horrify most C++
people:

for key in sequence:
try:
foo = dictionary [key]
except KeyError
foo = "not found"

instead of:

for key in sequence:
if dictionary.has_ key (key):
foo = dictionary [key]
else
foo = "not found"

If you're reasonably sure that most of the keys will be found in the
dictionary, it's probably faster to just try them all and handle the
occasional exception than to test each key to see if it exists.
--
http://mail.python.org/mailman/listinfo/python-list

--
Still searching for an even prime > 2!
Jul 18 '05 #5
Roy Smith wrote:
Lots of things you do in C++ are frowned upon in Python. Lots of things
you do in Python are frowned upon in C++.
This is something I need to learn. I suppose there's not much written
information on this informal topic, and that I'll have to read some
source code... Any advice on cleanly written projects from that point
of view ?
Specifically, exceptions in C++ are generally considered fairly
heavy-weight, but not so in Python. Here's another common python idiom
that uses exceptions in a way which would probably horrify most C++
people:

for key in sequence:
try:
foo = dictionary [key]
except KeyError
foo = "not found"

instead of:

for key in sequence:
if dictionary.has_ key (key):
foo = dictionary [key]
else
foo = "not found"


Hum, I stumbled on this FAQ a short time after I posted here, indeed :-)

Regards,
Olivier.

Jul 18 '05 #6
Olivier Parisy wrote:
Peter Hansen wrote:
Exceptions are also used by some as a mechanism for
returning information from subroutines, though it's
very likely the information will still be considered
"exceptiona l" in some way (think of it as an out-of-band
mechanism for returning special info).


Do you have some example of this in the standard library ?


It's easy to check for yourself, you have the source. ;-)

I searched for "(Exception " in the lib/*.py files, since
this code is likely to occur when someone subclasses the
top-level exception class.

There's an example similar to what I was describing in
inspect.py, using an EndOfBlock exception. The Queue
module has Full and Empty exceptions that are a good
example. By far the most occurrences of custom
exceptions are to define specialized ones denoting
error conditions, however. I suspect the usage I
described is more common outside the standard library,
in part because code where it would be useful is more
likely to occur in higher level code.

-Peter
Jul 18 '05 #7
> > Exceptions are also used by some as a mechanism for
returning information from subroutines, though it's
very likely the information will still be considered
"exceptiona l" in some way (think of it as an out-of-band
mechanism for returning special info).


Do you have some example of this in the standard library ?


pyparsing uses this technique to try various parse expressions - a raised
ParseException denotes that the attempted parsing pattern failed to match at
the current stream location.

In an earlier incarnation of this library, I implemented this by returning
True or False values to indicate successful matching, but when a False was
returned, I found I needed more information about why things were False.
The exception-based approach allows me to return a full exception, including
the match failure message and the location at which the failure occurred.

One optimization I have found w.r.t. exceptions is that, in pyparsing, a
given parsing expression always raises the almost the same exception, with
only the input location changing. I found a significant improvement by
pre-constructing the exception at grammar construction time, and then
raising a modified version at parse time. (Contrast with the dynamic
construction/garbage-collection of thousands of exception objects when
created and used only once.)

-- Paul
Jul 18 '05 #8
On Mon, 09 Aug 2004 15:01:38 +0200
Olivier Parisy <ol************ @free.fr> wrote:
Hi all,

I am new to Python (I just finished Guido's tutorial).
I was very surprised to learn there that the StopIteration
is used to end for loops in a standard iterator setting.

I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.

What is the Python canon on this topic ? Are exceptions
considered as reasonable control structures, or is
StopIteration alone of its kind ?


Actually StopIteration is a semantic peer of the long standing
IndexError and KeyError exceptions used in sequences and dicts.

In general I think you will find python uses exceptions often for flow
control. The try: except: block is more or less free if no exception
actually occurs.

-Casey

Jul 18 '05 #9
In article <41************ ***********@new s.free.fr> (Mon, 09 Aug 2004
15:01:38 +0200), Olivier Parisy wrote:
I come from C++, where the use of exceptions as control
structures is frowned upon for efficiency reasons.
In Bertrand Meyer's Eiffel, this is prohibited by the language design.
Exceptions wouldn't have been my choice for this kind of control, but Dr.
van Rossum is far more educated than I.
What is the Python canon on this topic ?
Exceptions are a primary control structure.
Are exceptions considered as reasonable control structures, or is
StopIteration alone of its kind ?


Yes. No.

--
"It's not like IBM can support Linux the way they support the mainframe
operating system. They don't write the code for it."
-- Steve Ballmer. http://news.com.com/2008-1082-998297.html. 25 Apr 2003

Jul 18 '05 #10

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

Similar topics

59
4451
by: kk_oop | last post by:
Hi. I wanted to use exceptions to handle error conditions in my code. I think doing that is useful, as it helps to separate "go" paths from error paths. However, a coding guideline has been presented that says "Use conventional error-handling techniques rather than exception handling for straightforward local error processing in which a program is easily able to deal with its own errors." By "conventional error-handling," I believe...
22
2740
by: Drew | last post by:
How do I know which exceptions are thrown by certain methods? For example, reading a file might throw an IO Exception, etc. In Java, the compiler won't even let you compile unless you put your code in try/catch blocks but the C# compiler doesn't seem to mind? I am particularly interested in what Exceptions are thrown by HttpWebResponse.
5
3811
by: Miyra | last post by:
Hi. I'm working with an app that uses exceptions for control flow. These are code blocks where exceptions are thrown/caught regularly. A couple hundred exceptions occur per hour and they're caught close to the point of origination. I'm trying to decide whether to refactor... What is the cost of throwing an exception in the CLR - relative to, say, a conditional statement? Are we taking talking 1+ orders of magnitude? Is there...
9
1763
by: Alvin Bruney [MVP] | last post by:
Exceptions must not be used to control program flow. I intend to show that this statement is flawed. In some instances, exceptions may be used to control program flow in ways that can lead to improved code readability and performance. Consider an application that must eliminate duplicates in a list. using system.collections;
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9957
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8983
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.