empty clause of for loops
Sven R. Kunze
srkunze at mail.de
Wed Mar 16 08:16:57 EDT 2016
On 16.03.2016 11:47, Peter Otten wrote:
>
> What would you expect?
A keyword filling the missing functionality? Some Python magic, I
haven't seen before. ;-)
>
>>>> class Empty(Exception): pass
> ...
>>>> def check_empty(items):
> ... items = iter(items)
> ... try:
> ... yield next(items)
> ... except StopIteration:
> ... raise Empty
> ... yield from items
> ...
>>>> try:
> ... for item in check_empty("abc"): print(item)
> ... except Empty: print("oops")
> ...
> a
> b
> c
>>>> try:
> ... for item in check_empty(""): print(item)
> ... except Empty: print("oops")
> ...
> oops
He will be highly delighted so see such a simplistic solution. ;-)
> I'm kidding, of course. Keep it simple and use a flag like you would in any
> other language:
>
> empty = True:
> for item in items:
> empty = False
> ...
> if empty:
> ...
>
He likes this approach. Thanks. :-)
Although, I for one would like a keyword. I remember having this issue
myself, and found that the "empty" variable approach is more like a
pattern. As usual, patterns are workarounds for features that a language
misses.
Best,
Sven
More information about the Python-list
mailing list