[Python-ideas] for/else statements considered harmful
Devin Jeanpierre
jeanpierreda at gmail.com
Fri Jun 8 11:14:45 CEST 2012
On Fri, Jun 8, 2012 at 4:04 AM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> Yuval Greenfield writes:
> > On Thu, Jun 7, 2012 at 1:50 PM, Stephen J. Turnbull <stephen at xemacs.org>wrote:
> >
> > > def search_in_iterable(key, iter):
> > > for item in iter:
> > > if item == key:
> > > return some_function_of(item)
> > > else:
> > > return not_found_default
> > >
> > >
> > You don't need the "else" there. An equivalent:
>
> *You* don't need it. *I* like it, because it expresses the fact that
> returning a default is a necessary complement to the for loop.
I've never been sure of what is good style here. It's comparable to
these two things:
def foo():
if bar():
return baz
return quux
def foo2():
if bar():
return baz
else:
return quux
Is there some well-accepted rule of which to use?
-- Devin
More information about the Python-ideas
mailing list