PEP 285: Adding a bool type

83 views
Skip to first unread message

Guido van Rossum

unread,
Mar 30, 2002, 12:39:10 AM3/30/02
to
I offer the following PEP for review by the community. If it receives
a favorable response, it will be implemented in Python 2.3.

A long discussion has already been held in python-dev about this PEP;
most things you could bring up have already been brought up there.
The head of the thread there is:

http://mail.python.org/pipermail/python-dev/2002-March/020750.html

I believe that the review questions listed near the beginning of the
PEP are the main unresolved issues from that discussion.

This PEP is also on the web, of course, at:

http://python.org/peps/pep-0285.html

If you prefer to look at code, here's a reasonably complete
implementation (in C; it may be slightly out of date relative to the
current CVS):

http://python.org/sf/528022

--Guido van Rossum (home page: http://www.python.org/~guido/)

PEP: 285
Title: Adding a bool type
Version: $Revision: 1.12 $
Last-Modified: $Date: 2002/03/30 05:37:02 $
Author: gu...@python.org (Guido van Rossum)
Status: Draft
Type: Standards Track
Created: 8-Mar-2002
Python-Version: 2.3
Post-History: 8-Mar-2002, 30-Mar-2002


Abstract

This PEP proposes the introduction of a new built-in type, bool,
with two constants, False and True. The bool type would be a
straightforward subtype (in C) of the int type, and the values
False and True would behave like 0 and 1 in most respects (for
example, False==0 and True==1 would be true) except repr() and
str(). All built-in operations that conceptually return a Boolean
result will be changed to return False or True instead of 0 or 1;
for example, comparisons, the "not" operator, and predicates like
isinstance().


Review

Dear reviewers:

I'm particularly interested in hearing your opinion about the
following three issues:

1) Should this PEP be accepted at all.

2) Should str(True) return "True" or "1": "1" might reduce
backwards compatibility problems, but looks strange to me.
(repr(True) would always return "True".)

3) Should the constants be called 'True' and 'False'
(corresponding to None) or 'true' and 'false' (as in C++, Java
and C99).

Most other details of the proposal are pretty much forced by the
backwards compatibility requirement; e.g. True == 1 and
True+1 == 2 must hold, else reams of existing code would break.

Minor additional issues:

4) Should we strive to eliminate non-Boolean operations on bools
in the future, through suitable warnings, so that e.g. True+1
would eventually (e.g. in Python 3000 be illegal). Personally,
I think we shouldn't; 28+isleap(y) seems totally reasonable to
me.

5) Should operator.truth(x) return an int or a bool. Tim Peters
believes it should return an int because it's been documented
as such. I think it should return a bool; most other standard
predicates (e.g. issubtype()) have also been documented as
returning 0 or 1, and it's obvious that we want to change those
to return a bool.


Rationale

Most languages eventually grow a Boolean type; even C99 (the new
and improved C standard, not yet widely adopted) has one.

Many programmers apparently feel the need for a Boolean type; most
Python documentation contains a bit of an apology for the absence
of a Boolean type. I've seen lots of modules that defined
constants "False=0" and "True=1" (or similar) at the top and used
those. The problem with this is that everybody does it
differently. For example, should you use "FALSE", "false",
"False", "F" or even "f"? And should false be the value zero or
None, or perhaps a truth value of a different type that will print
as "true" or "false"? Adding a standard bool type to the language
resolves those issues.

Some external libraries (like databases and RPC packages) need to
be able to distinguish between Boolean and integral values, and
while it's usually possible to craft a solution, it would be
easier if the language offered a standard Boolean type.

The standard bool type can also serve as a way to force a value to
be interpreted as a Boolean, which can be used to normalize
Boolean values. Writing bool(x) is much clearer than "not not x"
and much more concise than

if x:
return 1
else:
return 0

Here are some arguments derived from teaching Python. When
showing people comparison operators etc. in the interactive shell,
I think this is a bit ugly:

>>> a = 13
>>> b = 12
>>> a > b
1
>>>

If this was:

>>> a > b
True
>>>

it would require one millisecond less thinking each time a 0 or 1
was printed.

There's also the issue (which I've seen puzzling even experienced
Pythonistas who had been away from the language for a while) that if
you see:

>>> cmp(a, b)
1
>>> cmp(a, a)
0
>>>

you might be tempted to believe that cmp() also returned a truth
value. If ints are not (normally) used for Booleans results, this
would stand out much more clearly as something completely
different.


Specification

The following Python code specifies most of the properties of the
new type:

class bool(int):

def __new__(cls, val=0):
# This constructor always returns an existing instance
if val:
return True
else:
return False

def __repr__(self):
if self:
return "True"
else:
return "False"

__str__ = __repr__

def __and__(self, other):
if isinstance(other, bool):
return bool(int(self) & int(other))
else:
return int.__and__(self, other)

__rand__ = __and__

def __or__(self, other):
if isinstance(other, bool):
return bool(int(self) | int(other))
else:
return int.__or__(self, other)

__ror__ = __or__

def __xor__(self, other):
if isinstance(other, bool):
return bool(int(self) ^ int(other))
else:
return int.__xor__(self, other)

__rxor__ = __xor__

# Bootstrap truth values through sheer willpower
False = int.__new__(bool, 0)
True = int.__new__(bool, 1)

The values False and True will be singletons, like None; the C
implementation will not allow other instances of bool to be
created. At the C level, the existing globals Py_False and
Py_True will be appropriated to refer to False and True.

All built-in operations that are defined to return a Boolean
result will be changed to return False or True instead of 0 or 1.
In particular, this affects comparisons (<, <=, ==, !=, >, >=, is,
is not, in, not in), the unary operator 'not', the built-in
functions callable(), hasattr(), isinstance() and issubclass(),
the dict method has_key(), the string and unicode methods
endswith(), isalnum(), isalpha(), isdigit(), islower(), isspace(),
istitle(), isupper(), and startswith(), the unicode methods
isdecimal() and isnumeric(), and the 'closed' attribute of file
objects.

Note that subclassing from int means that True+1 is valid and
equals 2, and so on. This is important for backwards
compatibility: because comparisons and so on currently return
integer values, there's no way of telling what uses existing
applications make of these values.


Compatibility

Because of backwards compatibility, the bool type lacks many
properties that some would like to see. For example, arithmetic
operations with one or two bool arguments is allowed, treating
False as 0 and True as 1. Also, a bool may be used as a sequence
index.

I don't see this as a problem, and I don't want evolve the
language in this direction either; I don't believe that a stricter
interpretation of "Booleanness" makes the language any clearer.

Another consequence of the compatibility requirement is that the
expression "True and 6" has the value 6, and similarly the
expression "False or None" has the value None. The "and" and "or"
operators are usefully defined to return the first argument that
determines the outcome, and this won't change; in particular, they
don't force the outcome to be a bool. Of course, if both
arguments are bools, the outcome is always a bool. It can also
easily be coerced into being a bool by writing for example
"bool(x and y)".


Issues

Because the repr() or str() of a bool value is different from an
int value, some code (for example doctest-based unit tests, and
possibly database code that relies on things like "%s" % truth)
may fail. How much of a backwards compatibility problem this will
be, I don't know. If we this turns out to be a real problem, we
could changes the rules so that str() of a bool returns "0" or
"1", while repr() of a bool still returns "False" or "True".

Other languages (C99, C++, Java) name the constants "false" and
"true", in all lowercase. In Python, I prefer to stick with the
example set by the existing built-in constants, which all use
CapitalizedWords: None, Ellipsis, NotImplemented (as well as all
built-in exceptions). Python's built-in module uses all lowercase
for functions and types only. But I'm willing to consider the
lowercase alternatives if enough people think it looks better.

It has been suggested that, in order to satisfy user expectations,
for every x that is considered true in a Boolean context, the
expression x == True should be true, and likewise if x is
considered false, x == False should be true. This is of course
impossible; it would mean that e.g. 6 == True and 7 == True, from
which one could infer 6 == 7. Similarly, [] == False == None
would be true, and one could infer [] == None, which is not the
case. I'm not sure where this suggestion came from; it was made
several times during the first review period. For truth testing
of a value, one should use "if", e.g. "if x: print 'Yes'", not
comparison to a truth value; "if x == True: print 'Yes'" is not
only wrong, it is also strangely redundant.


Implementation

An experimental, but fairly complete implementation in C has been
uploaded to the SourceForge patch manager:

http://python.org/sf/528022


Copyright

This document has been placed in the public domain.



Local Variables:
mode: indented-text
indent-tabs-mode: nil
fill-column: 70
End:

Chris Gonnerman

unread,
Mar 30, 2002, 1:16:53 AM3/30/02
to
----- Original Message -----
From: "Guido van Rossum" <gu...@python.org>


> I offer the following PEP for review by the community. If it receives
> a favorable response, it will be implemented in Python 2.3.
>

> ...


>
> Dear reviewers:
>
> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

Looks cool to me.

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

"True" sounds best to me. Explicit is better and all that...

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).

Proper case is Pythonic (based on existing usage of None, exception
names, etc.)

> ...


>
> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.

bool. If you've got it, use it.

>...


>
> Some external libraries (like databases and RPC packages) need to
> be able to distinguish between Boolean and integral values, and
> while it's usually possible to craft a solution, it would be
> easier if the language offered a standard Boolean type.

This is a VERY good reason IMHO.

> The standard bool type can also serve as a way to force a value to
> be interpreted as a Boolean, which can be used to normalize
> Boolean values. Writing bool(x) is much clearer than "not not x"
> and much more concise than
> if x:
> return 1
> else:
> return 0

Yes! I LIKE it.

> ...


>
> There's also the issue (which I've seen puzzling even experienced
> Pythonistas who had been away from the language for a while) that if
> you see:
>
> >>> cmp(a, b)
> 1
> >>> cmp(a, a)
> 0
> >>>
>
> you might be tempted to believe that cmp() also returned a truth
> value.

This one bit me in the early days.

> ...


>
> I don't see this as a problem, and I don't want evolve the
> language in this direction either; I don't believe that a stricter
> interpretation of "Booleanness" makes the language any clearer.

Ditto. "Language clarity" has been thrown around as a reason for all
kinds of much more invasive enhancements. Python IS clear, and *very*
few constructs borrowed from other languages are going to improve it
now. Just two reserved words, True and False, in proper case, are not
going to break much and just might add some of the clarity that everyone
seems to want to add.

Chris Gonnerman -- chris.g...@newcenturycomputers.net
http://newcenturycomputers.net


Erik Max Francis

unread,
Mar 30, 2002, 2:28:21 AM3/30/02
to
Guido van Rossum wrote:

> I offer the following PEP for review by the community. If it receives
> a favorable response, it will be implemented in Python 2.3.

Outstanding! I've been waiting and hoping for Booleans in Python since
I first was introduced to it.

> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

Yes, I believe so.

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

I agree with you; having repr(True) == str(True) == "True" makes sense
to me.

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).

I'm also a C, C++, and Java guy, but I think that True and False (rather
than true and false) are more Python, as you say, given None. Internal
consistency makes more sense to me than matching other languages.

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal). Personally,
> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.

No strong opinion here; either solution seems acceptable to me.

> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.

No strong opinion here either, leaning toward leaving it be. I think it
should return a bool, since it's effectively converting an arbitrary
expression to a Boolean, but with a bool type and the new trends toward
type unification, one could write bool(expr), which should be the
equivalent of operator.truth(expr) but with type bool, and is shorter.

> Because the repr() or str() of a bool value is different from an
> int value, some code (for example doctest-based unit tests, and
> possibly database code that relies on things like "%s" % truth)
> may fail. How much of a backwards compatibility problem this will
> be, I don't know. If we this turns out to be a real problem, we
> could changes the rules so that str() of a bool returns "0" or
> "1", while repr() of a bool still returns "False" or "True".

Where is the backward compatibility problem for using bool? At present,
no one uses it, so none of their types will be bools (right?). Even if
they happen to use the values True and False (or whatever gets adopted),
those can be overridden just like None, so if they define and use them
they should get their values, not Python's. Right?

> It has been suggested that, in order to satisfy user expectations,
> for every x that is considered true in a Boolean context, the
> expression x == True should be true, and likewise if x is
> considered false, x == False should be true.

I agree with your assessment; I don't agree at all with this suggestion.
6 is not equal to True, even if 6 when converted to a bool is a True.
Python doesn't do (and shouldn't do) this kind of implicit conversion,
so the objection does not follow.

--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Nationalism is an infantile sickness.
\__/ Albert Einstein
Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
A new, virtual planet, every day.

Erik Max Francis

unread,
Mar 30, 2002, 2:30:40 AM3/30/02
to
[Following up to my own post here.]

Erik Max Francis wrote:

> Where is the backward compatibility problem for using bool? At
> present,
> no one uses it, so none of their types will be bools (right?).

Wasn't think this one all the way through; of course, it's when people
do comparisons that now return bools and do something explicit with
their return value, rather than just using its implicit booleanness.
Never mind.

David Eppstein

unread,
Mar 30, 2002, 2:42:34 AM3/30/02
to
In article <3CA56915...@alcyone.com>,

Erik Max Francis <m...@alcyone.com> wrote:

> > I offer the following PEP for review by the community. If it receives
> > a favorable response, it will be implemented in Python 2.3.
>
> Outstanding! I've been waiting and hoping for Booleans in Python since
> I first was introduced to it.

It's not an important issue to me, but I like the PEP.

> > 3) Should the constants be called 'True' and 'False'
> > (corresponding to None) or 'true' and 'false' (as in C++, Java
> > and C99).
>
> I'm also a C, C++, and Java guy, but I think that True and False (rather
> than true and false) are more Python, as you say, given None. Internal
> consistency makes more sense to me than matching other languages.

What he said.

--
David Eppstein UC Irvine Dept. of Information & Computer Science
epps...@ics.uci.edu http://www.ics.uci.edu/~eppstein/

Robin Becker

unread,
Mar 30, 2002, 3:35:33 AM3/30/02
to
In article <mailman.101746697...@python.org>, Guido van
Rossum <gu...@python.org> writes
......
This pretty much seems unwanted to me. Done purely for political
correctness. Whenever new keywords are discussed the Gods are against
them. Now we have to accept new constants true, false + a new type.
Silly like all those programmers who have constants like one and zero or
ten in code.

If we get bools can sets be far behind, and what about quaternions and
abelian groups?

>Review
>
> Dear reviewers:
>
> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

no. If needed implement a library module for those who want to bog down
their code. This will not improve the python interpreter one bit and has
already consumed vast quantities of hot air ie has taken time and effort
away from more important issues.


>
> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)
>

if yes to 1, str(true) == "1", str(false) == "0"


> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).
>
> Most other details of the proposal are pretty much forced by the
> backwards compatibility requirement; e.g. True == 1 and
> True+1 == 2 must hold, else reams of existing code would break.
>

true, false


> Minor additional issues:
>
> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal). Personally,
> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.
>

no true==1, false==0 is what's required.


> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.

int
--
Robin Becker

Christian Tanzer

unread,
Mar 30, 2002, 2:38:01 AM3/30/02
to

Erik Max Francis <m...@alcyone.com> wrote:

> > Because the repr() or str() of a bool value is different from an
> > int value, some code (for example doctest-based unit tests, and
> > possibly database code that relies on things like "%s" % truth)
> > may fail. How much of a backwards compatibility problem this will
> > be, I don't know. If we this turns out to be a real problem, we
> > could changes the rules so that str() of a bool returns "0" or
> > "1", while repr() of a bool still returns "False" or "True".
>
> Where is the backward compatibility problem for using bool? At present,
> no one uses it, so none of their types will be bools (right?). Even if
> they happen to use the values True and False (or whatever gets adopted),
> those can be overridden just like None, so if they define and use them
> they should get their values, not Python's. Right?

The value of `"%s" (not x, )` is going to change. Any code depending
on the old way will break.

--
Christian Tanzer tan...@swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92


Christian Tanzer

unread,
Mar 30, 2002, 2:28:09 AM3/30/02
to

> 1) Should this PEP be accepted at all.

I can do without it, but wouldn't mind it, as long as bools don't get
too strict (like point 4, below). IMHO, Python's traditional concept
of truth is much better than a Pascal-like concept of truth.

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

If str and repr were to behave differently from each other, I'd expect
repr(True) to return "1" and str(True) to return "True". Interchanging
that seems strange.

OTOH, I'm worried about backwards compatibility.

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).

'True' and 'False', please. It makes shadowing of the built-in values
by user defined variables much less likely.

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal). Personally,
> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.

IMHO, `28+isleap(y)` is certainly better than `28+int(isleap(y))`.

Used judiciously, booleans in arithmetic expressions can improve
readability over conditional statements.

> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.

I'd expect operator.truth to be an alias for 'bool'.

If booleans couldn't be used in integer contexts any more, I'd prefer
operator.truth to return an int <wink>.

> Because of backwards compatibility, the bool type lacks many
> properties that some would like to see. For example, arithmetic
> operations with one or two bool arguments is allowed, treating
> False as 0 and True as 1. Also, a bool may be used as a sequence
> index.

Counting the number of true values in a collection is a common
operation. Using bool as an index is also commonly needed.

IMO, allowing booleans in these contexts is a good thing (TM) in
general, not only for backwards compatibility.

> Other languages (C99, C++, Java) name the constants "false" and
> "true", in all lowercase. In Python, I prefer to stick with the
> example set by the existing built-in constants, which all use
> CapitalizedWords: None, Ellipsis, NotImplemented (as well as all
> built-in exceptions). Python's built-in module uses all lowercase
> for functions and types only. But I'm willing to consider the
> lowercase alternatives if enough people think it looks better.

Please make it consistent with Python, not with an arbitrary set of
other languages.

> For truth testing of a value, one should use "if", e.g. "if x: print
> 'Yes'", not comparison to a truth value; "if x == True: print 'Yes'"
> is not only wrong, it is also strangely redundant.

`if x:` is clear, concise, and generic. Adding comparions or
an explicit coercion to bool makes it ugly and more difficult
to read.

******

How will bool influence '__nonzero__'? Currently, Python insists that
'__nonzero__ should return an int'. Will this be changed to 'should
return a bool'?

As that would break existing code, I hope not.

Ralph Corderoy

unread,
Mar 30, 2002, 4:23:28 AM3/30/02
to
Hi Guido,

> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

I've not coded heavily in a language with a boolean type since Fortran.
I'm willing to give it a go though.

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).

I'd much prefer true and false, but then I'd like none too. Given the
DarkAlley we've already started down I guess True and False would be
better as more consistent within the language. Any chance of built-in
constants being available as lower-case too? Or just true and false
for the moment?

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal).

Definitely not, that would just lead to more long-winded source for
little gain.

> Personally, I think we shouldn't; 28+isleap(y) seems totally
> reasonable to me.

Absolutely.

> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such.

Unlike Tim to produce such a poor reason. Has he been paraphrased a
little too much?

> I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change
> those to return a bool.

Right.

Cheers,


Ralph.

Paul Rubin

unread,
Mar 30, 2002, 4:36:43 AM3/30/02
to
Guido van Rossum <gu...@python.org> writes:
> Dear reviewers:
>
> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

I don't see much need for it. There's no need to turn Python into Java.
Python, C, and Lisp have all done fine without bools. What kinds of
programming tasks in Python are bools supposed to make easier?

> Some external libraries (like databases and RPC packages) need to
> be able to distinguish between Boolean and integral values, and
> while it's usually possible to craft a solution, it would be
> easier if the language offered a standard Boolean type.

Again, most of those libraries have C interfaces and (pre-C99) C
didn't have bools. I could imagine adding some kind of bool objects
in a loadable class for purposes like this, but don't see a need for
them to pervade the language. Enums or symbols would be more useful
than bools.

> Here are some arguments derived from teaching Python. When
> showing people comparison operators etc. in the interactive shell,
> I think this is a bit ugly:
>
> >>> a = 13
> >>> b = 12
> >>> a > b
> 1

Nah, if there's one thing everyone knows about computers, it's that
they use 1's and 0's to represent truth values.

> There's also the issue (which I've seen puzzling even experienced
> Pythonistas who had been away from the language for a while) that if
> you see:
>
> >>> cmp(a, b)
> 1
> >>> cmp(a, a)
> 0
> >>>
>
> you might be tempted to believe that cmp() also returned a truth
> value. If ints are not (normally) used for Booleans results, this
> would stand out much more clearly as something completely
> different.

If cmp returns a boolean, it can no longer distinguish the 3 cases
a < b, a == b, or a > b. That is seriously broken.

Brett Cannon

unread,
Mar 30, 2002, 4:39:52 AM3/30/02
to
On Sat, 30 Mar 2002, Guido van Rossum wrote:

[snip]


> 1) Should this PEP be accepted at all.
>

Personally, I feel no great need for booleans, but it wouldn't hurt to
have them either. We all do the usual return 1 if true else return 0
standard on boolean-like methods, so it isn't like they would go unused.

But we do have that basic standard going and it is not that much more code
to handle. Python has always gone for verbose over shortcuts, and I can
easily view booleans as just a shortcut to appease people from other
languages.

Personally, I would give a +0 vote just because this is a common enough
case that a shortcut would be nice.


> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)
>

Return "True". I agree on the strange looking part. Plus we can only
bend over backwards so much for compability. I doubt the amount of code
that would be broken justifies the strangeness of returning "1".


> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).
>

If this is done, make it Pythonic. If we cared about being like other
langauges we wouldn't use Python because of that "funky whitespace
mattters stuff" issue. Go with 'True' and 'False'.


> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal). Personally,
> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.

I agree with this. Thanks to the standard way of representing false as 0
and true as everything else (but almost always as 1), I see no reason to
not treat it as such behind the scenes in terms of operations. Allows all
of us warped by C to continue to fool ourselves into treating boolean
values as ints.


>
> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.
>

I say return boolean. This goes back to my view of not worrying about
backwards compatibility as much as general correctness and being more
Pythonic.

This whole thing is in a way saying that we should have had booleans a
while back. So why not just do a complete cleanup of the situation and do
it right.


> Many programmers apparently feel the need for a Boolean type; most
> Python documentation contains a bit of an apology for the absence
> of a Boolean type. I've seen lots of modules that defined
> constants "False=0" and "True=1" (or similar) at the top and used
> those. The problem with this is that everybody does it
> differently. For example, should you use "FALSE", "false",
> "False", "F" or even "f"? And should false be the value zero or
> None, or perhaps a truth value of a different type that will print
> as "true" or "false"? Adding a standard bool type to the language
> resolves those issues.
>

Consistency is obviously the big draw for this. Since truth can be viewed
as anything not 0 or None, it is rather open and not standardized
officially. But we all treat 1 as true and 0 or None as false already.
Plus if someone feels the need to have the syntactic sugar for True and
False, they can do it themselves as mentioned above.

But the frequency of this in code, IMO, is frequent enough to warrant at
least considering the sugar. Everyone uses booleans in there code in some
form. And if having a standardized way of representing them makes
maintaining code that much easier, so be it.

-Brett C.

Tim Peters

unread,
Mar 30, 2002, 4:35:32 AM3/30/02
to
[Christian Tanzer]
> ...

> If str and repr were to behave differently from each other, I'd expect
> repr(True) to return "1" and str(True) to return "True". Interchanging
> that seems strange.

We try to ensure that eval(repr(x)) reproduce x whenever reasonably
possible. That best way to do that here is for repr(True) to return 'True'.
We also try to ensure that str(x) be "friendly" whenever possible, even if
that means eval(str(x)) has no chance of reproducing x exactly, or even of
running without raising an exception. The best way to do that here is also
for str(True) to return 'True', but:

> OTOH, I'm worried about backwards compatibility.

That's the only reason for str(True) to return '1'. How about str(True)
return '1' but str(False) return 'False'? That's what a committee would
compromise on <wink>.

> ...


> How will bool influence '__nonzero__'? Currently, Python insists that
> '__nonzero__ should return an int'. Will this be changed to 'should
> return a bool'?

I hope so.

> As that would break existing code, I hope not.

No, "should" != "must". Guido won't call code that returns an int here
broken, although he might call it deprecated, and leave you wondering when
the hammer will drop <wink>.


Tim Peters

unread,
Mar 30, 2002, 4:45:04 AM3/30/02
to
[Guido]

>> 5) Should operator.truth(x) return an int or a bool. Tim Peters
>> believes it should return an int because it's been documented
>> as such.

[Ralph Corderoy]


> Unlike Tim to produce such a poor reason. Has he been paraphrased a
> little too much?

Not in Guido's eyes <wink>. We don't need 3 equivalent ways to turn an
arbitrary expression into a bool ("bool(x)" same-as "not not (x)" same-as
"truth(x)"). *Especially* if str(bool) and repr(bool) produce 'True' and
'False', people have a legitimate need to make an arbitrary true/false
expression produce 0 and 1 too, if only to preserve 0/1-based true/false
output. operator.truth() has always been the best way to do exactly that.
Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0,
1)[boolexpr]" reek in comparison.


Mark McEahern

unread,
Mar 30, 2002, 6:01:36 AM3/30/02
to
[Guido]

> 1) Should this PEP be accepted at all.

+1

[Paul Rubin]


> I don't see much need for it. There's no need to turn Python into Java.
> Python, C, and Lisp have all done fine without bools. What kinds of
> programming tasks in Python are bools supposed to make easier?

I view the proposal not as 'making programming tasks easier' but as
improving the readability of Python code. If the proposal can achieve the
latter without 'making programming tasks harder', it seems like an obvious
win.

// mark


Ralph Corderoy

unread,
Mar 30, 2002, 6:39:51 AM3/30/02
to
Hi Tim,

Aha! Well, now I've got your side of the argument, and you've
co-incidentally snipped Guido's point of view, I'm firmly in favour of
yours ;-)

I've happily used `!!x' in C and found `not not x' in Python wordy so
I'm much in favour of operator.truth returning 0 or 1.

Cheers,


Ralph.

Martin v. Loewis

unread,
Mar 30, 2002, 6:46:03 AM3/30/02
to
Paul Rubin <phr-n...@nightsong.com> writes:

> I don't see much need for it. There's no need to turn Python into Java.
> Python, C, and Lisp have all done fine without bools.

C99 has stdbool.h, though.

> What kinds of programming tasks in Python are bools supposed to make
> easier?

RPC implementations (see the rationale in the PEP), XPath processors.

> > Some external libraries (like databases and RPC packages) need to
> > be able to distinguish between Boolean and integral values, and
> > while it's usually possible to craft a solution, it would be
> > easier if the language offered a standard Boolean type.
>
> Again, most of those libraries have C interfaces

Actually, no. Most of those libraries are pure-Python. Those that do
use C interfaces need to expose the bool types of the C interface.

> and (pre-C99) C didn't have bools.

Many C programs (in particular pre-C99) have bools. Not just one, but
hundreds of them. C99 introduces an additional one, which it calls the
"standard" boolean type.

Regards,
Martin

John Roth

unread,
Mar 30, 2002, 7:31:42 AM3/30/02
to

"Robin Becker" <ro...@jessikat.fsnet.co.uk> wrote in message
news:2zRcLUAV...@jessikat.fsnet.co.uk...

> In article <mailman.101746697...@python.org>, Guido van
> Rossum <gu...@python.org> writes
> ......
> This pretty much seems unwanted to me. Done purely for political
> correctness. Whenever new keywords are discussed the Gods are against
> them. Now we have to accept new constants true, false + a new type.
> Silly like all those programmers who have constants like one and zero
or
> ten in code.

Disagree strongly. One of the things that makes a programming
language pleasant is that you can **depend** on certain constructions.
Having a bool type, properly implemented, is IMHO definitely in
line with that - I've always thought that 0 and 1 were a kludge put
into languages by designers that were too lazy to do it right.

> If we get bools can sets be far behind, and what about quaternions and
> abelian groups?

I could see sets as part of the core language, if a couple of issues
with respect to notation could be cleared up. I don't see the other
two, but then, I don't really think that complex numbers should have
been part of the core language either.

It depends on what can be used by most applications. Sets and
enums are generally useful. Complex, quaternians and so forth
are application specific things.

John Roth

John Roth

unread,
Mar 30, 2002, 7:46:29 AM3/30/02
to

"Guido van Rossum" <gu...@python.org> wrote in message
news:mailman.101746697...@python.org...

> I offer the following PEP for review by the community. If it receives
> a favorable response, it will be implemented in Python 2.3.
>
> I'm particularly interested in hearing your opinion about the
> following three issues:
>
> 1) Should this PEP be accepted at all.

Yes. I think it will improve the readability of code.

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

That's a hard one. In general, I'd have to go with str(True)
returning 1 for compatability reasons. If you don't, I would
expect unit test suites to break, as well as anything that
externalizes values as strings and then loads them again.

Also, repr() should be documented as being changable
from release to release - that is, the result of repr() is intended
to be fed back into eval() in that release.

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).

Keep it consistent with None. True and False.

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal). Personally,
> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.

Actually, the example seems totally unreasonable to me. It's
treating the fact that February in a leap year has one more day
than February in a non leap year as a magic number. Bad! Bad!

More to the point, if bool is a subtype of integer, I don't see
anything wrong with the type coercion, and I don't see very
much value with the purist viewpoint. This could be looked at
again if there is ever a version of Python with strong typing.

> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.

Logically, it should return a bool. However, I'm quite willing
to settle for whatever is needed for compatability (breaking the
least amount of code.)

John Roth


Paul Rubin

unread,
Mar 30, 2002, 7:51:53 AM3/30/02
to
"John Roth" <john...@ameritech.net> writes:
> > If we get bools can sets be far behind, and what about quaternions and
> > abelian groups?
>
> I could see sets as part of the core language, if a couple of issues
> with respect to notation could be cleared up. I don't see the other
> two, but then, I don't really think that complex numbers should have
> been part of the core language either.

There's a PEP for sets that looks pretty good to me. They look
more useful than bools. They actually make some tasks easier.
I haven't heard yet how bools make anything easier.

> It depends on what can be used by most applications. Sets and
> enums are generally useful. Complex, quaternians and so forth
> are application specific things.

quaternions can be implemented by a module like cmath, if useful.
Alternatively they can be represented as 3x3 matrices in Numeric.

Roy Smith

unread,
Mar 30, 2002, 8:14:34 AM3/30/02
to
What should the following examples print?

>>> print {} == False
>>> print {} is False

I'm convinced the second one should print "False", but I'm not really sure
about the first. I also assume that

>>> print False is not True

should print "True"?

For those thinking ahead to obfuscated Python contests, I can see having
lots of fun with this. The following, for example, is a valid Python
program under this PEP:

False is not True is not "False is not True"

Pearu Peterson

unread,
Mar 30, 2002, 8:40:17 AM3/30/02
to

> ----- Original Message -----
> From: "Guido van Rossum" <gu...@python.org>
>
> > Dear reviewers:
> >
> > I'm particularly interested in hearing your opinion about the
> > following three issues:
> >
> > 1) Should this PEP be accepted at all.

It seems that this is already decided as Guido is the author and also the
only one who accepts PEPs.

> > The standard bool type can also serve as a way to force a value to
> > be interpreted as a Boolean, which can be used to normalize
> > Boolean values. Writing bool(x) is much clearer than "not not x"
> > and much more concise than
> > if x:
> > return 1
> > else:
> > return 0

This one does not convince me at all as one could always define

bool = lambda x: not not x

and I would never write such a verbose code fragment as above just to
return whether x is false or true. However, using constructs like

if x:
...

while x:
...

for x being a sequence or dictionary can be very useful and efficient.

In future (Python 2.>=3, >3), are these constructs valid or must they
be replaced with

while bool(x):
...

? :(


Ka-Ping Yee has raised related conserns in

http://mail.python.org/pipermail/python-dev/2002-March/020893.html

that never got a proper answer from Guido nor others.

So, I am (-1)*0 on this PEP.

-1 --- I have succesfully programmed in Python without needing the bool
function and I share Ka-Ping's concerns about Python future. To me the
only reasonable point in rationale seems to be that "other languages have
or will have boolean". That also sounds quite weak to me --- other
languages have many useful concepts that would be more worth for
introducing to Python than this boolean concept.

0 --- this PEP will be hardly rejected, it seems to me.

Regards,
Pearu

Guido van Rossum

unread,
Mar 30, 2002, 8:38:00 AM3/30/02
to
> [Guido]

> >> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> >> believes it should return an int because it's been documented
> >> as such.
>
> [Ralph Corderoy]
> > Unlike Tim to produce such a poor reason. Has he been paraphrased a
> > little too much?

[Tim]


> Not in Guido's eyes <wink>. We don't need 3 equivalent ways to turn an
> arbitrary expression into a bool ("bool(x)" same-as "not not (x)" same-as
> "truth(x)"). *Especially* if str(bool) and repr(bool) produce 'True' and
> 'False', people have a legitimate need to make an arbitrary true/false
> expression produce 0 and 1 too, if only to preserve 0/1-based true/false
> output. operator.truth() has always been the best way to do exactly that.
> Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0,
> 1)[boolexpr]" reek in comparison.

Tim must be missing something. The obvious way to turn a bool b into
an int is int(b). Having to import the obscure 'operator' module for
this purpose is backwards. (IMO there's almost *never* a reason to
import that module anyway.)

Peter Hansen

unread,
Mar 30, 2002, 11:08:10 AM3/30/02
to
Mark McEahern wrote:
>
> [Paul Rubin]
> > I don't see much need for it. There's no need to turn Python into Java.
> > Python, C, and Lisp have all done fine without bools. What kinds of
> > programming tasks in Python are bools supposed to make easier?
>
> I view the proposal not as 'making programming tasks easier' but as
> improving the readability of Python code. If the proposal can achieve the
> latter without 'making programming tasks harder', it seems like an obvious
> win.

Okay, can somebody please prove that?

Are there code snippets which clearly have significantly improved
readability as a result of a rewrite using the proposed bool?

Without that, I'm a strong -1 on this and other such proposals.

-Peter

Greg Weeks

unread,
Mar 30, 2002, 9:49:01 AM3/30/02
to
Guido van Rossum (gu...@python.org) wrote:
: I offer the following PEP for review by the community. If it receives

: a favorable response, it will be implemented in Python 2.3.

Having read this note (and nothing else on the subject), I vote "no".

I would, though, be happy to see built-in variables bound to 0 and 1.

Here is the argument that I find most compelling. The annoyance of
seeing

>>> true
1

is more than offset by the value of being reminded that Python, unlike
Java, attributes truth and falsity to objects that are not explicitly
boolean.


Greg

Martin v. Loewis

unread,
Mar 30, 2002, 12:19:23 PM3/30/02
to
Peter Hansen <pe...@engcorp.com> writes:

> Are there code snippets which clearly have significantly improved
> readability as a result of a rewrite using the proposed bool?

The standard library has 110 occurrences of "return 0", 70 occurrences
of "return 1", and 136 occurrences of "return None". Optimistically,
this makes 300 functions. It would help users of these 300 functions
if they would know whether those functions return a boolean or an
integral value (if integral, what range?); for the "return None"
cases, the boolean type would help to clarify whether this is "return
no value", "return False", or "return nil object";

Regards,
Martin

Peter Hansen

unread,
Mar 30, 2002, 12:42:39 PM3/30/02
to

So does this change proposes to change the readability so that
it is clear at a glance (at the source, not the documentation, which
seems an odd thing to base this on) that those functions return
boolean conditions rather than integers?

If that is _all_ this change does, I suppose it would be okay.
If it in _any way_ changes the functionality one can currently
expect for those return values, such as the ability to use as
indices into a sequence, then I'm still very -1.

I like Greg's response too. The improved readability does not
appear to outweigh the disadvantages of making Python's special
behaviour clear.

Furthermore, there will be code breakage, and that should always
rate very high on the list of reasons to leave well enough alone.

-Peter

Ralph Corderoy

unread,
Mar 30, 2002, 12:35:27 PM3/30/02
to
Hi Guido,

> > Not in Guido's eyes <wink>. We don't need 3 equivalent ways to
> > turn an arbitrary expression into a bool ("bool(x)" same-as "not
> > not (x)" same-as "truth(x)"). *Especially* if str(bool) and
> > repr(bool) produce 'True' and 'False', people have a legitimate
> > need to make an arbitrary true/false expression produce 0 and 1
> > too, if only to preserve 0/1-based true/false output.
> > operator.truth() has always been the best way to do exactly that.
> > Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and
> > "(0, 1)[boolexpr]" reek in comparison.
>
> Tim must be missing something. The obvious way to turn a bool b into
> an int is int(b). Having to import the obscure 'operator' module for
> this purpose is backwards. (IMO there's almost *never* a reason to
> import that module anyway.)

I thought Tim was trying to map a range of integer values onto just 0
and 1 as ints, not False and True, where as you're suggesting he just
wants to get an int from a boolean. I think he has an expression like
day_of_month, e.g. 30, and wants a 0 or 1 from it.

I could easily be wrong here.


Ralph.

Guido van Rossum

unread,
Mar 30, 2002, 1:09:54 PM3/30/02
to
[me]

> > Tim must be missing something. The obvious way to turn a bool b into
> > an int is int(b). Having to import the obscure 'operator' module for
> > this purpose is backwards. (IMO there's almost *never* a reason to
> > import that module anyway.)

[Ralph]


> I thought Tim was trying to map a range of integer values onto just 0
> and 1 as ints, not False and True, where as you're suggesting he just
> wants to get an int from a boolean. I think he has an expression like
> day_of_month, e.g. 30, and wants a 0 or 1 from it.

I should've said int(bool(x)) for any expression x. When I wrote int(b) I
meant b to be a value that was already a bool.

David Eppstein

unread,
Mar 30, 2002, 1:04:17 PM3/30/02
to
In article <a84t0v$k7u$1...@inputplus.demon.co.uk>,
ra...@inputplus.demon.co.uk (Ralph Corderoy) wrote:

If that's what he's doing, int(bool(x)) is still much clearer than the
alternative bool-to-int expressions that (as he says) reek.

Guido van Rossum

unread,
Mar 30, 2002, 1:10:28 PM3/30/02
to
[me]

> > Tim must be missing something. The obvious way to turn a bool b into
> > an int is int(b). Having to import the obscure 'operator' module for
> > this purpose is backwards. (IMO there's almost *never* a reason to
> > import that module anyway.)

[Ralph]


> I thought Tim was trying to map a range of integer values onto just 0
> and 1 as ints, not False and True, where as you're suggesting he just
> wants to get an int from a boolean. I think he has an expression like
> day_of_month, e.g. 30, and wants a 0 or 1 from it.

I should've said int(bool(x)) for any expression x. When I wrote int(b) I


meant b to be a value that was already a bool.

--Guido van Rossum (home page: http://www.python.org/~guido/)

Ken Peek

unread,
Mar 30, 2002, 1:51:24 PM3/30/02
to
Guido van Rossum <gu...@python.org> wrote in message news:<mailman.1017495346...@python.org>...

I don't see that adding a "bool" (or better: "boolean", since I HATE
abbreviated words) would be such a big issue. This would allow for
better "readability" of the code. ("Readability" being defined as
maximally exposing the intentions of the programmer to the largest
audience of readers as is practical.) Comparison operators (under the
hood) should return a "boolean", so that if you type:

>>> 1 < 2
True
>>> 1 > 2
False

Yes-- I think there should have to be some type conversion required if
you need to use your boolean in an expression. The idea being, that
you shouldn't be using a "boolean" in an expression anyway, unless it
is some kind of obscure programming trick (which should be depricated
anyway.)

If no one can agree on how the boolean type should be implemented,
then leave it the way it is, and add a "readonly" keyword-- which
would be useful for other constants as well:

readonly:
# attempts to write to these will throw a
# "TypeError: attempted write to a constant"
False = 0
True = 1
MY_CONSTANT = 42

As to the case of the keywords-- well, I prefer all uppercase for
constants, because I think they stand out better when reading code. I
don't think this should be forced by the language though-- let people
do whatever they want-- why be a baby sitter?

Regardless of whether or not a boolean type is implemented-- in my
code, I would simply define:
TRUE = True
FALSE = False

And if the 'readonly' construct is implemented:
readonly:
TRUE = True
FALSE = False

I then use TRUE and FALSE in my code instead of True and False.
Problem solved (for ME anyway). The 'readonly' keyword would be VERY
helpful though (to catch programming mistakes)-- which happen a lot
for me, anyway...

Martin v. Loewis

unread,
Mar 30, 2002, 3:48:04 PM3/30/02
to
Peter Hansen <pe...@engcorp.com> writes:

> So does this change proposes to change the readability so that
> it is clear at a glance (at the source, not the documentation, which
> seems an odd thing to base this on) that those functions return
> boolean conditions rather than integers?

The documentation should change as all, documenting that certain
functions return bool.

> If that is _all_ this change does, I suppose it would be okay.
> If it in _any way_ changes the functionality one can currently
> expect for those return values, such as the ability to use as
> indices into a sequence, then I'm still very -1.

Their type changes, and their repr. Apart from that, nothing changes.

> Furthermore, there will be code breakage, and that should always
> rate very high on the list of reasons to leave well enough alone.

Can you show examples of (real!) code that will break? Preferably code
you've written yourself.

Regards,
Martin

Terry Reedy

unread,
Mar 30, 2002, 3:52:47 PM3/30/02
to

"Guido van Rossum" <gu...@python.org> wrote in message
news:mailman.101746697...@python.org...

> I offer the following PEP for review by the community. If it
receives
> a favorable response, it will be implemented in Python 2.3.

> 1) Should this PEP be accepted at all.

+0.8 -- as long as it is not a first step in de-arithmetizing truth
values.

Proposed amendment: call the new type 'truth' instead of 'bool' and
change the title of the PEP to "Formalizing a Python truth type".

A. This PEP formalizes existing Python practice in regards to truth
values. The 'new' type is not really new. The main visible effect is
to change the display of the doubleton values. The existing magic
method is __truth__(). Better to call the new type and constructor
truth() than to change __truth__ () to __bool__().

B. 'bool' is an abbreviation of Boolean, the adjectival form of Boole,
an English mathematician. I agree with the philosophical argument for
nomenclature that is descriptive rather than 'nymic' (named after
persons -- I forget the formal linguistic term for such). All other
Python terms that I can think of (except for the name Python itself)
follow this sensible principle. To me, naming one particular type
after a person is somewhat jarring, especially when it is not
necessary.

C. Anyone learning Python has some idea of truth and truth values.
But I am sure there are some with no idea of what 'bool' means and
only a vague idea about 'Boolean'. Better formalizing Python truth
values should make them even easier to learn; why not call them what
they are?

D. The word bool(ean) carries a lot of baggage in terms of expected
behavior and *limitations* on behavior. At least half the debate on
this PEP revolves around the fact that Python truth values act
differently from 'proper' boolean values. The title of this PEP,
"Adding a bool type", is arguably misleading since the newly
formalized type will not be boolean as many understand the term.

If we do not call Python truth values what they are not quite, or
rather what they are more than, we avoid the mismatch between
expectation and reality (and years of requests to change reality to
match expectation). In other words, the critics are partly right;
however, my solution is to drop the slightly misleading word bool (and
its associated baggage) instead of changing current (and proposed)
behavior (which I think is pretty good).

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

I can see it either way.

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++,
Java
> and C99).

+ 1 for True/False to corresponding to None, etc. Do true/false work
*exactly* the same way in all three other languages? Will Python
True/False be exactly the same? (I suspect not but simply do not
know.)

> True+1 == 2 must hold, else reams of existing code would break.

yes, yes, yes. While this may not be 'proper' boolean behaviour, it
is current Python truth value behaviour.

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1
> would eventually (e.g. in Python 3000 be illegal).

no, no, no. Eliminating useful polymorohic behavior is hardly
Pythonic.

If the new type were called 'truth' (as suggested above, or 'binary')
instead of 'bool', this question would hardly arise. The behavior of
Python truth values is, for the most part, a *superset* of some
preconceived notions of allowed 'Boolean' operations. So what? This
is true of any type which inherits methods from two base types (see
below).

> I think we shouldn't; 28+isleap(y) seems totally reasonable
to me.

Forcing this and all similar constructions to be written as
'28+int(isleap(y))' gains nothing and goes against general Pythonic
polymorphism. Why should one be able to add instances of arbitrary
user-written classes to 28 but not instances of bool/truth?

I understand OO purist objections, but Python is simply not an
OO-purity language.
Documentation makes no claim about what one 'ought' to be able to do
with instances of derived classes versus instances of super-classes.

> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented

> as such. I think it should return a bool; most other
standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change
those
> to return a bool.

I think I would find it odd as new learner to have this one 'logical'
function not return bool.

> Note that subclassing from int means that True+1 is valid and
> equals 2, and so on. This is important for backwards
> compatibility: because comparisons and so on currently return
> integer values, there's no way of telling what uses existing
> applications make of these values.

> Because of backwards compatibility, the bool type lacks many
> properties that some would like to see.

?? Because of backwards compatibility, the bool (Python truth) type
will have properties that I *want* to keep.

> For example, arithmetic operations with one or two bool arguments


> is allowed, treating False as 0 and True as 1.

suitibility = has_a(x) + is_b(x) + does_c(x)

Again, wrapping each term in int() in the service of pedantry does not
strike me as Pythonic. Admittedly, I could define class mybool(int)
(using the reference implementation given in PEP + whatever needed to
make mixed expressions work) and have all predicates I write return
mybool instead of bool(truth). But having to do seems worse that
present situation.

> Also, a bool may be used as a sequence index.

(option_a, option_b)[binary_switch] # can be quite useful

> I don't see this as a problem, and I don't want evolve the
> language in this direction either; I don't believe that a
stricter
> interpretation of "Booleanness" makes the language any clearer.

Completely agreed. Again, these issues seem to arise from calling
Python truth values 'bool'. Conceptually, they inherit behavior from
both int and bool (in the strict sense).

> Another consequence of the compatibility requirement is that the
> expression "True and 6" has the value 6, and similarly the
> expression "False or None" has the value None. The "and" and
"or"
> operators are usefully defined to return the first argument that
> determines the outcome, and this won't change; in particular,
they
> don't force the outcome to be a bool.

Some languages use 'cand' and 'cor' to differentiate short-circuiting
'conditional'
and/or from strictly logical and/or, but I am glad Python does not.
In any case, Pythons and/or are Python truth value operators, not
Boolean operators.

About deriving bool from int: a couple of years ago, I followed a
looooong thread on comp.object about the relationship of circles and
ellipses and which should be derived from which. The problem for oo
theory, it seems to me, is that specialization can take place either
by addition -- a bird is a vertebrate that can fly -- or by
subtraction -- a ratite is a bird that cannot fly. Evolution does not
follow substitutivity rules. Neither do mathematicians and
programmers.

Terry J. Reedy

Ype Kingma

unread,
Mar 30, 2002, 4:23:54 PM3/30/02
to
Guido,

you wrote:
>
> I offer the following PEP for review by the community. If it receives
> a favorable response, it will be implemented in Python 2.3.
>

Thanks for this opportunity.

> http://python.org/sf/528022


>
> --Guido van Rossum (home page: http://www.python.org/~guido/)
>

> PEP: 285
> Title: Adding a bool type
> Version: $Revision: 1.12 $
> Last-Modified: $Date: 2002/03/30 05:37:02 $
> Author: gu...@python.org (Guido van Rossum)
> Status: Draft
> Type: Standards Track
> Created: 8-Mar-2002
> Python-Version: 2.3
> Post-History: 8-Mar-2002, 30-Mar-2002
>
> Abstract
>
> This PEP proposes the introduction of a new built-in type, bool,
> with two constants, False and True. The bool type would be a
> straightforward subtype (in C) of the int type, and the values
> False and True would behave like 0 and 1 in most respects (for
> example, False==0 and True==1 would be true) except repr() and
> str(). All built-in operations that conceptually return a Boolean
> result will be changed to return False or True instead of 0 or 1;
> for example, comparisons, the "not" operator, and predicates like
> isinstance().
>
> Review


>
> Dear reviewers:
>
> I'm particularly interested in hearing your opinion about the
> following three issues:
>

> 1) Should this PEP be accepted at all.

Partially.


I think there is no point in maintaining backward compatibility
of the assumptions that True == 1 and False == 0.
Please don't subtype int to define bool.

Within the language a 'cast to boolean' should be implied when a boolean
value is expected (ie. after 'if' and 'while'). This is in line with
the current situation. Making this cast to boolean explicit in the language
definition even simplifies the language definition.

>
> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)
>

str(True) should return "True".

> 3) Should the constants be called 'True' and 'False'
> (corresponding to None) or 'true' and 'false' (as in C++, Java
> and C99).
>

Caps.

> Most other details of the proposal are pretty much forced by the
> backwards compatibility requirement; e.g. True == 1 and


> True+1 == 2 must hold, else reams of existing code would break.
>

This can be handled by deprecation and eg. 'from __future__ import bool',
or by unundeprecation: 'from __past__ import nonbool'.

This might seem rather radical, but in C a similar thing has happened:
the compiler would silently cast a C int to a C pointer in earlier
versions of the language. Nowadays no C programmer would even dare
to think that way.

> Minor additional issues:


>
> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1

> would eventually (e.g. in Python 3000 be illegal). Personally,


> I think we shouldn't; 28+isleap(y) seems totally reasonable to
> me.
>

28+isleap(y) might seem reasonable now, but one should hope/assume that
Python outlives C at which point it will/would be just ballast.

Some other arguments against 28+isleap(y):
- explicit 28+int(isleap(y)) is better than implicit.
- here isleap should have been called onewhenleap in the first place.
- a current boolean function might return eg. a non empty list or an Ellipsis
to indicate a True return value, resulting in an appropriate TypeError here.

A bool is a bool and an int is an int.
The only relation between them is that they have to be implemented using
bits of a computer.
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.

Somehow this reminds me of subclassing Square from Rectangle:
it just doesn't feel right, even though it might work.
One should avoid subclassing a class that has instantiations.
Could someone provide a reference for this with a title
that ends in 'considered harmful'?


> 5) Should operator.truth(x) return an int or a bool. Tim Peters
> believes it should return an int because it's been documented
> as such. I think it should return a bool; most other standard
> predicates (e.g. issubtype()) have also been documented as
> returning 0 or 1, and it's obvious that we want to change those
> to return a bool.
>

Predicates should return a bool.

> Rationale
>
> Most languages eventually grow a Boolean type; even C99 (the new
> and improved C standard, not yet widely adopted) has one.


>
> Many programmers apparently feel the need for a Boolean type; most
> Python documentation contains a bit of an apology for the absence
> of a Boolean type. I've seen lots of modules that defined
> constants "False=0" and "True=1" (or similar) at the top and used
> those. The problem with this is that everybody does it
> differently. For example, should you use "FALSE", "false",
> "False", "F" or even "f"? And should false be the value zero or
> None, or perhaps a truth value of a different type that will print
> as "true" or "false"? Adding a standard bool type to the language
> resolves those issues.
>

> Some external libraries (like databases and RPC packages) need to
> be able to distinguish between Boolean and integral values, and
> while it's usually possible to craft a solution, it would be
> easier if the language offered a standard Boolean type.
>

That would be nice. Currently in jython one has to use java.lang.Bool
to call an overloaded java method that is defined with both a java boolean
and with a java int as argument. This does not happen too often,
but mapping a python bool to (and from) a java bool sure sounds good.

> The standard bool type can also serve as a way to force a value to
> be interpreted as a Boolean, which can be used to normalize
> Boolean values. Writing bool(x) is much clearer than "not not x"
> and much more concise than
>
> if x:
> return 1
> else:
> return 0
>

That would be great, however such functions should not be named as predicates,
they should be named onewhen...

<snip>

>
> Compatibility


>
> Because of backwards compatibility, the bool type lacks many

> properties that some would like to see. For example, arithmetic


> operations with one or two bool arguments is allowed, treating

> False as 0 and True as 1. Also, a bool may be used as a sequence
> index.
>

The only reason that it works now is the C heritage as explained above.
Why not use this as an opportunity to get rid of it?

With a non int bool, True and False would be real singletons:

bool(1) is True
bool(0) is False

True is not 1
True != 1
False is not 0
False != 0


Subclassing bool from int would also force 1 and 0 to be become
real singletons. The only reason this would work is that current
python implementations happen to implement 1 and 0 in this way.
This is related to subclassing an instantiated class, which should
be avoided, I think.

> I don't see this as a problem, and I don't want evolve the
> language in this direction either; I don't believe that a stricter
> interpretation of "Booleanness" makes the language any clearer.

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.

> Another consequence of the compatibility requirement is that the
> expression "True and 6" has the value 6, and similarly the
> expression "False or None" has the value None. The "and" and "or"
> operators are usefully defined to return the first argument that
> determines the outcome, and this won't change; in particular, they

> don't force the outcome to be a bool. Of course, if both
> arguments are bools, the outcome is always a bool. It can also
> easily be coerced into being a bool by writing for example
> "bool(x and y)".

These would work in the same way with a "non int" bool as I would prefer to have.

<snip>

Regards, and thanks again for the opportunity,

Ype.

dsavitsk

unread,
Mar 30, 2002, 4:10:33 PM3/30/02
to

"Robin Becker" <ro...@jessikat.fsnet.co.uk> wrote in message
news:2zRcLUAV...@jessikat.fsnet.co.uk...
> In article <mailman.101746697...@python.org>, Guido van
> Rossum <gu...@python.org> writes
> ......

***

> > 1) Should this PEP be accepted at all.

> no. If needed implement a library module for those who want to bog down
> their code. This will not improve the python interpreter one bit and has
> already consumed vast quantities of hot air ie has taken time and effort
> away from more important issues.

I second this suggestion. The language is good, and the presumption should
be not to change it w/o substantial reason. This doesn't seem like there is
substantial reason to me.

***

> --
> Robin Becker


Boris Qaré

unread,
Mar 30, 2002, 3:41:19 PM3/30/02
to
Martin v. Loewis wrote:
>

> > expect for those return values, such as the ability to use as
> > indices into a sequence, then I'm still very -1.
>
> Their type changes, and their repr. Apart from that, nothing changes.

How's that ? What's the point of making bool a type if we
can't subclass methods for __and__, __or__, __or_not__,
etc ? (we could still save the shortcut semantics by having
the other parameter appear as a generator, e.g., one should
call other.next() to get at the value)

Regards, Boris
--
Python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT")

Martin v. Loewis

unread,
Mar 30, 2002, 5:00:51 PM3/30/02
to
"Terry Reedy" <tej...@yahoo.com> writes:

> A. This PEP formalizes existing Python practice in regards to truth
> values. The 'new' type is not really new. The main visible effect is
> to change the display of the doubleton values. The existing magic
> method is __truth__(). Better to call the new type and constructor
> truth() than to change __truth__ () to __bool__().

The existing magic method is __nonzero__, and the PEP does not propose
to change it...

Regards,
Martin

Martin v. Loewis

unread,
Mar 30, 2002, 4:58:45 PM3/30/02
to
"Boris Qaré" <bor...@geneva-link.ch> writes:

> How's that ? What's the point of making bool a type if we
> can't subclass methods for __and__, __or__, __or_not__,

> etc ? we could still save the shortcut semantics ...

Those are redefined in bool (although the third one is name __xor__);
but they refer to the bitwise operators, &, |, ^.

The shortcut construct (and, or) won't change under this PEP.

Regards,
Martin

Jimmy Retzlaff

unread,
Mar 30, 2002, 4:22:13 PM3/30/02
to
Greg Weeks wrote:
> I would, though, be happy to see built-in variables bound to 0 and 1.

I assume you mean that the only change would be to implicitly have
built-ins like:

False = 0
True = 1

There is a trap with this approach in that some people will come to
conceptualize False/True as being instances of a Boolean type, even
though they are not. Consider code like:

if MyCoolFunction(12.3) == True:
print 'cool'

If MyCoolFunction returns a "true" value which is not 1 (e.g., -1), then
this code will not take the path suggested by the misconception that
True is an instance of a proper type (which would imply robust
implementations of comparison operators).

This trap is common in C/C++ code that #defines true and false. Some
people have to be constantly reminded not to compare to true, and those
reminders all too often come in the form of long debugging sessions.

Jimmy

Erik Max Francis

unread,
Mar 30, 2002, 5:18:54 PM3/30/02
to
Paul Rubin wrote:

> I don't see much need for it. There's no need to turn Python into
> Java.
> Python, C, and Lisp have all done fine without bools. What kinds of
> programming tasks in Python are bools supposed to make easier?

Comparing Python's lack of a Boolean type to C (which _does_ have one in
the latest C99 Standard, so I'll presume you mean C89) and Lisp seems
somewhat unfair, since their conceptions of what is true and false are
much simpler than Python's. In C, any non-zero value (integral or
floating point) or null pointer is true; in Lisp, any non-nil value is
true. Lisp even has a special symbol for representing explicit truth:
t.

Python's non-bool concept of truth is much more complicated, as many
things can be false: 0, 0.0, 0-as-rational (when and if that happens),
empty strings, empty lists, empty tuples, empty dictionaries, and --
more importantly -- any class instance that implements the __nonzero__
method to return one of the above values.

I'd say that C and Lisp lacking a Boolean type is in a different
category of language design than Python lacking one. Truth testing is
so simple in C and Lisp that you can get away with not having one pretty
easily. I don't think that's the case for Python; Python's lack of a
Boolean data type is one of the few things I think is truly missing.

--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Nationalism is an infantile sickness.
\__/ Albert Einstein
Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
A new, virtual planet, every day.

Martin v. Loewis

unread,
Mar 30, 2002, 5:24:57 PM3/30/02
to
Ype Kingma <yki...@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

Carel Fellinger

unread,
Mar 30, 2002, 5:40:05 PM3/30/02
to
Terry Reedy <tej...@yahoo.com> wrote:

...


> Proposed amendment: call the new type 'truth' instead of 'bool' and
> change the title of the PEP to "Formalizing a Python truth type".

...lots of arguments snipped

A *very* good idea.


--
groetjes, carel

Tim Peters

unread,
Mar 30, 2002, 5:25:26 PM3/30/02
to
[Robin Becker]
> This pretty much seems unwanted to me. Done purely for political
> correctness. Whenever new keywords are discussed the Gods are against
> them. Now we have to accept new constants true, false + a new type.

True, False and bool aren't proposed to be keywords; they're just new
builtins. If you currently have code doing

try:
True
except NameError:
breathe()

I suppose you'll stop breathing.

but-if-you-have-code-like-that-maybe-it's-for-the-best-ly y'rs - tim


Tim Peters

unread,
Mar 30, 2002, 5:29:29 PM3/30/02
to
[Guido]
>> There's also the issue (which I've seen puzzling even experienced
>> Pythonistas who had been away from the language for a while) that if
>> you see:
>>
>> >>> cmp(a, b)
>> 1
>> >>> cmp(a, a)
>> 0
>> >>>
>>
>> you might be tempted to believe that cmp() also returned a truth
>> value. If ints are not (normally) used for Booleans results, this
>> would stand out much more clearly as something completely
>> different.

[Paul Rubin]
> If cmp returns a boolean, it can no longer distinguish the 3 cases
> a < b, a == b, or a > b. That is seriously broken.

He didn't suggest changing cmp. He's saying that if functions that return
bools printed True/False instead of 1/0, people would be much less likely to
fall into the trap of believing cmp() returns a bool (cmp() would continue
to display not True/False, but little integers).


Tim Peters

unread,
Mar 30, 2002, 5:44:12 PM3/30/02
to
[Guido, on why operator.truth() should change to return True/False]

> Tim must be missing something. The obvious way to turn a bool b into
> an int is int(b).

It's also an incorrect way for me, because I meant "true/false expression"
in the way Python has always meant it, e.g. operator.truth([]) == 0, but
int([]) raises an exception. The alternative int(bool(b)) is not obvious
(else you would have thought of it first <wink>), and becomes needed only if
operator.truth() is changed.

> Having to import the obscure 'operator' module for this purpose is
> backwards.

Under the PEP it's extremely easy to get a bool result (bool(b)), so I favor
presuming that anyone bothering to use operator.truth() will do so because
bool() doesn't do what they want; and if they're using truth() in 2.2, are
doing so because they specifically want a 0/1 result.

> (IMO there's almost *never* a reason to import that module anyway.)

That's not a reason to change what it does -- people who do import it
generally know exactly what they're doing, or have no idea <wink>.


Tim Peters

unread,
Mar 30, 2002, 5:52:23 PM3/30/02
to
>> 1) Should this PEP be accepted at all.

[Pearu Peterson]


> It seems that this is already decided as Guido is the author and also
> the only one who accepts PEPs.

Guido has rejected his own PEPs before. It depends on the quality of
arguments raised, both pro and con.

> ...


> In future (Python 2.>=3, >3), are these constructs valid or must they
> be replaced with
>
> while bool(x):
> ...
>
> ? :(

Under the PEP "while x:" continues to work fine.

> Ka-Ping Yee has raised related conserns in
>
> http://mail.python.org/pipermail/python-dev/2002-March/020893.html
>
> that never got a proper answer from Guido nor others.

There are 8 replies to his msg. I don't know what you mean by "proper".
Under the PEP, none of the stuff he was worried about breaks, and that was
explained. I thought Greg Ewing's reply was more than enough:

http://mail.python.org/pipermail/python-dev/2002-March/020921.html


Carel Fellinger

unread,
Mar 30, 2002, 6:12:03 PM3/30/02
to
Guido van Rossum <gu...@python.org> wrote:
...

> I'm particularly interested in hearing your opinion about the
> following three issues:

As you seem more interested in votes this time around then in arguments:)
I'll try to restrict my self to yes and no anwsers.

> 1) Should this PEP be accepted at all.

yes (I always missed it)

> 2) Should str(True) return "True" or "1": "1" might reduce
> backwards compatibility problems, but looks strange to me.
> (repr(True) would always return "True".)

str(True) == "True" (more readable at the interpreter prompt)

> 3) Should the constants be called 'True' and 'False'

definitely 'True' and 'False'

> Minor additional issues:

> 4) Should we strive to eliminate non-Boolean operations on bools
> in the future, through suitable warnings, so that e.g. True+1

no.

The first time I came across "days + isleap(year)" I found it higly
puzzling (I was raised with strict typing), but now that I'm used to
it I wouldn't want to loose it.


> 5) Should operator.truth(x) return an int or a bool. Tim Peters

assuming its result can be used in integer expressions, it should
return a canonical truth value, so bool (preferably called 'truth')


--
groetjes, carel

John Roth

unread,
Mar 30, 2002, 6:24:08 PM3/30/02
to

"Martin v. Loewis" <mar...@v.loewis.de> wrote in message
news:m3y9ga7...@mira.informatik.hu-berlin.de...

I make it optimistically 180 functions. Given the reasonably
high quality of the standard library, "return None" almost
certainly means that the function does not have a return value,
not that the return value should be treated as False. Good
practice shouldn't be to return None if you meant False - the
convention is 1 or 0.

John Roth

>


John Roth

unread,
Mar 30, 2002, 6:30:52 PM3/30/02
to

"Carel Fellinger" <cfel...@iae.nl> wrote in message
news:a85es5$a95$1...@animus.fel.iae.nl...

Agreed.

John Roth


Guido van Rossum

unread,
Mar 30, 2002, 6:36:07 PM3/30/02
to
> [Guido, on why operator.truth() should change to return True/False]
> > Tim must be missing something. The obvious way to turn a bool b into
> > an int is int(b).

[[Tim, being difficult]


> It's also an incorrect way for me,

No it's not, note that I said "turn a bool b into an int". Clearly
the assumption there is that b is a bool, not an arbitrary value in
whose truth value we're interested.

> because I meant "true/false expression" in the way Python has always
> meant it, e.g. operator.truth([]) == 0, but int([]) raises an
> exception. The alternative int(bool(b)) is not obvious (else you
> would have thought of it first <wink>), and becomes needed only if
> operator.truth() is changed.

IMO, bool(x) is the right way to "normalize" any value into a truth
value. The way I think of operator.truth(x) is as something returning
a normalized truth value. Since we're changing all places that return
standard truth values from returning 0/1 to returning False/True, I
don't see why operator.truth() should not follow suit. If we think
that we can change comparisons, isinstance(), s.islower() and so on to
return a bool without breaking much, I see no reason why we can't
change operator.truth().

> > Having to import the obscure 'operator' module for this purpose is
> > backwards.
>
> Under the PEP it's extremely easy to get a bool result (bool(b)), so
> I favor presuming that anyone bothering to use operator.truth() will
> do so because bool() doesn't do what they want;

No, they do so because they wrote the code before bool existed.

> and if they're using truth() in 2.2, are doing so because they
> specifically want a 0/1 result.

And since False==0 and True==1, that's what they're getting.

I'm going to make this a BDFL pronouncement; I understand your
argument but I don't agree with it.

Paul Sidorsky

unread,
Mar 30, 2002, 6:40:10 PM3/30/02
to
Ype Kingma wrote:

> A bool is a bool and an int is an int.
> The only relation between them is that they have to be implemented using
> bits of a computer.
> Python is sufficiently high level not to care about the bits.

Wow, wait long enough and somebody will say exactly what you're
thinking. I pretty much agree 100% with everything Ype wrote.

I am totally in favour of a boolean type. Writing "value = 1" instead
of "value = True" has seemed wrong ever since I started with Python. I
feel it important to add a definitive "yea" on this since there has been
quite a bit of resistance to this PEP so far. However, while I think
it'd be great to have a bool type, I think it would be even better to
see it done "right" from the start.

From what I have read on python-dev it looks as if the desire to mix
ints and bools stems mainly from wanting to preserve backward
compatibility. However, it seems to me that allowing ints and bools to
be interchanged somewhat is going to create a lot of situations where
the two of them get mixed in the same module. Old code will use ints,
while newer changes and additions will use True/False as programmers get
used to using them in new projects. Maintaining these kind of modules
is going to be hell until somebody finally decides to correct everything
to the new style. If this is going to be done anyhow, why not at least
force people it to be done right the first time? People may gripe at
first at having to upgrade code, but in the end they'll be better off
than if they hadn't.

Hmmm, this seem like a good time to share my own horror story about what
can happen when you mix ints and bools. This was in C (not C99 though)
so there was no bool type - just like Python is now.

I had a program that was storing a bunch of values, and in one part I
needed to know if just one particular value was there or not, so of
course I had assigned that value 0 and exploited the fact that I could
use "!value" to test for it quickly. I needed this result a few times
so I assigned it to a variable.

Some time later I was adding features and found that in one case I
needed to know exactly what the value was, so I modified that part of
the program to use the same variable to store the actual value instead
of a truth value. This meant that what was 0 (false) would now be a
positive integer, and vice-versa. This must have slipped my mind
because I got the assignment the wrong way around.

This should have broken the program immediately, except that when I was
converting the the rest of this part of the program I had missed a
negation of the old value. The result was essentially that of applying
"value = !(!value)". The program still worked WRT the old truth checks,
but was completely unable to determine the actual value where I wanted
it to because the value could only be 0 or 1. Needless to say, it took
a very long time to track this problem down.

This would never have happened if bools and ints were separate types.
The extra negation would have meant I was trying to assign a bool to an
int and caused an error immediately. Furthermore, I almost certainly
would never have _tried_ such a twisted approach to begin with. I did
it the way I did because in C I _could_ do it that way.

Mixing ints and bools doesn't offer enough protection in my mind. A
boolean type that can be partially interchanged with an int might have
prevented my nightmare above from happening, but not necessarily. As I
said, though, a separate boolean type would have prevented this kind of
error from even compiling. Having that kind of protection built into
the language is very appealing, at least to me.

I admit that in this case above the problem was ultimately the result of
my own stupidity. However, if programmers weren't stupid the odd time
we wouldn't even need languages like Python because we'd all be able to
program in perfect C. Heck, we might not even need C because we could
program in perfect assembly. Given that we're not pefect, the job of a
high-level language should be to provide more protection for programmers
not from lower-level languages, but from themselves.

--
======================================================================
Paul Sidorsky Calgary, Canada
pau...@shaw.ca http://members.shaw.ca/paulsid/

phil hunt

unread,
Mar 30, 2002, 5:46:00 PM3/30/02
to
On Sat, 30 Mar 2002 08:38:00 -0500, Guido van Rossum <gu...@python.org> wrote:
>
>Tim must be missing something. The obvious way to turn a bool b into
>an int is int(b).

Will this work on old versions of python? I've just checked that it
works on 2.0, but what about 1.5.1 or 1.6?

I'd guess (b*1) would work on everything, however.


--
<"><"><"> Philip Hunt <ph...@comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically
advantageous for him to believe."
-- Alison Brooks, referring to Michael
Portillo, on soc.history.what-if

phil hunt

unread,
Mar 30, 2002, 3:05:35 PM3/30/02
to
On 30 Mar 2002 01:36:43 -0800, Paul Rubin <phr-n...@nightsong.com> wrote:
>Guido van Rossum <gu...@python.org> writes:
>> Dear reviewers:

>>
>> I'm particularly interested in hearing your opinion about the
>> following three issues:
>>
>> 1) Should this PEP be accepted at all.
>
>I don't see much need for it.

Nor do I. Python works OK as it is, asnd this proposal adds nothing
new semantically (because bool must act the similarly to int, for
compatibility). The only advantage I see is that code is slightly
more self-documenting, e.g.:

return True

instead of:

return 1

> There's no need to turn Python into Java.

Indeed. Python, as it stands, is a much clearer and nicer-to-code-in
langauge than Java, C, C++, etc.

phil hunt

unread,
Mar 30, 2002, 2:53:53 PM3/30/02
to
On Sat, 30 Mar 2002 00:39:10 -0500, Guido van Rossum <gu...@python.org> wrote:
>Abstract
>
> This PEP proposes the introduction of a new built-in type, bool,
> with two constants, False and True.

My first reaction to this was "shit, this will break every
non-trivial program". However the details of the proposal are such
that it won't, it goes out of its way to implement backwards
compatibility.

>Rationale
>
> Most languages eventually grow a Boolean type; even C99 (the new
> and improved C standard, not yet widely adopted) has one.

That's hardly a valid reason.

Should we scrap syntactic indentation and use BEGIN and END keywords
instead? Most languages do some varient of that.

> Here are some arguments derived from teaching Python. When
> showing people comparison operators etc. in the interactive shell,
> I think this is a bit ugly:
>
> >>> a = 13
> >>> b = 12
> >>> a > b
> 1
> >>>
>
> If this was:
>
> >>> a > b
> True
> >>>

That *is* a valid reason. However, it must be decided whether
Python's primary goal is to be easy to learn or easy to use.

This proposal makes it easier to learn in some respects, but adds
difficulty as well, as the user must learn a new data type, albeit
a rather simple one.

> it would require one millisecond less thinking each time a 0 or 1
> was printed.

This would be true the first 2 or 3 times someone sees a 0 or 1 in
response to a boolean query.

> There's also the issue (which I've seen puzzling even experienced
> Pythonistas who had been away from the language for a while) that if
> you see:
>
> >>> cmp(a, b)
> 1
> >>> cmp(a, a)
> 0
> >>>
>
> you might be tempted to believe that cmp() also returned a truth
> value. If ints are not (normally) used for Booleans results, this
> would stand out much more clearly as something completely
> different.

That's true, but it's not a biggy.

> Other languages (C99, C++, Java) name the constants "false" and
> "true", in all lowercase. In Python, I prefer to stick with the
> example set by the existing built-in constants, which all use
> CapitalizedWords: None, Ellipsis, NotImplemented (as well as all
> built-in exceptions). Python's built-in module uses all lowercase
> for functions and types only. But I'm willing to consider the
> lowercase alternatives if enough people think it looks better.

I prefer True, False.

phil hunt

unread,
Mar 30, 2002, 6:38:19 PM3/30/02
to
On Sat, 30 Mar 2002 20:05:35 +0000, phil hunt <ph...@comuno.freeserve.co.uk> wrote:
>On 30 Mar 2002 01:36:43 -0800, Paul Rubin <phr-n...@nightsong.com> wrote:
>>Guido van Rossum <gu...@python.org> writes:
>>> Dear reviewers:
>>>
>>> I'm particularly interested in hearing your opinion about the
>>> following three issues:
>>>
>>> 1) Should this PEP be accepted at all.
>>
>>I don't see much need for it.
>
>Nor do I. Python works OK as it is, asnd this proposal adds nothing
>new semantically (because bool must act the similarly to int, for
>compatibility). The only advantage I see is that code is slightly
>more self-documenting, e.g.:
>
> return True
>
>instead of:
>
> return 1

I've gone through some of my herbivore code, looking to see where
I've used 0 or 1 as a boolean. Example 1:

debug = 0 # debugging this module?

Frankly, if that is unclear to anyone, they are not cut out to be a
programmer. Bear in mind that most non-programmers are aware of the
0/1 paradigm for boolean values: it appears on much electrical
equipment.

Example 2:

CONFIG_DEFAULT_VALUES = {
'dest': "file:mess_out_%(ix)s",
'log': 1,
'logItems': ["i", "ip", "o", "op", "cmd", "comment"],
'logMessItems': ["From", "To", "Cc", "Bcc", "Subject",
"Message-Id", "X-Herbivore"],
}


Here, the 1 value for 'log' means turn on logging, so could
naturally be replaced by a boolean. These are default values for the
config file; in the file they will look like:

log = 1

The file is executable Python code, and so could naturally be
changed to:

log = True

if it is unclear. But (1) it isn't unclear, since the default config
file contains a comment before each config variable, saying what it
means -- and anyway there will be a GUI config tool for Herbivore,
and (2) Herbivore, by design is required to be easily installed;
specifically, the user shouldn't have to upgrade to a newer version
of Python, so I wouldn't be able to use booleans for a long time
after they'd been added.

So there would be no benefit for me at least in adding this feature.

Now we turn to the other side of the coin: would this proposal cause
problems. Contrary to my initial post, I see one place where it
might well do. Consider a program that communicates with instances
of the same program on other machines by way of Python data
expressed as repr() strings. Each instance of this program will work
on its own. Each instance will continue to work if Python on that
machine is upgraded to a post-boolean version. But the upgraded and
unupgraded will no longer be able to talk to each other if there are
any boolean values being passed around. This could well be a
hard-to-track-down error, since both versions will continue to work
perfectly well on their own.

So because there seem to be few advantages, potential disadvantages,
and because the proposal adds unnecessary complexity to the Python
language in return for some superfluous syntactic sugar, I dislike
this proposal.