PEP 285: Adding a bool type: yes, but not as int subtype

Martin v. Loewis martin at v.loewis.de
Sun Mar 31 06:14:18 EST 2002


Ype Kingma <ykingma at accessforall.nl> writes:

> I'd like to know whether this PEP merging all numeric types would also merge
> the bool type into its evt. hierarchy.

See for yourself:

http://python.sourceforge.net/peps/pep-0228.html
http://python.sourceforge.net/peps/pep-0242.html


> > Notice that the relationship of bool and int has two aspects: one is
> > whether you can combine them in numeric operations,
> > e.g. 28+isleap(year). There is absolutely no way to remove this
> > property from the language - too much code would break if that would
> > raise an exception.
> 
> There are two ways to do this:
> - marking such code with: from __past__ import nonbool
>   (as I remarked earlier this is rather radical)

I hate the __future__ statement, so I definitely don't want to get a
__past__ statement. Following PEP 5, you will need a phased
introduction strategy for booleans if you don't want to interact them
with numbers. Don't expect to get this in this decade, though.

Also, I doubt that this would be implementable: those magic import
statements can only perform 'static' analysis of the module in
question. Consider the following scenario:

# module a.py
def foo_p():
  return True

# module b.py
def addem(a,b):
  return a+b

# module c.py
from __past__ import nonbool
import a,b
print b.addem(10, a.foo_p())

How is the bytecode of c.py supposed to know that foo_p returns a
boolean, and that addem will attempt to convert this to an integer?

> - defining __add__ and __radd__ in the int and float classes to also
> accept a bool sounds quite pythonic and acceptable to me.

That would work, but only somewhat. There are other places where
booleans need to act as integers, e.g. indexing: array[b] ought to
work, for backwards compatibility, even if b suddently turns into a
boolean. That means that every __getitem__ implementation needs to
become aware of booleans - so likely a lot of code would break.

> An Square that is a Rectangle has inherits two degrees of freedom,
> (height and width) which have to constrained to a single one in the
> implementation.
> Implementing such constraints is a bit awkward 

That depends on the rectangle interface. If rectangles are immutable,
implementing the constraint is straight-forward, not awkward.

class Rectangle:
  def __init__(self, x, y, w, h):
    self.x,self.y,self.w,self.h = x,y,w,h

  def area(self):
     return self.w*self.h

class Square(Rectangle):
  def __init__(self, x, y, w):
    Rectangle.__init__(self, x, y, w, w)

> When bool is-a int, one would have to (awkwardly) implement at least
> one such constraint, namely that bool values can only be 1 or 0.

Not at all. Bools are immutable, and singletons. If bool would not
inherit from int, nothing in the implementation would change; see the
PEP.

Regards,
Martin



More information about the Python-list mailing list