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


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

Re: empty clause of for loops

Started byRuud de Jong <ruud.de.jong@xs4all.nl>
First post2016-03-16 14:37 +0100
Last post2016-03-16 14:37 +0100
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: empty clause of for loops Ruud de Jong <ruud.de.jong@xs4all.nl> - 2016-03-16 14:37 +0100

#105025 — Re: empty clause of for loops

FromRuud de Jong <ruud.de.jong@xs4all.nl>
Date2016-03-16 14:37 +0100
SubjectRe: empty clause of for loops
Message-ID<mailman.202.1458135923.12893.python-list@python.org>
Peter Otten schreef op 2016-03-16 13:57:
> If you don't like exceptions implement (or find) something like
> 
> items = peek(items)
> if items.has_more():
>    # at least one item
>    for item in items:
>        ...
> else:
>    # empty
> 
> Only if such a function is used a lot or cannot be conceived without 
> severe
> shortcumings adding to the syntax should be considered. The 
> (hypothetical)
> question you should answer: which current feature would you throw out 
> to
> make room for your cool new addition?

No need for hypothetical functions or syntax:

x = sentinal = object()
for x in sequence:
    # handle x
if x is sentinal:
    # sequence was empty.

Disclaimer: not tested because I don't have access to Python from my 
working location.
But it should work according to the language reference, section 8.3 on 
the 'for' statement:
"Names in the target list are not deleted when the loop is finished, but 
if the sequence is empty, they will not have been assigned to at all by 
the loop."

Regards, Ruud

[toc] | [standalone]


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


csiph-web