Pythonic exceptionalism (was: A C-like if statement)
Cameron Laird
claird at lairds.us
Sat Feb 25 21:08:01 EST 2006
In article <pan.2006.02.23.22.14.53.56541 at REMOVETHIScyber.com.au>,
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
>On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
>
>>> try:
>>> i = a.find("3")
>>> print "It's here: ", i
>>> except NotFound:
>>> print "No 3's here"
>>
>> Nuts. I guess you're right. It wouldn't be proper. Things are added or
>> proposed every day for Python that I can't even pronounce, but a simple 'if
>> (I = a.find("3")) != -1' isn't allowed. Huh. It might be time to go back
>> to BASIC. :)
>
>There are *reasons* why Python discourages functions with side-effects.
>Side-effects make your code hard to test and harder to debug.
>
>> I think your way would work if .find() were replaced with .index(). I'm
>> just trying to clean up an if/elif tree a bit, so using try would make
>> things bigger.
>
>Then write a function! Instead of calling the try..except block in every
>branch directly, pull it out into a function:
>
>def test(s,what):
> try:
> i = s.index(what)
> print "It's here: ", i
> except ValueError:
> print "No 3's here"
.
.
.
A recent piece by Collin Park <URL:
http://www.linuxjournal.com/article/8794 >
illustrates how a user-defined exception
arises so naturally in a tiny toy example
that it occurs to a teenager first program-
ming.
More information about the Python-list
mailing list