Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

PEP 285: Adding a bool type

113 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.

Tim Peters

unread,
Mar 30, 2002, 8:17:40 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,

[Guido, being more difficult]


> 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.

In context, your original int(b) suggestion was in response to my:

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.

where, as I explained in the later msg to which you're replying now, just in
case it wasn't clear the first time around:

I meant "true/false expression" in the way Python has always
meant it, e.g. operator.truth([]) == 0, but int([]) raises an
exception.

So you may say that "clearly the assumption there is that b is a bool", but
it's not at all clear that was a *reasonable* assumption in the context in
which you first said it: I've been thru the business twice now of
explaining why int() isn't suitable for the cases I was talking about.
int(bool) is not a case I was talking about.

> IMO, bool(x) is the right way to "normalize" any value into a truth
> value.

Sure, it will be. But if you need to, e.g., "preserve 0/1-based true/false
output", bool(x) may not work (depending on whether you yield to making
str(bool) and/or repr(bool) return "0"/"1").

> The way I think of operator.truth(x) is as something returning
> a normalized truth value.

Well, that's where we differ: bool(x) will be *the* "right way to
'normalize' any value into a truth value". As at the start, I don't need
two "right ways" to do exactly the same thing.

> ...
> [more of the same]
> ...


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

Whew! I'm glad that's finally over,

you-should-do-that-more-often<wink>-ly y'rs - tim


Peter Hansen

unread,
Mar 31, 2002, 1:44:33 AM3/31/02
to
"Martin v. Loewis" wrote:
>
> 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.

But your point in the message I was replying to was that there
are 300 functions which have code that says "return 0" or "return 1"
or "return None" and the change will help users of those functions.
Didn't that imply those users are not looking at the documentation,
but are trying to read the source to figure out how the code works?
If the documentation must be changed, why not just make it clear
in the documentation what it means when a method returns 1 or 0 or None?

> > 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.

I don't even need to dig up examples since I so often put this
code at the start of my modules:

True, False = 1, 0

Or, now that I think of it, will that continue to work as these
will just be built-ins now hidden by my local definitions? If so,
my bad for mentioning code breakage.

-Peter

Peter Hansen

unread,
Mar 31, 2002, 1:47:55 AM3/31/02
to
Ken Peek wrote:
>
> I don't see that adding a "bool" (or better: "boolean", since I HATE
> abbreviated words) would be such a big issue.

Agreed on that point. "bool" would be less clear to newcomers and
possibly those with limited English. (Vague assumption there that
those people might have heard of Boolean algebra but might not
link it to the shorter form as quickly.)

Besides, if we're doing this to look like the other languages,
don't they use "boolean" more often? (I realize that's not
really the reason for doing this.)

Erik Max Francis

unread,
Mar 31, 2002, 1:48:40 AM3/31/02
to
Peter Hansen wrote:

> Agreed on that point. "bool" would be less clear to newcomers and
> possibly those with limited English. (Vague assumption there that
> those people might have heard of Boolean algebra but might not
> link it to the shorter form as quickly.)
>
> Besides, if we're doing this to look like the other languages,
> don't they use "boolean" more often? (I realize that's not
> really the reason for doing this.)

C++ uses bool, C99 uses _Bool, Java uses boolean ...

I can see both ways here. I'm more used to seeing bool, but wouldn't
object to boolean.

Ype Kingma

unread,
Mar 31, 2002, 6:16:47 AM3/31/02
to
Martin,

you wrote:
>
> 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.

I was referring to the bits in flag registers which allow all kinds of
beatiful assembly language optimizations.
I think we mostly agree here.
I'd like to know whether this PEP merging all numeric types would also merge
the bool type into its evt. hierarchy.

>
> Notice that the relationship of bool and int has two aspects: one is
> whether you can combine them in numeric operations,
> e.g. 28+isleap(year). There is absolutely no way to remove this
> property from the language - too much code would break if that would
> raise an exception.

There are two ways to do this:
- marking such code with: from __past__ import nonbool
(as I remarked earlier this is rather radical)
- defining __add__ and __radd__ in the int and float classes to also accept a bool
sounds quite pythonic and acceptable to me.

> 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.

Agreed.



> > 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.

An Square that is a Rectangle has inherits two degrees of freedom,
(height and width) which have to constrained to a single one in the
implementation.
Implementing such constraints is a bit awkward and can be avoided
by implementing Square as a OneDegreeOfFreedomThing and a Rectangle
as a TwoDegreeOfFreedomThing.
These ...DegreeOfFreedomThing's are intended as abstract to be consistent
with the design rule to not inherit from a class that has instantions.

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

> > 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.

Ok. But just like the bool + int things above
this could be implemented by implementing __cmp__ and
__rcmp__ for the bool class and/or the numeric class.

>
> > 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

You're right.

> > 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.

I guess it's time for me to reread the fine manual and to read the
bool thread on python-dev about whether the __add__ and __cmp__.

Thanks for the corrections,
Regards,

Ype

Martin v. Loewis

unread,
Mar 31, 2002, 5:16:54 AM3/31/02
to
"John Roth" <john...@ameritech.net> writes:

> 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.

Notice a subtlety, though: In a high-quality library, if the
*function* has no return value, the return statement should be just
"return". I'd always assume that the function would normally return an
object, and that "return None" indicates that no object is available
in this case. A quick glance shows that this indeed seems to be the
case in the majority of the cases.

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 5:25:13 AM3/31/02
to
ph...@comuno.freeserve.co.uk (phil hunt) writes:

> 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.

The way Guido meant this is really "turn a *bool* into an int". There
are no bools in 2.0, so I wonder what you've checked. If you want to
change an arbitrary object into 0/1, int() certainly won't work:

>>> int([])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object can't be converted to int

To turn an arbitrary object into a bool, you could have used
operator.truth so far, since Python 1.4. To turn that into 0/1 pair,
you could write int(operator.truth(obj)). This will also work back to
Python 1.4, since truth already returns 0/1; passing that to int() was
always allowed.

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 5:28:59 AM3/31/02
to
ph...@comuno.freeserve.co.uk (phil hunt) writes:

> 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.

I think this has been decided; many educators are interested in using
Python in school (at all levels of education).

> 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.

This should not be a problem. The notion of boolean values must be
understood, anyway, and wordings like "[],{},None, ..., 'count as
true'" are more easy to understand (IMO) if there really is the thing
they count as.

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 5:39:09 AM3/31/02
to
Tim Peters <tim...@comcast.net> writes:

> In context, your original int(b) suggestion was in response to my:
>
> 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.
>

[...]


> So you may say that "clearly the assumption there is that b is a bool", but
> it's not at all clear that was a *reasonable* assumption in the context in
> which you first said it: I've been thru the business twice now of
> explaining why int() isn't suitable for the cases I was talking about.
> int(bool) is not a case I was talking about.

Your list of alternatives that reek in comparison was
puzzling. int(bool(obj)) doesn't reek to me: it is obvious what it
does, it does that efficiently, and it requires less typing than
operator.truth(obj).

In that context, I took Guido's response as "why are you bringing up
this silly list of alternatives, yet ignoring the obvious alternative:
int is the right way to get an int from a bool": int(bool(obj)).

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 5:47:11 AM3/31/02
to
Peter Hansen <pe...@engcorp.com> writes:

> But your point in the message I was replying to was that there
> are 300 functions which have code that says "return 0" or "return 1"
> or "return None" and the change will help users of those functions.
> Didn't that imply those users are not looking at the documentation,
> but are trying to read the source to figure out how the code works?

No. It implied that users read the source of the code; whether or not
they look at the documentation was not implied.

> If the documentation must be changed, why not just make it clear in
> the documentation what it means when a method returns 1 or 0 or
> None?

The documentation already says that. However "If the section in fact
existed, return 1. Otherwise return 0." leads to the question "why
aren't you returning a boolean value?", to which the answer is
"because they are not supported in the language".

> True, False = 1, 0
>
> Or, now that I think of it, will that continue to work as these
> will just be built-ins now hidden by my local definitions?

Indeed, yes.

> If so, my bad for mentioning code breakage.

There still might be code breakage, but it will be much less frequent
than you feared.

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 5:52:52 AM3/31/02
to
Paul Sidorsky <pau...@shaw.ca> writes:

> 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?

There are guidelines for language evolution (PEP 5). Those mandate
that incompatible changes get a warning period, before outright
breaking code.

If booleans are introduced in the way the PEP suggests, but would
*not* interact with numbers in the way proposed, PEP 5 would be
clearly violated. Also, there are strong opinions on both sides: some
people actually like booleans to interact with numbers in the way
Python does it.

So phasing out those interactions would be another PEP, one that
cannot complete before Python 2.7 or so.

Regards,
Martin

Martin v. Loewis

unread,
Mar 31, 2002, 6:14:18 AM3/31/02
to
Ype Kingma <yki...@accessforall.nl> writes:

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

See for yourself:

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Regards,
Martin

Hernan M. Foffani

unread,
Mar 31, 2002, 6:44:18 AM3/31/02
to
"phil hunt" escribió en el mensaje
> ....

>
> 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.
>
> [an example of a "log" flag follows]

Actually "debug" and "log" flags use to be confusing if the original
author didn't document the use case. Those can be either boolean
flags or integers level indicators.

For instance, in your example the "debug = 0" may have both meanings.
It's the "?" in the commentary that raises the bets towards boolean.

It's a very common practice to start with a boolean meaning and
"promote" it afterwards to a level parameter. I'm not judging that
practice here because I don't think it is a problem, it just works.

Regards,
-Hernan


John Roth

unread,
Mar 31, 2002, 7:41:05 AM3/31/02
to

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

Good point. In that case, the result still isn't logically a boolean -
it's at least "True", "False" or "Huh?"

John Roth
>
> Regards,
> Martin
>


Ralph Corderoy

unread,
Mar 31, 2002, 8:07:11 AM3/31/02
to
Hi Guido,

> IMO, bool(x) is the right way to "normalize" any value into a truth
> value.

What do you think of `truth(x)' for all the good reasons listed
elsewhere in the thread? You used truth yourself instead of Boolean
above.


Ralph.

Ralph Corderoy

unread,
Mar 31, 2002, 7:41:59 AM3/31/02
to
Hi Terry,

> 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?

That's an excellent point, as are the others you make. My Mum would
understand true but not bool or Boolean.


Ralph.

Peter Hansen

unread,
Mar 31, 2002, 9:07:57 AM3/31/02
to
"Martin v. Loewis" wrote:
>
> Peter Hansen <pe...@engcorp.com> writes:
> > If the documentation must be changed, why not just make it clear in
> > the documentation what it means when a method returns 1 or 0 or
> > None?
>
> The documentation already says that. However "If the section in fact
> existed, return 1. Otherwise return 0." leads to the question "why
> aren't you returning a boolean value?", to which the answer is
> "because they are not supported in the language".

Heh... I thought the answer was "we _are_ returning a boolean
value, but they're spelled 1 and 0 in Python".

-Peter

Roy Smith

unread,
Mar 31, 2002, 9:26:28 AM3/31/02
to
mar...@v.loewis.de (Martin v. Loewis) wrote:
> Your list of alternatives that reek in comparison was
> puzzling. int(bool(obj)) doesn't reek to me: it is obvious what it
> does, it does that efficiently, and it requires less typing than
> operator.truth(obj).

Seems to me, obj.bool().int() would be the obvious way.

Aahz

unread,
Mar 31, 2002, 9:33:53 AM3/31/02
to
In article <slrnaac5uf...@comuno.freeserve.co.uk>,

phil hunt <ph...@comuno.freeserve.co.uk> wrote:
>
>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.

It must? Much of why I love Python so much is because it's *both*. By
using lots of simple, orthogonal constructs, Python manages that unusual
feat. That's the main reason I was (and am) unhappy with the "print >>"
proposal, but on the whole, I can't argue with Guido's ability to find
solutions that promote the goals of both "easy learn" and "easy use".

I happen to think that adding a truth type (I like the suggestion of
"truth" over "bool") does that.
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?

Paul Prescod

unread,
Mar 31, 2002, 11:01:29 AM3/31/02
to
Arthur Siegel wrote:
>
>...
>
> If I am concerned about the readability of my code
> for other non-experts (and I usually am), I might
> do a:
>
> True = 1
> False = 0
>
> at a modules head and go from there.
>
> I am not understanding what beyond that the
> Boolean type accomplishes.
>
> It would perhaps not detract from the debate
> if the upside could be explained in terms that
> spoke to the practicalities of writing workable
> and readable code in Python, rather than in
> terms of language design theory and
> implementation internals.

One way to sum it up is "if that's a good convention for readability
then why not make it a built-in concept in the language so that we do
not all invent our own spellings for it?" Having bool be separate from
integer is useful for introspection. For instance if you pass a "1" to
Jython, COM or SOAP, it is hard for Jython or the Python COM bindings or
ZSI to know whether you meant to pass an integer or a boolean. In the
worse case this can mean you call the wrong overloaded method. Even in
pure python it may occasionally (very occasionally) be useful to write
code of the form: "if the first argument is a boolean then do X, else if
it is an integer do Y." Finally, booleans can have different displays so
that:

print "isWindowMaximized:", isWindowMaximized

will print "True", rather than "1". The former is a little clearer.

Paul Prescod

Erno Kuusela

unread,
Mar 31, 2002, 11:59:04 AM3/31/02
to
In article <mailman.101746697...@python.org>, Guido van
Rossum <gu...@python.org> writes:

[...]


| 1) Should this PEP be accepted at all.

no.

[...]
| Rationale

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

i don't agree wit this argument.

| 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.

clearly you should not use constants, but use 0 and 1. i've
personally not seen any code that uses constants like that.
i'm sure you could find many other questionable practices used
by many modules. i don't agree with this argument either.

| 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 true, but not very significant.

| 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

i say add a bool() builtin that returns 0 or 1, if it makes you
feel better.


| Here are some arguments derived from teaching Python.

[...]

in my experience, even absolute beginners naturally understand
that 0 means false and 1 means true.

the fact that other objects are interpreted as true or false can be
slightly confusing, but in my opinion this is not enough of a problem
to warrant the addition to language basics.

keep python clean! ;)

-- erno


Stefan Schwarzer

unread,
Mar 31, 2002, 1:14:07 PM3/31/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.
> [...]
> Review

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

I'm -1 on this PEP.

To summarize: The problem I have with this proposal is that it does a
half-hearted job (and can only do so because of backward compatibility
issues).

I think it's a bad deal to get

> >>> a > b
> True
> >>>

but on the other hand have to keep in mind subtle interactions between
bools and ints. For example, I consider it very unintutive that
"True == 1" should by true but "True == 2" should be false. I
understand well that this is for backward compatibility, i. e. not
breaking code that uses "boolean" results to calculate something
together with numbers.

There are, as pointed out, too much cases where bool/int interactions
lead to surprises because the behaviour of the bool type does not live
up to its abstract concept that it should have. This is confusing; in
effect one would have to think _more_ whether the code does what is
should. If one deals with ints _explicitly_, calculation outcomes are
much easier to see.

Regarding special uses such as RPC and databases it would suffice to
add a "boolean" module to the standard library. This would offer a
standard way to handle a boolean type for these special purposes,
wouldn't it?

So, in my opinion the disadvantages strongly outweigh the benefits of
the PEP.

Additionally, the PEP brings some more design ambiguity which I
dislike. Should my function/method return 0, None, - or False, in a
specific case? Having to make this decision reminds me at the choice
of defining an attribute as "protected" vs. "private", or using
"virtual" or not, in C++. Sometimes, I would like to postpone
decisions until later. This thinking is in line with the earlier post
in which someone said that "it's not unusual for an integer meaning
true or false to become a 'level' variable".

_If_ the PEP is accepted (which I do not hope), I would prefer ...

> 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 be "1" (because of the arguments of Marc-Andre
Lemburg; some applications actually might make use of this
representation).

> 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"

> 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.

Not to me, despite its convenience. As the name suggests, isleap should
return a bool. But then, it shouldn't be added to an int. A solution
to resolve this would be to change the name of isleap.

> 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.

operator.truth(x) should return a bool.

Stefan

Tim Peters

unread,
Mar 31, 2002, 12:56:52 PM3/31/02
to
[Ralph Corderoy, to Guido]

> What do you think of `truth(x)' for all the good reasons listed
> elsewhere in the thread? You used truth yourself instead of Boolean
> above.

Actually, he didn't. True story: we (PythonLabs) recently chatted with Jim
Fulton (Zope Corp's CTO, Guido's boss, and very long-time Python user) about
truth values in Python. Jim declaimed that he always wished Python had a
function to convert Python's notion of true/false into an integer 1/0, and
suggested that "truth()" would be a good name for it. He didn't realize
that operator.truth() was already there, and does exactly what he asked for.
I had a nagging suspicion, so dug into the CVS history then, and discovered
that operator.truth() was added for Python 1.4 -- and the code was
contributed by (tada!) Jim Fulton. He did the work in the last millennium,
and simply forgot all about it then.

So if anyone on c.l.py ever feels silly about asking for a feature that's
already there, don't -- the people who *implement* features sometimes do the
same thing.

e.g.-i-still-wish-math.log(2L**100000)-didn't-blow-up-ly y'rs - tim


Ype Kingma

unread,
Mar 31, 2002, 2:27:09 PM3/31/02
to
Martin,

you wrote:
>
> Ype Kingma <yki...@accessforall.nl> writes:
>
> > I'd like to know whether this PEP merging all numeric types would also merge
> > the bool type into its evt. hierarchy.
>
> See for yourself:
>
> http://python.sourceforge.net/peps/pep-0228.html

Quote from PEP 228:

Suggested Interface For Python's Numerical Model

While coercion rules will remain for add-on types and classes, the
built in type system will have exactly one Python type -- a
number. There are several things which can be considered "number
methods":

1. isnatural()
2. isintegral()
3. isrational()
4. isreal()
5. iscomplex()

End of quote.

While I wouldn't mind for bool to implement this interface,
I would object to True.isnatural() to return True, and also to
True.isintegral() to return True.

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

This is the one about numerical kind objects allowing
for predetermined numerical precision. Since the minimal
precision of a numerical kind from this PEP is one decimal digit
it would probably never allow for a number with only two
usable values.

> > > Notice that the relationship of bool and int has two aspects: one is
> > > whether you can combine them in numeric operations,
> > > e.g. 28+isleap(year). There is absolutely no way to remove this
> > > property from the language - too much code would break if that would
> > > raise an exception.
> >
> > There are two ways to do this:
> > - marking such code with: from __past__ import nonbool
> > (as I remarked earlier this is rather radical)
>
> I hate the __future__ statement, so I definitely don't want to get a
> __past__ statement. Following PEP 5, you will need a phased
> introduction strategy for booleans if you don't want to interact them
> with numbers. Don't expect to get this in this decade, though.
>

For backward compatibility I don't mind interacting booleans with numbers.
The coercion framework is there, it only needs to be extended with the bool class
(sigh.)

<snip>

>
> > - defining __add__ and __radd__ in the int and float classes to also
> > accept a bool sounds quite pythonic and acceptable to me.
>
> That would work, but only somewhat. There are other places where
> booleans need to act as integers, e.g. indexing: array[b] ought to
> work, for backwards compatibility, even if b suddently turns into a
> boolean. That means that every __getitem__ implementation needs to
> become aware of booleans - so likely a lot of code would break.
>

Only user code __getitem__ implementations that already use booleans for
indexing would break.
When these are the only ones that would break I think deprecation
would be quite acceptable to handle them, especially because the
fix only consists of inserting an int() call.
Indexing a dict with both int and bool keys might involve some confusion
when True is not 1 anymore. This case should be rare, however.
Slices should be no problem: they only need int values, so the
evt. int() call can be provided when a slice is created.

> > An Square that is a Rectangle has inherits two degrees of freedom,
> > (height and width) which have to constrained to a single one in the
> > implementation.
> > Implementing such constraints is a bit awkward
>
> That depends on the rectangle interface. If rectangles are immutable,
> implementing the constraint is straight-forward, not awkward.
>
> class Rectangle:
> def __init__(self, x, y, w, h):
> self.x,self.y,self.w,self.h = x,y,w,h
>
> def area(self):
> return self.w*self.h
>
> class Square(Rectangle):
> def __init__(self, x, y, w):
> Rectangle.__init__(self, x, y, w, w)
>

Even in the non mutable case the redundancy of self.w and self.h
has to be accepted here.

> > When bool is-a int, one would have to (awkwardly) implement at least
> > one such constraint, namely that bool values can only be 1 or 0.
>
> Not at all. Bools are immutable, and singletons. If bool would not
> inherit from int, nothing in the implementation would change; see the
> PEP.

I meant that the implementation would need to select the appropriate
singleton instead of computing the integer as inherited in the is-a int case.

All this leaves me in favour of PEP 285 with some remarks:
- use of current booleans in user code __getitem__ implementations should
be deprecated with indication of the int() fix. After this a bool should not be
an int anymore.
- Once a bool is no more an int, the implementation of backward compatible 0/1 numerical
behaviour could be done in __add__, __radd__, __cmp__, __rcmp__ and similar
methods of the bool and/or numerical classes and in __getitem__ methods of indexable
classes.

Regards,
Ype

P.S. Thanks for putting up with the typo's. Waking up takes more time some days.

--
email at xs4all.nl

Aahz

unread,
Mar 31, 2002, 1:47:13 PM3/31/02
to
In article <mailman.101759752...@python.org>,

Tim Peters <tim...@comcast.net> wrote:
>[Ralph Corderoy, to Guido]
>>
>> What do you think of `truth(x)' for all the good reasons listed
>> elsewhere in the thread? You used truth yourself instead of Boolean
>> above.
>
>Actually, he didn't. True story: we (PythonLabs) recently chatted with
>Jim Fulton (Zope Corp's CTO, Guido's boss, and very long-time Python
>user) about truth values in Python. Jim declaimed that he always
>wished Python had a function to convert Python's notion of true/false
>into an integer 1/0, and suggested that "truth()" would be a good name
>for it. He didn't realize that operator.truth() was already there, and
>does exactly what he asked for. I had a nagging suspicion, so dug into
>the CVS history then, and discovered that operator.truth() was added
>for Python 1.4 -- and the code was contributed by (tada!) Jim Fulton.
>He did the work in the last millennium, and simply forgot all about it
>then.

But what do you think of changing bool() to truth()?

Erik Max Francis

unread,
Mar 31, 2002, 2:04:12 PM3/31/02
to
Ralph Corderoy wrote:

I'm not really sure how beneficial this would be. In the real world,
not everything about a programming language -- even a low-overhead
language like Python -- can be instantly intuited by non-programmers.
After some elementary level they're going to have to start reading.
That bool (or boolean) is a Boolean type is not a hard concept to get
across, and I don't see how calling it "truth" is really all that much
more helpful.

It's far better, in my opinion, to give it a standard name from computer
science (bool or boolean) and let new programmers take the tiny little
steps (in this case) to add a new word to their vocabulary -- a word
that will help them in future explorations of programming and computer
science, no less.

Excessive attempts to make terms more approachable can lead to disaster
in the degenerate case, resulting in just a new form of terminology that
now nobody understands.

Erik Max Francis

unread,
Mar 31, 2002, 2:09:00 PM3/31/02
to
Stefan Schwarzer wrote:

> but on the other hand have to keep in mind subtle interactions between
> bools and ints. For example, I consider it very unintutive that
> "True == 1" should by true but "True == 2" should be false.

Why? Implicit conversions seem un-Pythonic, so why would this be
unfortunate? When you write (True == 2) you're asking, "Is the value
true equal to the integer value 2?" the answer to which is clearly no.
Same thing with something like (2 == "2") -- no conversions are going on
here so the test is false.

> Additionally, the PEP brings some more design ambiguity which I
> dislike. Should my function/method return 0, None, - or False, in a
> specific case?

Seems pretty clear, and it depends on what the function or method is
supposed to be computing. If it's an object or lack-of-object, then
None. If it's a Boolean, then True or False. If it's an integer, then
some integer or 0.

Erik Max Francis

unread,
Mar 31, 2002, 2:09:47 PM3/31/02
to
Ralph Corderoy wrote:

> What do you think of `truth(x)' for all the good reasons listed
> elsewhere in the thread? You used truth yourself instead of Boolean
> above.

But you already have precisely this:

from operator import truth

Erik Max Francis

unread,
Mar 31, 2002, 2:10:40 PM3/31/02
to
Aahz wrote:

> But what do you think of changing bool() to truth()?

In the new type unification scheme, bool seems a much better name than
truth.

Aahz

unread,
Mar 31, 2002, 2:30:19 PM3/31/02
to
In article <3CA75EFB...@alcyone.com>,

Erik Max Francis <m...@alcyone.com> wrote:
>Ralph Corderoy wrote:
>>
>> What do you think of `truth(x)' for all the good reasons listed
>> elsewhere in the thread? You used truth yourself instead of Boolean
>> above.
>
>But you already have precisely this:
>
> from operator import truth

13. There should be one-- and preferably only one --obvious way to do it.

Emile van Sebille

unread,
Mar 31, 2002, 2:51:31 PM3/31/02
to
Erik Max Francis

> Stefan Schwarzer wrote:
> > but on the other hand have to keep in mind subtle interactions
between
> > bools and ints. For example, I consider it very unintutive that
> > "True == 1" should by true but "True == 2" should be false.
>
> Why? Implicit conversions seem un-Pythonic, so why would this be
> unfortunate? When you write (True == 2) you're asking, "Is the value
> true equal to the integer value 2?" the answer to which is clearly no.

If a=b, shouldn't a==a, a==b and b==a all be true?

Someone (Guido?) already mentioned that testing for true is redundant,
but doesn't :
if 2:
imply
if 2 == True:
which in turn then implies that:
True == 2
is true?

Or-would-we-be-restricted-to-while-1:-ly y'rs

--

Emile van Sebille
em...@fenx.com

---------

Tim Peters

unread,
Mar 31, 2002, 2:17:20 PM3/31/02
to
[Aahz]

> But what do you think of changing bool() to truth()?

Whatever Guido tells me to think <wink>. Before then, I think "bool"
usually reads better, as it's less a strain to use as either adjective or
noun. Contrast, e.g.,

isatty returns bool
isatty returns a bool
isatty returns a bool value

with

isatty returns truth
isatty returns a truth
isatty returns a truth value

After reading "isatty returns a truth", I'm left wondering which specific
truth it returns, and whether I'd agree with it <wink>.

Strangely enough, even today:

>>> print os.isatty.__doc__
isatty(fd) -> Boolean
Return true if the file descriptor 'fd' is an open file descriptor
connected to the slave end of a terminal.
>>>

isatty(fd) -> truth

doesn't read poorly, though.


Tim Peters

unread,
Mar 31, 2002, 2:38:41 PM3/31/02
to
[Erik Max Francis]
> ...

> Excessive attempts to make terms more approachable can lead to disaster
> in the degenerate case, resulting in just a new form of terminology that
> now nobody understands.

People should be aware that Guido is acutely sensitive to that: ABC went
out of its way to invent new "friendly" terms for everything, and indeed
that just increased ABC's isolation. Like, instead of "string" it used
"text", instead of "function" it was "how-to", and if you still can't guess
what ABC meant by "train", I don't blame you <wink -- as a hint, a text is
one kind of train -- as a really great hint, the answer is "sequence">.
About ABC's notion of truth:

A predicate-how-to defines the meaning of a new predicate ...
Predicates are used in examinations, which are a special case
of tests. ... Tests do not return a value, but succeed or fail
via the report, succeed and fail commands.

IOW, cutting thru the unique terminology, ABC finessed the "bool or truth?"
question by not having any such datatype, and, e.g., the set of expressions
allowable after an "if" had no intersection with those allowable as what you
think of as the right-hand-side of an assignment statement (which ABC called
putting a value in a location, via the PUT command).


Aahz

unread,
Mar 31, 2002, 3:35:29 PM3/31/02
to
In article <2NJp8.140405$Yv2.43077@rwcrnsc54>,

Emile van Sebille <em...@fenx.com> wrote:
>
>Someone (Guido?) already mentioned that testing for true is redundant,
>but doesn't :
> if 2:
>imply
> if 2 == True:

Nope. That's like saying

if '':

having the same result as

if []:

implies that

'' == []

which is completely untrue.

phil hunt

unread,
Mar 31, 2002, 2:07:38 PM3/31/02
to
On 31 Mar 2002 09:33:53 -0500, Aahz <aa...@pythoncraft.com> wrote:
>In article <slrnaac5uf...@comuno.freeserve.co.uk>,
>phil hunt <ph...@comuno.freeserve.co.uk> wrote:
>>
>>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.
>
>It must? Much of why I love Python so much is because it's *both*.

There are bound to be some cases where both goals collide. The fuss
over / is a good example, IMO.

>using lots of simple, orthogonal constructs, Python manages that unusual
>feat. That's the main reason I was (and am) unhappy with the "print >>"
>proposal, but on the whole, I can't argue with Guido's ability to find
>solutions that promote the goals of both "easy learn" and "easy use".

That's true.


--
<"><"><"> 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

David Abrahams

unread,
Mar 31, 2002, 3:53:23 PM3/31/02
to

"Emile van Sebille" <em...@fenx.com> wrote in message
news:2NJp8.140405$Yv2.43077@rwcrnsc54...

> Someone (Guido?) already mentioned that testing for true is redundant,
> but doesn't :
> if 2:
> imply
> if 2 == True:
> which in turn then implies that:
> True == 2
> is true?

Not exactly.

if x:

would be the same as

if bool(x):

(which is the same way it works in C++, FWIW).

-Dave


John Roth

unread,
Mar 31, 2002, 4:30:31 PM3/31/02
to

"Erik Max Francis" <m...@alcyone.com> wrote in message
news:3CA75DAC...@alcyone.com...

> Ralph Corderoy wrote:
>
> > Terry Reedy wrote:
> >
> > > 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?
> >
> > That's an excellent point, as are the others you make. My Mum would
> > understand true but not bool or Boolean.
>
> I'm not really sure how beneficial this would be. In the real world,
> not everything about a programming language -- even a low-overhead
> language like Python -- can be instantly intuited by non-programmers.
> After some elementary level they're going to have to start reading.
> That bool (or boolean) is a Boolean type is not a hard concept to get
> across, and I don't see how calling it "truth" is really all that much
> more helpful.
>
> It's far better, in my opinion, to give it a standard name from
computer
> science (bool or boolean) and let new programmers take the tiny little
> steps (in this case) to add a new word to their vocabulary -- a word
> that will help them in future explorations of programming and computer
> science, no less.

The trouble is that 'bool' as a data type **isn't** the standard
name from mathematics. Correct usage is something like:
"Boolean logic manipulates truth values." That is, the data
type is a truth value (see, for example, "truth table".) The usage
in programming languages is simply incorrect linguistically.

Python has always had Boolean logic - and, or not and
so forth. What's being added is the truth data type.

> Excessive attempts to make terms more approachable can lead to
disaster
> in the degenerate case, resulting in just a new form of terminology
that
> now nobody understands.

But nobody has suggested calling it the Aristotelian data type.

John Roth


Martin v. Loewis

unread,
Mar 31, 2002, 5:07:32 PM3/31/02
to
Stefan Schwarzer <s.sch...@ndh.net> writes:

> Regarding special uses such as RPC and databases it would suffice to
> add a "boolean" module to the standard library. This would offer a
> standard way to handle a boolean type for these special purposes,
> wouldn't it?

How would it be different from what the PEP proposes?

Regards,
Martin

Tim Peters

unread,
Mar 31, 2002, 4:49:21 PM3/31/02
to
[Pearu Peterson]
> Theorem:
> ========
> Assume specification of PEP 285. The following statements hold truth:
>
> True is One
>
> and
>
> False is Zero,
>
> where One and Zero represent integers 1 and 0, respectively.

The theorem is false; it would be true if you replaced "is" by "==".

> Proof:
> ------
> According to PEP, True and False are instances of bool that is a
> subclass of int.

True.

> Therefore True and False can be considered as integers

Unclear what that means, exactly.

> and it makes sense to compare them with integers.

Except "is", in terms of which your theorem is stated, is a special kind of
comparison that can reveal non-guaranteed implementation accidents. To cut
this short, there's no guarantee that even

0 is 0

returns true, although it *happens* to be true in all implementations of
CPython to date (although for different internal reasons in different
implementations!). The PEP *does* guarantee that

True is True
False is False

are true; that's a stronger guarantee than is made for integers.

> If n is an integer then the following statements hold
>
> True == n only if n is 1

Only if you're using a non-Python meaning for "is". A true statement using
Python meanings would be

True == n if and only if n == 1

Note that this covers cases like

True == 1.0

too.

> ...


Pearu Peterson

unread,
Mar 31, 2002, 4:26:33 PM3/31/02
to

On 31 Mar 2002, Stefan Schwarzer wrote:

> bools and ints. For example, I consider it very unintutive that
> "True == 1" should by true but "True == 2" should be false. I


Just a random thought ...

Theorem:
========
Assume specification of PEP 285. The following statements hold truth:

True is One

and

False is Zero,

where One and Zero represent integers 1 and 0, respectively.

Proof:


------
According to PEP, True and False are instances of bool that is a subclass

of int. Therefore True and False can be considered as integers and it
makes sense to compare them with integers. If n is an integer then the
following statements hold

True == n only if n is 1

and

False == n only if n is 0.

Note that these statements still hold if n is varied within the set
of all standard Python objects:

{None} U Tuples U Lists U Strings U Numbers ..

with ==-relation defined as the Python ==-relation when comparing objects
of different types.

Q.E.D.

truth-is-True-is-One-is-1-is-integer-is-bool-really-necessary?'ly

Pearu


Martin v. Loewis

unread,
Mar 31, 2002, 5:18:37 PM3/31/02
to
Pearu Peterson <pe...@cens.ioc.ee> writes:

> Just a random thought ...
>
> Theorem:
> ========
> Assume specification of PEP 285. The following statements hold truth:
>
> True is One
>
> and
>
> False is Zero,
>
> where One and Zero represent integers 1 and 0, respectively.

It depends on what the meaning of 'is' is. Did you mean 'is' in the
Python sense of checking identity? Then this theorem can't possibly
true: type(One) is int and type(True) is bool implies One is not True.

>
> Proof:
> ------
> According to PEP, True and False are instances of bool that is a subclass
> of int. Therefore True and False can be considered as integers and it
> makes sense to compare them with integers. If n is an integer then the
> following statements hold
>
> True == n only if n is 1
>
> and
>
> False == n only if n is 0.

That is correct. However, a==b does not imply a is b.

Regards,
Martin

Ralph Corderoy

unread,
Mar 31, 2002, 5:16:37 PM3/31/02
to
Hi,

> [Ralph Corderoy, to Guido]
> > What do you think of `truth(x)' for all the good reasons listed
> > elsewhere in the thread? You used truth yourself instead of
> > Boolean above.
>
> Actually, he didn't.

Yes he did. You just snipped it so you'd have something to say ;-)

Guido wrote:

"IMO, bool(x) is the right way to "normalize" any value into a
truth value."

So there he is, using `truth' as opposed to `any value into a Boolean
value'.


Ralph.

Guido van Rossum

unread,
Mar 31, 2002, 5:52:00 PM3/31/02
to
"Martin v. Loewis" wrote:
>
> Ype Kingma <yki...@accessforall.nl> writes:
>
> > I'd like to know whether this PEP merging all numeric types would also merge
> > the bool type into its evt. hierarchy.
>
> See for yourself:
>
> http://python.sourceforge.net/peps/pep-0228.html
> http://python.sourceforge.net/peps/pep-0242.html

But see also my comments on these two in
http://www.python.org/doc/essays/pepparade.html; neither PEP is likely to
have any effect on Python's future.

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

Guido van Rossum

unread,
Mar 31, 2002, 6:00:37 PM3/31/02
to
> What do you think of `truth(x)' for all the good reasons listed
> elsewhere in the thread? You used truth yourself instead of Boolean
> above.

I didn't see any good reasons for calling it truth(). :-)

I am reminded of ABC, Python's predecessor. Its designers were very
concerned about newbies being confused by traditional computer science
terms like "function", "procedure" and "variable", so they invented
all new terminology. Functions ended up being called YIELDs,
procedures were HOW-TOs, statements became commands, and variables
became locations.

The main effect this had was to confuse the died-in-the-wool
programmers; it didn't make any difference for the newbies because
they had to learn the concepts anyway. When you come in with a
blank mind it doesn't matter if a particular concept is called
"variable" or "waffle" -- you have to learn a new meaning for an
existing word either way, and the previous meaning you knew for the
word is barely relevant in the new context.

So, I am adamantly against using "truth" for the new type -- many
languages (all the way back to Algol-60 and Pascal) call it Boolean or
bool. Given 'int', 'def' and 'dict', 'bool' feels more Pythonic than
'boolean'.

Pearu Peterson

unread,
Mar 31, 2002, 6:07:29 PM3/31/02
to

On 31 Mar 2002, Martin v. Loewis wrote:

> Pearu Peterson <pe...@cens.ioc.ee> writes:
>
> > Just a random thought ...
> >
> > Theorem:
> > ========
> > Assume specification of PEP 285. The following statements hold truth:
> >
> > True is One
> >
> > and
> >
> > False is Zero,
> >
> > where One and Zero represent integers 1 and 0, respectively.
>
> It depends on what the meaning of 'is' is. Did you mean 'is' in the
> Python sense of checking identity? Then this theorem can't possibly
> true: type(One) is int and type(True) is bool implies One is not True.

Sure, this theorem could be improved for correctness by starting defining
the meanings of words.

I could not use "is" in Python sense because Python does not define
objects One and Zero (note the use "represent" instead of "are"), for
instance. I used "is" in a general sense that in some cases coincides
with the Python "is" (as Tim already mentioned, also the 0 is 0 issue).

> > Proof:
> > ------
> > According to PEP, True and False are instances of bool that is a subclass
> > of int. Therefore True and False can be considered as integers and it
> > makes sense to compare them with integers. If n is an integer then the
> > following statements hold
> >
> > True == n only if n is 1
> >
> > and
> >
> > False == n only if n is 0.
>
> That is correct. However, a==b does not imply a is b.

Sure. My main point with this theorem is that the above statements hold
even if n is an arbitrary python object ("is" in a general sense).
Therefore I find objects True and 1 the same (and questioning the
necessity for introducing bool). They are not the same in Python
"is" sense but this is irrelevant (as an implementation issue): Python
"is" only compares Python objects and not the concepts that these objects
represent.

Later being more important to me, though, using the former quite often
with None. (BTW, None has not always the meaning of False, but the
meaning of "don't know" or "default", like in distutils).

Pearu


It is loading more messages.
0 new messages