The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Chris Angelico rosuav at gmail.com
Tue Mar 22 09:13:48 EDT 2016


On Tue, Mar 22, 2016 at 11:59 PM, BartC <bc at freeuk.com> wrote:
> (1) Not bother with exceptions at all inside the function
>
> (2) Not bother with them in the user code either
>
> (3) Let any errors just crash out (raise a Python system error) (just like I
> did in my original jpeg program which I was called out on)
>
> (4) Or if the user code does want to check for certain errors (like, File
> Not Found, by far the most likely, and so that it can deal with that and
> continue executing), it now has to go and dig out docs for ... what? The
> user code needs to know what is going on inside the supposedly opaque
> function it's calling.

Yes, yes, at first, and try it.

The first step in any program is to write it in the very simplest way
possible. That usually means ignoring all error handling. And yes,
this is true in EVERY language - C, PHP, Pike, DeScribe Macro
Language, you name it. Then you try it, and you find one of two
things:

1) The code you've written is encountering error conditions that it
can't handle, and has to pass upstream; or
2) The code you've written is getting passed error conditions that it
knows how to deal with.

The first one is a time to raise an exception. The second is a time to
catch one. And since, by default, Python prints those exceptions to
the console, you should [1] have all the information you need to catch
the ones you understand, because you've seen them in testing.

Note, though, that "deal with" really means "deal with", and NOT
"print oops to the console and terminate". If all you're going to do
with an exception is print and terminate, *let it go*, unless it's a
user-triggered failure, in which case you catch it right at the very
highest level, and basically fall off the end of your program. The
number of times you have sys.exit() in an except clause should be
vanishingly small.

ChrisA

[1] Some libraries force you to dig around a bit to figure out how
you're supposed to import those exception classes. But that's usually
*one* thing to look up in the docs - "oh, so I import
foobarbletch.exceptions.OutOfBeerException".



More information about the Python-list mailing list