bool behavior in Python 3000?

tah tim.hochberg at gmail.com
Thu Jul 12 05:14:44 CEST 2007


On Jul 11, 1:30 pm, Nick Craig-Wood <n... at craig-wood.com> wrote:
> Alan Isaac <ais... at american.edu> wrote:
> >  Miles wrote:
> > > What boolean operation does '-' represent?
>
> >  Complementation.
> >  And as usual, a-b is to be interpreted as a+(-b).
> >  In which case the desired behavior is
> >   False-True = False+(-True)=False+False = False
>
> If you want to do algebra with bools in python then use the logical
> operators (and or not) and not the arithmetical operators.
>
> Eg
>
>   >>> False or not True
>   False

Let me comment on what I suspect is Alan's Hidden Agenda (tm). Since
this question surfaced earlier on the numpy list, I suspect that part
of the motivation here has to do with trying to come up with a natural
way to work with arrays of booleans. The operators and,or,not don't
work for this purpose since they can't be overloaded to return an
arbitrary value. You can almost make this work with &,|,^:

>>> a = np.array([True, False, False])
>>> b = np.array([True, True, False])
>>> a & b
array([ True, False, False], dtype=bool)
>>> a | b
array([ True,  True, False], dtype=bool)
>>> a ^ b
array([False,  True, False], dtype=bool)

This is meshes well with the behavior of True and False:

>>> True & True
True
>>> True | True
True
>>> True ^ True
False

This doesn't leave you with anything equivalent to 'not' however. Or
nothing consistent. Currently '~a' will complement a boolean array,:

>>> ~a
array([False,  True,  True], dtype=bool)

However that's less than ideal since it doesn't mesh up with the
behavior of booleans on their own:

>>> ~True
-2

That's potentially confusing. It's not any skin of my nose since I
use, and will likely continue to use, boolean arrays in only the most
rudimentary ways. However, I thought I'd offer some additional
context.

-tim




More information about the Python-list mailing list