empty clause of for loops
Peter Otten
__peter__ at web.de
Wed Mar 16 08:57:56 EDT 2016
Sven R. Kunze wrote:
> 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.
I'd put that the other way round: syntactical support for every pattern
would make for a rather unwieldy language. You have to choose carefully, and
this requirement could easily be fulfilled by a function, first in your
personal toolbox, then in a public libary, then in the stdlib.
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?
More information about the Python-list
mailing list