Why bool( object )?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri May 1 11:44:23 CEST 2009


On Fri, 01 May 2009 01:56:50 -0700, Paul Rubin wrote:

> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>> (2) Why assume that a, b and c are sequences with a fast __len__
>> method? They might be (say) linked lists that take O(N) to calculate
>> the length, or binary trees that don't even have a length, but can be
>> iterated over.
> 
> Why assume they have a bool method?  Or a __or__ operator?

What programming language are you using?

I'm using Python, where objects don't require either a bool or __or__ 
method (not operator) to work with the or operator.

>>> hasattr(None, '__or__') or hasattr(None, '__bool__') or \
... hasattr(None, '__nonzero__')
False
>>> 
>>> x = object()
>>> hasattr(x, '__or__') or hasattr(x, '__bool__') or \
... hasattr(x, '__nonzero__')
False
>>>
>>> None or x
<object object at 0xb7f3b4f0>

Any object can be used as an operand to the boolean operators.


> Eh.
> 
>    for seq in [a,b,c]:
>      if sum(1 for x in imap(do_something_with, seq)) > 0:
>        break

Did I stumble into an Obfuscated Python competition?




-- 
Steven



More information about the Python-list mailing list