[Python-ideas] Control Flow - Never Executed Loop Body
Émanuel Barry
vgr255 at live.ca
Sun Mar 20 19:48:33 EDT 2016
> From Vito De Tullio
> Sent: Sunday, March 20, 2016 7:39 PM
> To: python-ideas at python.org
> Subject: Re: [Python-ideas] Control Flow - Never Executed Loop Body
>
> ...thinking about it, is there a reason why the boolean interpretation of
an
> empty iterator is true?
>
> I know it's not trivial to know if an iterator is empty (still, there are
a
> pair of recipes online, like http://code.activestate.com/recipes/413614-
> testing-for-an-empty-iterator/ or the first part of the response at
> http://stackoverflow.com/a/3114423/273593 ) but shoulnd't be more
> "pythonic"
> to just have a "falsy" value for an "empty" iterator?
Not trivial, indeed. Consider the following:
def gen():
while random.choice([0, 1]):
yield "spam"
Is it empty? Is it not? You can't tell when it will be, and while that is a
bad example (I hope something like that doesn't get used!), arbitrary
generators can have side effects, or be empty under certain circumstances
and not under others.
That being said, we can maybe make the built-in iterators return a falsey
value in such cases, and let third-party iterators handle that on their own,
if they feel like doing that. Generators would always be true, but it's an
opt-in solution, and custom iterators can already define their own __bool__
if they want.
-Emanuel
~ Anything can be a duck if you try hard enough ~
More information about the Python-ideas
mailing list