empty clause of for loops
Ruud de Jong
ruud.de.jong at xs4all.nl
Wed Mar 16 09:37:00 EDT 2016
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
More information about the Python-list
mailing list