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

Martin v. Loewis martin at v.loewis.de
Sat Mar 30 17:24:57 EST 2002


Ype Kingma <ykingma at accessforall.nl> writes:

> Python is sufficiently high level not to care about the bits.
> Python never had a C float type, only a C double type, for precisily
> this reason.

Python does, however, have a long int type, side-by-side with the int
type - because it cares about bits. Atleast it used to, there is a PEP
for merging the two integer types. There is also a PEP merging all
numeric types into a single one, or a hierarchy of types.

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.

The other question is whether bool should inherit from int. Notice
that this is unrelated: you could have the arithmetic operations even
without inheritance. The inheritance from int is mostly an
implementation convenience: too much code in the interpreter itself
would need to change to make bool inherit from object only.

> Somehow this reminds me of subclassing Square from Rectangle:
> it just doesn't feel right, even though it might work.

I can't see the relationship: A Sqare is-a Rectangle, so following
classic OO principles, the inheritance is clearly right. Depending on
how you define the Rectangle interface, this inheritance relationship
would even satisfy LSP.

> With a non int bool, True and False would be real singletons:
> 
> bool(1) is True
> bool(0) is False

They are singletons even under the PEP: You have to work really hard
to make two instances of True (bool(1) is (not bool(0)) is bool(1) is
True); and if it was a type not inheriting from int, you could *still*
make extra instances if you wanted to hard enough.

> True is not 1

This is True in the PEP.

> True != 1

This is False, and it should be, since making it True would break
backwards compatibility.

> Subclassing bool from int would also force 1 and 0 to be become
> real singletons. 

Can you elaborate? This is not at all the case.

> The only reason this would work is that current python
> implementations happen to implement 1 and 0 in this way.

Not at all:

>>> (1>0) is 1
0

> But you could make the language definition simpler by explicitly
> defining the cast to bool in contexts where a boolean is expected,
> see above. This would allow the current casts (eg. list to bool as
> non empty) to be described at the standard types instead of in the
> language definition.

It is already that way, the method determining truth is __nonzero__;
for historic reasons, a number of fallbacks are taken if __nonzero__
isn't implemented.

Regards,
Martin




More information about the Python-list mailing list