Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105025
| From | Ruud de Jong <ruud.de.jong@xs4all.nl> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: empty clause of for loops |
| Date | 2016-03-16 14:37 +0100 |
| Message-ID | <mailman.202.1458135923.12893.python-list@python.org> (permalink) |
| References | <56E93413.6090108@mail.de> <ncbdk4$h9u$1@ger.gmane.org> <56E94EB9.9050507@mail.de> <ncbl8p$hq6$1@ger.gmane.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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: empty clause of for loops Ruud de Jong <ruud.de.jong@xs4all.nl> - 2016-03-16 14:37 +0100
csiph-web