Expression can be simplified on list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 29 05:49:36 EDT 2016


On Thursday 29 September 2016 18:45, Jussi Piitulainen wrote:

> Steven D'Aprano writes:
> 
> [- -]
> 
>> What is this truthiness abstraction? It is the difference between
>> "something" and "nothing".
>>
>> Values which represent nothing, e.g.:
>>
>> - None
>> - numeric zero: 0, 0.0, 0j, Decimal(0) etc
>> - empty strings u'', ''
>> - empty containers [], (), {} etc.
>>
>> are treated as falsey. And values that represent something, e.g.:
> 
> [- -]
> 
> What do you say about things like iterators and generators? I'd say they
> are containers, but they count as true even when they are empty.

No, they aren't containers, because they don't support membership testing or 
len(), as containers must.

But I agree the abstraction leaks. We would like empty iterables (iterators and 
sequences) to be falsey, but the problem is, how do you know if an iterator is 
empty without consuming a value from it? Sequences and containers can be probed 
without consuming values, but iterators cannot be.

So although you can use them in many of the same places that you might use a 
sequence or container, they aren't actually sequences or containers, and are 
better treated as something like a function. (Except instead of calling them, 
you pass them to next() to get the next value.)

And what are functions? Why, they're *things*, of course, and hence *something* 
rather than nothing, even if they return None, or never return at all, or 
crash. And so even though it is inconvenient, nevertheless it is logical for 
iterators to always be truthy.

However, if you had a peekable iterator where you can peek ahead to see if they 
are empty or not, then it might make sense to treat them as more like a 
sequence than a function. But arbitrary iterators do not support a peek() 
operation.

Either way, the abstraction leaks a bit. Never mind -- welcome to life as a 
programmer.


-- 
Steven
git gets easier once you get the basic idea that branches are homeomorphic 
endofunctors mapping submanifolds of a Hilbert space.




More information about the Python-list mailing list