[Python-ideas] for/else statements considered harmful
Stephen J. Turnbull
stephen at xemacs.org
Fri Jun 8 10:04:27 CEST 2012
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.
While this is something of a TOOWTDI violation, there are cases where
else is needed to express the semantics, as well (eg, if the first
return statement is replaced by "process(item); break").
More information about the Python-ideas
mailing list