Why bool( object )?

Aaron Brady castironpi at gmail.com
Fri May 1 18:03:30 EDT 2009


On May 1, 4:30 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 01 May 2009 16:30:19 +1200, Lawrence D'Oliveiro wrote:
> > I have never written anything so unbelievable in my life. And I hope I
> > never will.
>
> I didn't say you did. If anyone thought I was quoting Lawrence's code,
> I'd be surprised. It was not my intention to put words into your mouth.
>
> But seeing as you have replied, perhaps you could tell us something.
> Given so much you despise using non-bools in truth contexts, how would
> you re-write my example to avoid "a or b or c"?
>
> for x in a or b or c:
>     do_something_with(x)

I think Hendrik's is the closest so far, but still doesn't iterate
over x:

for t in [a,b,c]:
    if t:
        for x in t:
            do_something_with(x)
        break

This is still not right, since Steven's code will raise an exception
if 'a' and 'b' test False, and 'c' is non-iterable.

>>> for x in 0 or 0 or 0:
...     print( x )
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> for x in 0 or 0 or []:
...     print( x )
...
>>> for x in 0 or 0 or 1:
...     print( x )
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> for x in ['abc'] or 0 or 0:
...     print( x )
...
abc

To mimic it exactly, you'd have to actually convert the first one,
execute 'or' on the other two, since they may have side-effects or
return other values than themselves, and try iterating over the last
one.  I think you are looking at an 'ireduce' function, which doesn't
exist in 'itertools' yet.

I don't think it would be very common to write Steven's construction
for arbitrary values of 'a', 'b', and 'c'.



More information about the Python-list mailing list