Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #91827 > unrolled thread

Re: for...else

Started byPeter Otten <__peter__@web.de>
First post2015-06-02 14:27 +0200
Last post2015-06-02 14:27 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: for...else Peter Otten <__peter__@web.de> - 2015-06-02 14:27 +0200

#91827 — Re: for...else

FromPeter Otten <__peter__@web.de>
Date2015-06-02 14:27 +0200
SubjectRe: for...else
Message-ID<mailman.54.1433248099.13271.python-list@python.org>
acdr wrote:

> Hi,
> 
> Currently, in various places in my code, I have the equivalent of:
> 
> for x in it:
>     if complicated_calculation_1():
>         cleanup()
>         break
>     complicated_calculation_2()
>     if complicated_calculation_3():
>         cleanup()
>         break
> 
> Obviously, I'm repeating myself by having two separate calls to
> cleanup(). I can't really see a nicer way to do this. (Though I see
> plenty of non-nice ways to do this, such as adding "broken = True" in
> front of every "break", and then after the loop is done, have an "if
> broken" section.) Other solutions that I'm not particularly fond of
> can be found on stackexchange, where someone else is trying to do the
> same thing:
> http://stackoverflow.com/questions/3296044/opposite-of-python-for-else

Perhaps you like of these:

for x in it:
    if not complicated_calculation_1():
        complicated_calculation_2()
        if not complicated_calculation_3():
            continue
    cleanup()
    break

def f():
    for x in it:
        if complicated_calculation_1():
            break
        complicated_calculation_2()
        if complicated_calculation_3():
            break
    else:
        return
    cleanup()

> I'm wondering if there is a demand for expanding the "for...else"
> functionality to be expanded also have a block of code that only gets
> called if the loop is broken out of. I.e.:
> 
> for x in it:
>     ...
> then:
>     # "break" was called
>     ...
> else:
>     # "break was not called
>     ...

You may not like using a flag, but it's a really obvious approach and the 
situations where it's necessary are not very common. Apart from indentation-
based blocks Python is very middle-of-the-road, so I'd ask if there is an 
existing language that has such a feature, and if yes, is it used 
frequently? I suspect that there are many Python programmers that have never 
even used (for...else).

Python the language is already becoming too complicated for my taste; I 
would rather not add more constructs where there is no significant 
advantage. 

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web