8000 - patch #1600346 submitted by Tomer Filiba · python/cpython@4dafcc4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4dafcc4

Browse files
committed
- patch #1600346 submitted by Tomer Filiba
- Renamed nb_nonzero slots to nb_bool - Renamed __nonzero__ methods to __bool__ - update core, lib, docs, and tests to match
1 parent dfc9d4f commit 4dafcc4

31 files changed

+118
-82
lines changed

Demo/classes/Complex.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def __rcmp__(self, other):
165165
other = ToComplex(other)
166166
return cmp(other, self)
167167

168-
def __nonzero__(self):
168+
def __bool__(self):
169169
return not (self.re == self.im == 0)
170170

171171
abs = radius = __abs__

Demo/classes/Rat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def __rcmp__(b, a):
223223
return cmp(Rat(a), b)
224224

225225
# a != 0
226-
def __nonzero__(a):
226+
def __bool__(a):
227227
return a.__num != 0
228228

229229
# coercion

Doc/lib/liboperator.tex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ \section{\module{operator} ---
5555
Return the outcome of \keyword{not} \var{o}. (Note that there is no
5656
\method{__not__()} method for object instances; only the interpreter
5757
core defines this operation. The result is affected by the
58-
\method{__nonzero__()} and \method{__len__()} methods.)
58+
\method{__bool__()} and \method{__len__()} methods.)
5959
\end{funcdesc}
6060

6161
\begin{funcdesc}{truth}{o}

Doc/lib/libstdtypes.tex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ \section{Truth Value Testing\label{truth}}
5151
\item any empty mapping, for example, \code{\{\}}.
5252

5353
\item instances of user-defined classes, if the class defines a
54-
\method{__nonzero__()} or \method{__len__()} method, when that
54+
\method{__bool__()} or \method{__len__()} method, when that
5555
method returns the integer zero or \class{bool} value
5656
\code{False}.\footnote{Additional
5757
information on these special methods may be found in the

Doc/lib/libtimeit.tex

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -162,44 +162,44 @@ \subsection{Examples}
162162
missing and present object attributes.
163163

164164
\begin{verbatim}
165-
% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
165+
% timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass'
166166
100000 loops, best of 3: 15.7 usec per loop
167-
% timeit.py 'if hasattr(str, "__nonzero__"): pass'
167+
% timeit.py 'if hasattr(str, "__bool__"): pass'
168168
100000 loops, best of 3: 4.26 usec per loop
169-
% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
169+
% timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass'
170170
1000000 loops, best of 3: 1.43 usec per loop
171-
% timeit.py 'if hasattr(int, "__nonzero__"): pass'
171+
% timeit.py 'if hasattr(int, "__bool__"): pass'
172172
100000 loops, best of 3: 2.23 usec per loop
173173
\end{verbatim}
174174

175175
\begin{verbatim}
176176
>>> import timeit
177177
>>> s = """\
178178
... try:
179-
... str.__nonzero__
179+
... str.__bool__
180180
... except AttributeError:
181181
... pass
182182
... """
183183
>>> t = timeit.Timer(stmt=s)
184184
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
185185
17.09 usec/pass
186186
>>> s = """\
187-
... if hasattr(str, '__nonzero__'): pass
187+
... if hasattr(str, '__bool__'): pass
188188
... """
189189
>>> t = timeit.Timer(stmt=s)
190190
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
191191
4.85 usec/pass
192192
>>> s = """\
193193
... try:
194-
... int.__nonzero__
194+
... int.__bool__
195195
... except AttributeError:
196196
... pass
197197
... """
198198
>>> t = timeit.Timer(stmt=s)
199199
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
200200
1.97 usec/pass
201201
>>> s = """\
202-
... if hasattr(int, '__nonzero__'): pass
202+
... if hasattr(int, '__bool__'): pass
203203
... """
204204
>>> t = timeit.Timer(stmt=s)
205205
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

Doc/lib/libwinreg.tex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ \subsection{Registry Handle Objects \label{handle-object}}
375375
also accept an integer, however, use of the handle object is
376376
encouraged.
377377

378-
Handle objects provide semantics for \method{__nonzero__()} - thus
378+
Handle objects provide semantics for \method{__bool__()} - thus
379379
\begin{verbatim}
380380
if handle:
381381
print "Yes"

Doc/lib/libxmlrpclib.tex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ \subsection{Boolean Objects \label{boolean-objects}}
171171
This class may be initialized from any Python value; the instance
172172
returned depends only on its truth value. It supports various Python
173173
operators through \method{__cmp__()}, \method{__repr__()},
174-
\method{__int__()}, and \method{__nonzero__()} methods, all
174+
\method{__int__()}, and \method{__bool__()} methods, all
175175
implemented in the obvious ways.
176176

177177
It also has the following method, supported mainly for internal use by

Doc/ref/ref3.tex

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,13 +1313,13 @@ \subsection{Basic customization\label{customization}}
13131313
\withsubitem{(object method)}{\ttindex{__cmp__()}}
13141314
\end{methoddesc}
13151315

1316-
\begin{methoddesc}[object]{__nonzero__}{self}
1316+
\begin{methoddesc}[object]{__bool__}{self}
13171317
Called to implement truth value testing, and the built-in operation
1318-
\code{bool()}; should return \code{False} or \code{True}, or their
1319-
integer equivalents \code{0} or \code{1}.
1318+
\code{bool()}; should return \code{False} or \code{True}.
13201319
When this method is not defined, \method{__len__()} is
1321-
called, if it is defined (see below). If a class defines neither
1322-
\method{__len__()} nor \method{__nonzero__()}, all its instances are
1320+
called, if it is defined (see below) and \code{True} is returned when
1321+
the length is not zero. If a class defines neither
1322+
\method{__len__()} nor \method{__bool__()}, all its instances are
13231323
considered true.
13241324
\withsubitem{(mapping object method)}{\ttindex{__len__()}}
13251325
\end{methoddesc}
@@ -1693,9 +1693,9 @@ \subsection{Emulating container types\label{sequence-types}}
16931693
Called to implement the built-in function
16941694
\function{len()}\bifuncindex{len}. Should return the length of the
16951695
object, an integer \code{>=} 0. Also, an object that doesn't define a
1696-
\method{__nonzero__()} method and whose \method{__len__()} method
1696+
\method{__bool__()} method and whose \method{__len__()} method
16971697
returns zero is considered to be false in a Boolean context.
1698-
\withsubitem{(object method)}{\ttindex{__nonzero__()}}
1698+
\withsubitem{(object method)}{\ttindex{__bool__()}}
16991699
\end{methoddesc}
17001700

17011701
\begin{methoddesc}[container object]{__getitem__}{self, key}

Include/object.h

Copy file name to clipboard
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ typedef struct {
160160
unaryfunc nb_negative;
161161
unaryfunc nb_positive;
162162
unaryfunc nb_absolute;
163-
inquiry nb_nonzero;
163+
inquiry nb_bool;
164164
unaryfunc nb_invert;
165165
binaryfunc nb_lshift;
166166
binaryfunc nb_rshift;

Lib/decimal.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -633,14 +633,14 @@ def _check_nans(self, other = None, context=None):
633633
return other
634634
return 0
635635

636-
def __nonzero__(self):
636+
def __bool__(self):
637637
"""Is the number non-zero?
638638
639639
0 if self == 0
640640
1 if self != 0
641641
"""
642642
if self._is_special:
643-
return 1
643+
return True
644644
return sum(self._int) != 0
645645

646646
def __cmp__(self, other, context=None):
@@ -759,7 +759,7 @@ def __hash__(self):
759759
i = int(self)
760760
if self == Decimal(i):
761761
return hash(i)
762-
assert self.__nonzero__() # '-0' handled by integer case
762+
assert self.__bool__() # '-0' handled by integer case
763763
return hash(str(self.normalize()))
764764

765765
def as_tuple(self):

Lib/test/test_bool.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,24 +335,51 @@ def test_picklevalues(self):
335335

336336
def test_convert_to_bool(self):
337337
# Verify that TypeError occurs when bad things are returned
338-
# from __nonzero__(). This isn't really a bool test, but
338+
# from __bool__(). This isn't really a bool test, but
339339
# it's related.
340340
check = lambda o: self.assertRaises(TypeError, bool, o)
341341
class Foo(object):
342-
def __nonzero__(self):
342+
def __bool__(self):
343343
return self
344344
check(Foo())
345345

346346
class Bar(object):
347-
def __nonzero__(self):
347+
def __bool__(self):
348348
return "Yes"
349349
check(Bar())
350350

351351
class Baz(int):
352-
def __nonzero__(self):
352+
def __bool__(self):
353353
return self
354354
check(Baz())
355355

356+
# __bool__() must return a bool not an int
357+
class Spam(int):
358+
def __bool__(self):
359+
return 1
360+
check(Spam())
361+
362+
class Eggs:
363+
def __len__(self):
364+
return -1
365+
self.assertRaises(ValueError, bool, Eggs())
366+
367+
def test_sane_len(self):
368+
# this test just tests our assumptions about __len__
369+
# this will start failing if __len__ changes assertions
370+
for badval in ['illegal', -1, 1 << 32]:
371+
class A:
372+
def __len__(self):
373+
return badval
374+
try:
375+
bool(A())
376+
except (Exception), e_bool:
377+
pass
378+
try:
379+
len(A())
380+
except (Exception), e_len:
381+
pass
382+
self.assertEqual(str(e_bool), str(e_len))
356383

357384
def test_main():
358385
test_support.run_unittest(BoolTest)

Lib/test/test_builtin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def write(self, line):
9494
]
9595

9696
class TestFailingBool:
97-
def __nonzero__(self):
97+
def __bool__(self):
9898
raise RuntimeError
9999

100100
class TestFailingIter:

Lib/test/test_decimal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -990,7 +990,7 @@ def checkSameDec(operation, useOther=False):
990990
checkSameDec("__mod__", True)
991991
checkSameDec("__mul__", True)
992992
checkSameDec("__neg__")
993-
checkSameDec("__nonzero__")
993+
checkSameDec("__bool__")
994994
checkSameDec("__pos__")
995995
checkSameDec("__pow__", True)
996996
checkSameDec("__radd__", True)

Lib/test/test_descr.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -417,8 +417,8 @@ def ints():
417417
if verbose: print "Testing int operations..."
418418
numops(100, 3)
419419
# The following crashes in Python 2.2
420-
vereq((1).__nonzero__(), 1)
421-
vereq((0).__nonzero__(), 0)
420+
vereq((1).__bool__(), True)
421+
vereq((0).__bool__(), False)
422422
# This returns 'NotImplemented' in Python 2.2
423423
class C(int):
424424
def __add__(self, other):
@@ -1682,7 +1682,7 @@ def __getitem__(self, i):
16821682
class Proxy(object):
16831683
def __init__(self, x):
16841684
self.x = x
1685-
def __nonzero__(self):
1685+
def __bool__(self):
16861686
return not not self.x
16871687
def __hash__(self):
16881688
return hash(self.x)
@@ -1722,7 +1722,7 @@ def __contains__(self, value):
17221722
class DProxy(object):
17231723
def __init__(self, x):
17241724
self.x = x
1725-
def __nonzero__(self):
1725+
def __bool__(self):
17261726
return not not self.x
17271727
def __hash__(self):
17281728
return hash(self.x)

Lib/test/test_iter.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -327,10 +327,10 @@ def test_builtin_filter(self):
327327
class Boolean:
328328
def __init__(self, truth):
329329
self.truth = truth
330-
def __nonzero__(self):
330+
def __bool__(self):
331331
return self.truth
332-
bTrue = Boolean(1)
333-
bFalse = Boolean(0)
332+
bTrue = Boolean(True)
333+
bFalse = Boolean(False)
334334

335335
class Seq:
336336
def __init__(self, *args):

Lib/test/test_operator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ def test_sub(self):
319319

320320
def test_truth(self):
321321
class C(object):
322-
def __nonzero__(self):
322+
def __bool__(self):
323323
raise SyntaxError
324324
self.failUnlessRaises(TypeError, operator.truth)
325325
self.failUnlessRaises(SyntaxError, operator.truth, C())

Lib/test/test_richcmp.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def __setitem__(self, i, v):
5151
def __hash__(self):
5252
raise TypeError, "Vectors cannot be hashed"
5353

54-
def __nonzero__(self):
54+
def __bool__(self):
5555
raise TypeError, "Vectors cannot be used in Boolean contexts"
5656

5757
def __cmp__(self, other):
@@ -133,7 +133,7 @@ def test_mixed(self):
133133

134134
for ops in opmap.itervalues():
135135
for op in ops:
136-
# calls __nonzero__, which should fail
136+
# calls __bool__, which should fail
137137
self.assertRaises(TypeError, bool, op(a, b))
138138

139139
class NumberTest(unittest.TestCase):
@@ -208,13 +208,13 @@ def __cmp__(self, other): raise RuntimeError, "expected"
208208
self.assertRaises(RuntimeError, cmp, a, b)
209209

210210
def test_not(self):
211-
# Check that exceptions in __nonzero__ are properly
211+
# Check that exceptions in __bool__ are properly
212212
# propagated by the not operator
213213
import operator
214214
class Exc(Exception):
215215
pass
216216
class Bad:
217-
def __nonzero__(self):
217+
def __bool__(self):
218218
raise Exc
219219

220220
def do(bad):

Lib/xml/dom/minidom.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class Node(xml.dom.Node):
3838

3939
prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
4040

41-
def __nonzero__(self):
41+
def __bool__(self):
4242
return True
4343

4444
def toxml(self, encoding = None):

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ TO DO
3636
Core and Builtins
3737
-----------------
3838

39+
- Renamed nb_nonzero to nb_bool and __nonzero__ to __bool__
40+
3941
- Classic classes are a thing of the past. All classes are new style.
4042

4143
- Exceptions *must* derive from BaseException.

Modules/_ctypes/_ctypes.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4017,7 +4017,7 @@ static PyMethodDef Simple_methods[] = {
40174017
{ NULL, NULL },
40184018
};
40194019

4020-
static int Simple_nonzero(CDataObject *self)
4020+
static int Simple_bool(CDataObject *self)
40214021
{
40224022
return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
40234023
}
@@ -4032,7 +4032,7 @@ static PyNumberMethods Simple_as_number = {
40324032
0, /* nb_negative */
40334033
0, /* nb_positive */
40344034
0, /* nb_absolute */
4035-
(inquiry)Simple_nonzero, /* nb_nonzero */
4035+
(inquiry)Simple_bool, /* nb_bool */
40364036
};
40374037

40384038
#if (PY_VERSION_HEX < 0x02040000)
@@ -4364,7 +4364,7 @@ static PySequenceMethods Pointer_as_sequence = {
43644364
};
43654365

43664366
static int
4367-
Pointer_nonzero(CDataObject *self)
4367+
Pointer_bool(CDataObject *self)
43684368
{
43694369
return *(void **)self->b_ptr != NULL;
43704370
}
@@ -4379,7 +4379,7 @@ static PyNumberMethods Pointer_as_number = {
43794379
0, /* nb_negative */
43804380
0, /* nb_positive */
43814381
0, /* nb_absolute */
4382-
(inquiry)Pointer_nonzero, /* nb_nonzero */
4382+
(inquiry)Pointer_bool, /* nb_bool */
43834383
};
43844384

43854385
PyTypeObject Pointer_Type = {

0 commit comments

Comments
 (0)
0