Inline assignments

jillson at gmail.com jillson at gmail.com
Thu Mar 9 16:29:28 CET 2006


Coming from a background that exposed me to far too many languages, I
find the latter two examples (i.e. use try/except) to be horrible
solutions.  It's not a matter of light/heavy weight, it's a matter of
using exceptions for normal loop flow control is a really bad idea.
1)  I think it's less clear why the loop works
2)  The possibility (in more complicated examples) that this could mask
a real exception (if for example, your function

I recommend reading Effective Java (Bloch), specifically the beginning
of the exceptions chapter, for more details why using exceptions to
exit loops is a bad thing (and while the title is effective java, much
of it is directly applicable to a lot of python code)

> > Which is quite ugly. This might have been a bad example, since
> > somestring.split() could be used instead, but it's still valid for other
> > situations.
>
> Such as?
>
> Here is another way:
>
> pos = somestring.find("/")
> while pos != -1:
>     part = somestring[:pos]
>     somestring = somestring[pos + 1:]
>     # handle part
>
> And another:
>
> while True:
>     try:
>         pos = somestring.index("/")
>     except ValueError:
>         break
>     part = somestring[:pos]
>     somestring = somestring[pos + 1:]
>     # handle part
>
>
> And a third:
>
> start = 0
> while True:
>     try:
>         pos = somestring.index("/", start)
>     except ValueError:
>         break
>     # handle somestring[start:pos]
>     start = pos + 1
>
>
> If you are coming from a Java background, you may consider exceptions to
> be a lot of work. In Python, setting up a try...except block is very
> lightweight, so long as exceptions are rare. Hitting the except clause is
> more work, so you should avoid that idiom if you expect the try to raise
> an exception most of the time.
> 
> 
> 
> -- 
> Steven.




More information about the Python-list mailing list