Skip to content

Commit 77f6a65

Browse files
committed
Add the 'bool' type and its values 'False' and 'True', as described in
PEP 285. Everything described in the PEP is here, and there is even some documentation. I had to fix 12 unit tests; all but one of these were printing Boolean outcomes that changed from 0/1 to False/True. (The exception is test_unicode.py, which did a type(x) == type(y) style comparison. I could've fixed that with a single line using issubtype(x, type(y)), but instead chose to be explicit about those places where a bool is expected. Still to do: perhaps more documentation; change standard library modules to return False/True from predicates.
1 parent e9c0358 commit 77f6a65

29 files changed

+494
-383
lines changed

Doc/lib/libfuncs.tex

+10
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,16 @@ \section{Built-in Functions \label{built-in-funcs}}
7777
to \code{\var{function}(*\var{args}, **\var{keywords})}.
7878
\end{funcdesc}
7979

80+
\begin{funcdesc}{bool}{x}
81+
Convert a value to a Boolean, using the standard truth testing
82+
procedure. If \code{x} is false, this returns \code{False};
83+
otherwise it returns \code{True}. \code{bool} is also a class,
84+
which is a subclass of \code{int}. Class \code{bool} cannot be
85+
subclassed further. Its only instances are \code{False} and
86+
\code{True}.
87+
\indexii{Boolean}{type}
88+
\end{funcdesc}
89+
8090
\begin{funcdesc}{buffer}{object\optional{, offset\optional{, size}}}
8191
The \var{object} argument must be an object that supports the buffer
8292
call interface (such as strings, arrays, and buffers). A new buffer

Doc/lib/libstdtypes.tex

+31-10
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@ \section{Built-in Types \label{types}}
22

33
The following sections describe the standard types that are built into
44
the interpreter. These are the numeric types, sequence types, and
5-
several others, including types themselves. There is no explicit
6-
Boolean type; use integers instead.
5+
several others, including types themselves.
76
\indexii{built-in}{types}
8-
\indexii{Boolean}{type}
97

108
Some operations are supported by several object types; in particular,
119
all objects can be compared, tested for truth value, and converted to
@@ -30,6 +28,9 @@ \subsection{Truth Value Testing \label{truth}}
3028
\item \code{None}
3129
\withsubitem{(Built-in object)}{\ttindex{None}}
3230

31+
\item \code{False}
32+
\withsubitem{(Built-in object)}{\ttindex{False}}
33+
3334
\item zero of any numeric type, for example, \code{0}, \code{0L},
3435
\code{0.0}, \code{0j}.
3536

@@ -50,11 +51,12 @@ \subsection{Truth Value Testing \label{truth}}
5051
\index{true}
5152

5253
Operations and built-in functions that have a Boolean result always
53-
return \code{0} for false and \code{1} for true, unless otherwise
54-
stated. (Important exception: the Boolean operations
55-
\samp{or}\opindex{or} and \samp{and}\opindex{and} always return one of
56-
their operands.)
57-
54+
return \code{0} or \code{False} for false and \code{1} or \code{True}
55+
for true, unless otherwise stated. (Important exception: the Boolean
56+
operations \samp{or}\opindex{or} and \samp{and}\opindex{and} always
57+
return one of their operands.)
58+
\index{False}
59+
\index{True}
5860

5961
\subsection{Boolean Operations \label{boolean}}
6062

@@ -68,7 +70,7 @@ \subsection{Boolean Operations \label{boolean}}
6870
{if \var{x} is false, then \var{x}, else \var{y}}{(1)}
6971
\hline
7072
\lineiii{not \var{x}}
71-
{if \var{x} is false, then \code{1}, else \code{0}}{(2)}
73+
{if \var{x} is false, then \code{True}, else \code{False}}{(2)}
7274
\end{tableiii}
7375
\opindex{and}
7476
\opindex{or}
@@ -161,15 +163,18 @@ \subsection{Comparisons \label{comparisons}}
161163

162164
\subsection{Numeric Types \label{typesnumeric}}
163165

164-
There are four numeric types: \dfn{plain integers}, \dfn{long integers},
166+
There are four distinct numeric types: \dfn{plain integers},
167+
\dfn{long integers},
165168
\dfn{floating point numbers}, and \dfn{complex numbers}.
169+
In addition, Booleans are a subtype of plain integers.
166170
Plain integers (also just called \dfn{integers})
167171
are implemented using \ctype{long} in C, which gives them at least 32
168172
bits of precision. Long integers have unlimited precision. Floating
169173
point numbers are implemented using \ctype{double} in C. All bets on
170174
their precision are off unless you happen to know the machine you are
171175
working with.
172176
\obindex{numeric}
177+
\obindex{Boolean}
173178
\obindex{integer}
174179
\obindex{long integer}
175180
\obindex{floating point}
@@ -1389,6 +1394,22 @@ \subsubsection{The Ellipsis Object \label{bltin-ellipsis-object}}
13891394

13901395
It is written as \code{Ellipsis}.
13911396

1397+
\subsubsection{Boolean Values}
1398+
1399+
Boolean values are the two constant objects \code{False} and
1400+
\code{True}. They are used to represent truth values (although other
1401+
values can also be considered false or true). In numeric contexts
1402+
(for example when used as the argument to an arithmetic operator),
1403+
they behave like the integers 0 and 1, respectively. The built-in
1404+
function \function{bool()} can be used to cast any value to a Boolean,
1405+
if the value can be interpreted as a truth value (see section Truth
1406+
Value Testing above).
1407+
1408+
They are written as \code{False} and \code{True}, respectively.
1409+
\index{False}
1410+
\index{True}
1411+
\indexii{Boolean}{values}
1412+
13921413

13931414
\subsubsection{Internal Objects \label{typesinternal}}
13941415

Doc/ref/ref3.tex

+17-3
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ \section{The standard type hierarchy\label{types}}
162162
These represent elements from the mathematical set of whole numbers.
163163
\obindex{integer}
164164

165-
There are two types of integers:
165+
There are three types of integers:
166166

167167
\begin{description}
168168

@@ -187,6 +187,17 @@ \section{The standard type hierarchy\label{types}}
187187
an infinite string of sign bits extending to the left.
188188
\obindex{long integer}
189189

190+
\item[Booleans]
191+
These represent the truth values False and True. The two objects
192+
representing the values False and True are the only Boolean objects.
193+
The Boolean type is a subtype of plain integers, and Boolean values
194+
behave like the values 0 and 1, respectively, in almost all contexts,
195+
the exception being that when converted to a string, the strings
196+
\code{"False"} or \code{"True"} are returned, respectively.
197+
\obindex{Boolean}
198+
\ttindex{False}
199+
\ttindex{True}
200+
190201
\end{description} % Integers
191202

192203
The rules for integer representation are intended to give the most
@@ -222,6 +233,7 @@ \section{The standard type hierarchy\label{types}}
222233

223234
\end{description} % Numbers
224235

236+
225237
\item[Sequences]
226238
These represent finite ordered sets indexed by non-negative numbers.
227239
The built-in function \function{len()}\bifuncindex{len} returns the
@@ -1074,8 +1086,10 @@ \subsection{Basic customization\label{customization}}
10741086
\end{methoddesc}
10751087

10761088
\begin{methoddesc}[object]{__nonzero__}{self}
1077-
Called to implement truth value testing; should return \code{0} or
1078-
\code{1}. When this method is not defined, \method{__len__()} is
1089+
Called to implement truth value testing, and the built-in operation
1090+
\code{bool()}; should return \code{False} or \code{True}, or their
1091+
integer equivalents \code{0} or \code{1}.
1092+
When this method is not defined, \method{__len__()} is
10791093
called, if it is defined (see below). If a class defines neither
10801094
\method{__len__()} nor \method{__nonzero__()}, all its instances are
10811095
considered true.

Include/Python.h

+1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979

8080
#include "unicodeobject.h"
8181
#include "intobject.h"
82+
#include "boolobject.h"
8283
#include "longobject.h"
8384
#include "floatobject.h"
8485
#ifndef WITHOUT_COMPLEX

Include/intobject.h

-15
Original file line numberDiff line numberDiff line change
@@ -38,21 +38,6 @@ extern DL_IMPORT(PyObject *) PyInt_FromLong(long);
3838
extern DL_IMPORT(long) PyInt_AsLong(PyObject *);
3939
extern DL_IMPORT(long) PyInt_GetMax(void);
4040

41-
42-
/*
43-
False and True are special intobjects used by Boolean expressions.
44-
All values of type Boolean must point to either of these; but in
45-
contexts where integers are required they are integers (valued 0 and 1).
46-
Hope these macros don't conflict with other people's.
47-
48-
Don't forget to apply Py_INCREF() when returning True or False!!!
49-
*/
50-
51-
extern DL_IMPORT(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct; /* Don't use these directly */
52-
53-
#define Py_False ((PyObject *) &_Py_ZeroStruct)
54-
#define Py_True ((PyObject *) &_Py_TrueStruct)
55-
5641
/* Macro, trading safety for speed */
5742
#define PyInt_AS_LONG(op) (((PyIntObject *)(op))->ob_ival)
5843

Include/object.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -531,8 +531,8 @@ extern DL_IMPORT(long) _Py_RefTotal;
531531
#define Py_DECREF(op) \
532532
if (--_Py_RefTotal, 0 < (--((op)->ob_refcnt))) ; \
533533
else if (0 == (op)->ob_refcnt) _Py_Dealloc( (PyObject*)(op)); \
534-
else (void)fprintf( stderr, "%s:%i negative ref count %i\n", \
535-
__FILE__, __LINE__, (op)->ob_refcnt)
534+
else ((void)fprintf( stderr, "%s:%i negative ref count %i\n", \
535+
__FILE__, __LINE__, (op)->ob_refcnt), abort())
536536
#else /* !Py_REF_DEBUG */
537537

538538
#ifdef COUNT_ALLOCS

Lib/difflib.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -976,11 +976,11 @@ def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
976976
Examples:
977977
978978
>>> IS_LINE_JUNK('\n')
979-
1
979+
True
980980
>>> IS_LINE_JUNK(' # \n')
981-
1
981+
True
982982
>>> IS_LINE_JUNK('hello\n')
983-
0
983+
False
984984
"""
985985

986986
return pat(line) is not None
@@ -992,13 +992,13 @@ def IS_CHARACTER_JUNK(ch, ws=" \t"):
992992
Examples:
993993
994994
>>> IS_CHARACTER_JUNK(' ')
995-
1
995+
True
996996
>>> IS_CHARACTER_JUNK('\t')
997-
1
997+
True
998998
>>> IS_CHARACTER_JUNK('\n')
999-
0
999+
False
10001000
>>> IS_CHARACTER_JUNK('x')
1001-
0
1001+
False
10021002
"""
10031003

10041004
return ch in ws

Lib/doctest.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -545,19 +545,19 @@ def is_private(prefix, base):
545545
does not both begin and end with (at least) two underscores.
546546
547547
>>> is_private("a.b", "my_func")
548-
0
548+
False
549549
>>> is_private("____", "_my_func")
550-
1
550+
True
551551
>>> is_private("someclass", "__init__")
552-
0
552+
False
553553
>>> is_private("sometypo", "__init_")
554-
1
554+
True
555555
>>> is_private("x.y.z", "_")
556-
1
556+
True
557557
>>> is_private("_x.y.z", "__")
558-
0
558+
False
559559
>>> is_private("", "") # senseless but consistent
560-
0
560+
False
561561
"""
562562

563563
return base[:1] == "_" and not base[:2] == "__" == base[-2:]

Lib/pickle.py

+18
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ def __init__(self, value):
101101
EMPTY_TUPLE = ')'
102102
SETITEMS = 'u'
103103
BINFLOAT = 'G'
104+
TRUE = 'Z'
105+
FALSE = 'z'
106+
104107

105108
__all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
106109
del x
@@ -256,6 +259,13 @@ def save_none(self, object):
256259
self.write(NONE)
257260
dispatch[NoneType] = save_none
258261

262+
def save_bool(self, object):
263+
if object:
264+
self.write(TRUE)
265+
else:
266+
self.write(FALSE)
267+
dispatch[bool] = save_bool
268+
259269
def save_int(self, object):
260270
if self.bin:
261271
# If the int is small enough to fit in a signed 4-byte 2's-comp
@@ -629,6 +639,14 @@ def load_none(self):
629639
self.append(None)
630640
dispatch[NONE] = load_none
631641

642+
def load_false(self):
643+
self.append(False)
644+
dispatch[FALSE] = load_false
645+
646+
def load_true(self):
647+
self.append(True)
648+
dispatch[TRUE] = load_true
649+
632650
def load_int(self):
633651
data = self.readline()
634652
try:

Lib/test/output/test_augassign

+6-6
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ test_augassign
44
6
55
[1, 2, 3, 4, 1, 2, 3, 4]
66
[1, 2, 1, 2, 3]
7-
1
8-
1
9-
1
7+
True
8+
True
9+
True
1010
11
11-
1
11+
True
1212
12
13-
1
14-
1
13+
True
14+
True
1515
13
1616
__add__ called
1717
__radd__ called

Lib/test/output/test_extcall

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ h() argument after ** must be a dictionary
3131
dir() argument after ** must be a dictionary
3232
NoneType object argument after ** must be a dictionary
3333
dir() got multiple values for keyword argument 'b'
34-
3 512 1
34+
3 512 True
3535
3
3636
3
3737
za () {} -> za() takes exactly 1 argument (0 given)

Lib/test/output/test_gettext

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ trggrkg zrffntr pngnybt yvoenel.
2323
wink wink
2424
bacon
2525
test api 2
26-
1
26+
True
2727
gettext
2828
albatross
2929
bacon

Lib/test/output/test_grammar

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,6 @@ classdef
6060
[3, 4, 5]
6161
[(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]
6262
[(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), (5, 'Banana'), (5, 'Coconut')]
63-
[0, 0, 0]
63+
[False, False, False]
6464
[[1, 2], [3, 4], [5, 6]]
6565
[('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), ('Macdonalds', 'Cheeseburger')]

0 commit comments

Comments
 (0)