From python-3000-checkins at python.org Wed Nov 22 05:45:33 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 22 Nov 2006 05:45:33 +0100 (CET) Subject: [Python-3000-checkins] r52819 - python/branches/p3yk/Python/ceval.c Message-ID: <20061122044533.AA3DF1E4008@bag.python.org> Author: guido.van.rossum Date: Wed Nov 22 05:45:33 2006 New Revision: 52819 Modified: python/branches/p3yk/Python/ceval.c Log: Make it compile with older compilers. Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Wed Nov 22 05:45:33 2006 @@ -2721,11 +2721,11 @@ for (i = co->co_argcount; i < co->co_argcount + co->co_kwonlyargcount; i++) { + PyObject *name, *def; if (GETLOCAL(i) != NULL) continue; - PyObject *name = - PyTuple_GET_ITEM(co->co_varnames, i); - PyObject *def = NULL; + name = PyTuple_GET_ITEM(co->co_varnames, i); + def = NULL; if (kwdefs != NULL) def = PyDict_GetItem(kwdefs, name); if (def != NULL) { From python-3000-checkins at python.org Wed Nov 22 05:55:53 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 22 Nov 2006 05:55:53 +0100 (CET) Subject: [Python-3000-checkins] r52820 - in python/branches/p3yk/Lib: compiler/transformer.py test/test_compiler.py Message-ID: <20061122045553.AD3A01E4008@bag.python.org> Author: guido.van.rossum Date: Wed Nov 22 05:55:53 2006 New Revision: 52820 Modified: python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/test/test_compiler.py Log: The rest of patch 1549670 by Jiwon, making the compiler test pass. This removes some bogus debug stuff Jiwon accidentally left in last time. Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Wed Nov 22 05:55:53 2006 @@ -831,17 +831,11 @@ i = i + 3 else: # no vararg assert node[0] == token.COMMA - i += 1 - #elif node[0] == token.COMMA: - # i += 1 - # kwonlyargs, skip = self.keywordonlyargs(nodelist[i:]) - # i += skip - if nodelist[i][0] == token.NAME: + i += 2 + if i < len(nodelist) and nodelist[i][0] == token.NAME: kwonlyargs, skip = self.keywordonlyargs(nodelist[i:]) i += skip - print "kwonlyargs:", kwonlyargs - if i < len(nodelist): # should be DOUBLESTAR t = nodelist[i][0] @@ -869,7 +863,6 @@ # skip the comma i = i + 1 - print "names:", names, "defaults:", defaults, "kwonlyargs:", kwonlyargs, "flags:", flags return names, defaults, kwonlyargs, flags def com_fpdef(self, node): Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Wed Nov 22 05:55:53 2006 @@ -19,51 +19,36 @@ libdir = os.path.dirname(unittest.__file__) testdir = os.path.dirname(test.test_support.__file__) -## for dir in [libdir, testdir]: -## for basename in os.listdir(dir): -## # Print still working message since this test can be really slow -## if next_time <= time.time(): -## next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL -## print >>sys.__stdout__, \ -## ' testCompileLibrary still working, be patient...' -## sys.__stdout__.flush() -## -## if not basename.endswith(".py"): -## continue -## if not TEST_ALL and random() < 0.98: -## continue -## path = os.path.join(dir, basename) -## if test.test_support.verbose: -## print "compiling", path -## f = open(path, "U") -## buf = f.read() -## f.close() -## if "badsyntax" in basename or "bad_coding" in basename: -## self.assertRaises(SyntaxError, compiler.compile, -## buf, basename, "exec") -## else: -## try: -## compiler.compile(buf, basename, "exec") -## except Exception, e: -## args = list(e.args) -## args[0] += "[in file %s]" % basename -## e.args = tuple(args) -## raise - - path = "/home/jiwon/p3yk/Lib/test/test_keywordonlyarg.py" - if test.test_support.verbose: - print "compiling", path - f = open(path, "U") - buf = f.read() - f.close() - #try: - compiler.compile(buf, "test_keywordonlyarg.py", "exec") - #except Exception, e: - # args = list(e.args) - # args[0] += "[in file %s]" % path - # e.args = tuple(args) - # raise - + for dir in [libdir, testdir]: + for basename in os.listdir(dir): + # Print still working message since this test can be really slow + if next_time <= time.time(): + next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL + print >>sys.__stdout__, \ + ' testCompileLibrary still working, be patient...' + sys.__stdout__.flush() + + if not basename.endswith(".py"): + continue + if not TEST_ALL and random() < 0.98: + continue + path = os.path.join(dir, basename) + if test.test_support.verbose: + print "compiling", path + f = open(path, "U") + buf = f.read() + f.close() + if "badsyntax" in basename or "bad_coding" in basename: + self.assertRaises(SyntaxError, compiler.compile, + buf, basename, "exec") + else: + try: + compiler.compile(buf, basename, "exec") + except Exception, e: + args = list(e.args) + args[0] += "[in file %s]" % basename + e.args = tuple(args) + raise def testNewClassSyntax(self): compiler.compile("class foo():pass\n\n","","exec") From python-3000-checkins at python.org Wed Nov 22 15:42:42 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 22 Nov 2006 15:42:42 +0100 (CET) Subject: [Python-3000-checkins] r52823 - python/branches/p3yk/Lib/test/test_keywordonlyarg.py Message-ID: <20061122144242.7516D1E4009@bag.python.org> Author: guido.van.rossum Date: Wed Nov 22 15:42:41 2006 New Revision: 52823 Added: python/branches/p3yk/Lib/test/test_keywordonlyarg.py (contents, props changed) Log: Unit tests for PEP 3102, by Jiwon Seo. Forgot to add these earlier. Added: python/branches/p3yk/Lib/test/test_keywordonlyarg.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/test/test_keywordonlyarg.py Wed Nov 22 15:42:41 2006 @@ -0,0 +1,151 @@ +#!/usr/bin/env python + +"""Unit tests for the keyword only argument specified in PEP 3102.""" + +__author__ = "Jiwon Seo" +__email__ = "seojiwon at gmail dot com" + +import unittest +from test.test_support import run_unittest + +def posonly_sum(pos_arg1, *arg, **kwarg): + return pos_arg1 + sum(arg) + sum(kwarg.values()) +def keywordonly_sum(*, k1=0, k2): + return k1 + k2 +def keywordonly_nodefaults_sum(*, k1, k2): + return k1 + k2 +def keywordonly_and_kwarg_sum(*, k1, k2, **kwarg): + return k1 + k2 + sum(kwarg.values()) +def mixedargs_sum(a, b=0, *arg, k1, k2=0): + return a + b + k1 + k2 + sum(arg) +def mixedargs_sum2(a, b=0, *arg, k1, k2=0, **kwargs): + return a + b + k1 + k2 + sum(arg) + sum(kwargs.values()) + +def sortnum(*nums, reverse=False): + return sorted(list(nums), reverse=reverse) + +def sortwords(*words, reverse=False, **kwargs): + return sorted(list(words), reverse=reverse) + +class Foo: + def __init__(self, *, k1, k2=0): + self.k1 = k1 + self.k2 = k2 + def set(self, p1, *, k1, k2): + self.k1 = k1 + self.k2 = k2 + def sum(self): + return self.k1 + self.k2 + +class KeywordOnlyArgTestCase(unittest.TestCase): + def assertRaisesSyntaxError(self, codestr): + def shouldRaiseSyntaxError(s): + compile(s, "", "single") + self.assertRaises(SyntaxError, shouldRaiseSyntaxError, codestr) + + def testSyntaxErrorForFunctionDefinition(self): + self.assertRaisesSyntaxError("def f(p, *):\n pass\n") + self.assertRaisesSyntaxError("def f(p1, *, p1=100):\n pass\n") + self.assertRaisesSyntaxError("def f(p1, *k1, k1=100):\n pass\n") + self.assertRaisesSyntaxError("def f(p1, *, k1, k1=100):\n pass\n") + self.assertRaisesSyntaxError("def f(p1, *, k1, **k1):\n pass\n") + self.assertRaisesSyntaxError("def f(p1, *, None, **k1):\n pass\n") + self.assertRaisesSyntaxError("def f(p, *, (k1, k2), **kw):\n pass\n") + + def testSyntaxForManyArguments(self): + fundef = "def f(" + for i in range(255): + fundef += "i%d, "%i + fundef += "*, key=100):\n pass\n" + self.assertRaisesSyntaxError(fundef) + + fundef2 = "def foo(i,*," + for i in range(255): + fundef2 += "i%d, "%i + fundef2 += "lastarg):\n pass\n" + self.assertRaisesSyntaxError(fundef2) + + # exactly 255 arguments, should compile ok + fundef3 = "def f(i,*," + for i in range(253): + fundef3 += "i%d, "%i + fundef3 += "lastarg):\n pass\n" + compile(fundef3, "", "single") + + def testSyntaxErrorForFunctionCall(self): + self.assertRaisesSyntaxError("f(p, k=1, p2)") + self.assertRaisesSyntaxError("f(p, *(1,2), k1=100)") + + def testRaiseErrorFuncallWithUnexpectedKeywordArgument(self): + self.assertRaises(TypeError, keywordonly_sum, ()) + self.assertRaises(TypeError, keywordonly_nodefaults_sum, ()) + self.assertRaises(TypeError, Foo, ()) + try: + keywordonly_sum(k2=100, non_existing_arg=200) + self.fail("should raise TypeError") + except TypeError: + pass + try: + keywordonly_nodefaults_sum(k2=2) + self.fail("should raise TypeError") + except TypeError: + pass + + def testFunctionCall(self): + self.assertEquals(1, posonly_sum(1)) + self.assertEquals(1+2, posonly_sum(1,**{"2":2})) + self.assertEquals(1+2+3, posonly_sum(1,*(2,3))) + self.assertEquals(1+2+3+4, posonly_sum(1,*(2,3),**{"4":4})) + + self.assertEquals(1, keywordonly_sum(k2=1)) + self.assertEquals(1+2, keywordonly_sum(k1=1, k2=2)) + + self.assertEquals(1+2, keywordonly_and_kwarg_sum(k1=1, k2=2)) + self.assertEquals(1+2+3, keywordonly_and_kwarg_sum(k1=1, k2=2, k3=3)) + self.assertEquals(1+2+3+4, + keywordonly_and_kwarg_sum(k1=1, k2=2, + **{"a":3,"b":4})) + + self.assertEquals(1+2, mixedargs_sum(1, k1=2)) + self.assertEquals(1+2+3, mixedargs_sum(1, 2, k1=3)) + self.assertEquals(1+2+3+4, mixedargs_sum(1, 2, k1=3, k2=4)) + self.assertEquals(1+2+3+4+5, mixedargs_sum(1, 2, 3, k1=4, k2=5)) + + self.assertEquals(1+2, mixedargs_sum2(1, k1=2)) + self.assertEquals(1+2+3, mixedargs_sum2(1, 2, k1=3)) + self.assertEquals(1+2+3+4, mixedargs_sum2(1, 2, k1=3, k2=4)) + self.assertEquals(1+2+3+4+5, mixedargs_sum2(1, 2, 3, k1=4, k2=5)) + self.assertEquals(1+2+3+4+5+6, + mixedargs_sum2(1, 2, 3, k1=4, k2=5, k3=6)) + self.assertEquals(1+2+3+4+5+6, + mixedargs_sum2(1, 2, 3, k1=4, **{'k2':5, 'k3':6})) + + self.assertEquals(1, Foo(k1=1).sum()) + self.assertEquals(1+2, Foo(k1=1,k2=2).sum()) + + self.assertEquals([1,2,3], sortnum(3,2,1)) + self.assertEquals([3,2,1], sortnum(1,2,3, reverse=True)) + + self.assertEquals(['a','b','c'], sortwords('a','c','b')) + self.assertEquals(['c','b','a'], sortwords('a','c','b', reverse=True)) + self.assertEquals(['c','b','a'], + sortwords('a','c','b', reverse=True, ignore='ignore')) + + def testKwDefaults(self): + def foo(p1,p2=0, *, k1, k2=0): + return p1 + p2 + k1 + k2 + + self.assertEquals(2, foo.func_code.co_kwonlyargcount) + self.assertEquals({"k2":0}, foo.func_kwdefaults) + foo.func_kwdefaults = {"k1":0} + try: + foo(1,k1=10) + self.fail("func_kwdefaults is not properly changed") + except TypeError: + pass + +def test_main(): + run_unittest(KeywordOnlyArgTestCase) + +if __name__ == "__main__": + test_main() From python-3000-checkins at python.org Tue Nov 28 20:15:39 2006 From: python-3000-checkins at python.org (jack.diederich) Date: Tue, 28 Nov 2006 20:15:39 +0100 (CET) Subject: [Python-3000-checkins] r52853 - in python/branches/p3yk: Demo/classes/Complex.py Demo/classes/Rat.py Doc/lib/liboperator.tex Doc/lib/libstdtypes.tex Doc/lib/libtimeit.tex Doc/lib/libwinreg.tex Doc/lib/libxmlrpclib.tex Doc/ref/ref3.tex Include/object.h Lib/decimal.py Lib/test/test_bool.py Lib/test/test_builtin.py Lib/test/test_decimal.py Lib/test/test_descr.py Lib/test/test_iter.py Lib/test/test_operator.py Lib/test/test_richcmp.py Lib/xml/dom/minidom.py Misc/NEWS Modules/_ctypes/_ctypes.c Modules/datetimemodule.c Objects/boolobject.c Objects/complexobject.c Objects/floatobject.c Objects/intobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/typeobject.c Objects/weakrefobject.c PC/_winreg.c Message-ID: <20061128191539.5E7B01E400F@bag.python.org> Author: jack.diederich Date: Tue Nov 28 20:15:13 2006 New Revision: 52853 Modified: python/branches/p3yk/Demo/classes/Complex.py python/branches/p3yk/Demo/classes/Rat.py python/branches/p3yk/Doc/lib/liboperator.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libtimeit.tex python/branches/p3yk/Doc/lib/libwinreg.tex python/branches/p3yk/Doc/lib/libxmlrpclib.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_decimal.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_iter.py python/branches/p3yk/Lib/test/test_operator.py python/branches/p3yk/Lib/test/test_richcmp.py python/branches/p3yk/Lib/xml/dom/minidom.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Modules/_ctypes/_ctypes.c python/branches/p3yk/Modules/datetimemodule.c python/branches/p3yk/Objects/boolobject.c python/branches/p3yk/Objects/complexobject.c python/branches/p3yk/Objects/floatobject.c python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/longobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/weakrefobject.c python/branches/p3yk/PC/_winreg.c Log: - 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 Modified: python/branches/p3yk/Demo/classes/Complex.py ============================================================================== --- python/branches/p3yk/Demo/classes/Complex.py (original) +++ python/branches/p3yk/Demo/classes/Complex.py Tue Nov 28 20:15:13 2006 @@ -165,7 +165,7 @@ other = ToComplex(other) return cmp(other, self) - def __nonzero__(self): + def __bool__(self): return not (self.re == self.im == 0) abs = radius = __abs__ Modified: python/branches/p3yk/Demo/classes/Rat.py ============================================================================== --- python/branches/p3yk/Demo/classes/Rat.py (original) +++ python/branches/p3yk/Demo/classes/Rat.py Tue Nov 28 20:15:13 2006 @@ -223,7 +223,7 @@ return cmp(Rat(a), b) # a != 0 - def __nonzero__(a): + def __bool__(a): return a.__num != 0 # coercion Modified: python/branches/p3yk/Doc/lib/liboperator.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liboperator.tex (original) +++ python/branches/p3yk/Doc/lib/liboperator.tex Tue Nov 28 20:15:13 2006 @@ -55,7 +55,7 @@ Return the outcome of \keyword{not} \var{o}. (Note that there is no \method{__not__()} method for object instances; only the interpreter core defines this operation. The result is affected by the -\method{__nonzero__()} and \method{__len__()} methods.) +\method{__bool__()} and \method{__len__()} methods.) \end{funcdesc} \begin{funcdesc}{truth}{o} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Tue Nov 28 20:15:13 2006 @@ -51,7 +51,7 @@ \item any empty mapping, for example, \code{\{\}}. \item instances of user-defined classes, if the class defines a - \method{__nonzero__()} or \method{__len__()} method, when that + \method{__bool__()} or \method{__len__()} method, when that method returns the integer zero or \class{bool} value \code{False}.\footnote{Additional information on these special methods may be found in the Modified: python/branches/p3yk/Doc/lib/libtimeit.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtimeit.tex (original) +++ python/branches/p3yk/Doc/lib/libtimeit.tex Tue Nov 28 20:15:13 2006 @@ -162,13 +162,13 @@ missing and present object attributes. \begin{verbatim} -% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' +% timeit.py 'try:' ' str.__bool__' 'except AttributeError:' ' pass' 100000 loops, best of 3: 15.7 usec per loop -% timeit.py 'if hasattr(str, "__nonzero__"): pass' +% timeit.py 'if hasattr(str, "__bool__"): pass' 100000 loops, best of 3: 4.26 usec per loop -% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' +% timeit.py 'try:' ' int.__bool__' 'except AttributeError:' ' pass' 1000000 loops, best of 3: 1.43 usec per loop -% timeit.py 'if hasattr(int, "__nonzero__"): pass' +% timeit.py 'if hasattr(int, "__bool__"): pass' 100000 loops, best of 3: 2.23 usec per loop \end{verbatim} @@ -176,7 +176,7 @@ >>> import timeit >>> s = """\ ... try: -... str.__nonzero__ +... str.__bool__ ... except AttributeError: ... pass ... """ @@ -184,14 +184,14 @@ >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 17.09 usec/pass >>> s = """\ -... if hasattr(str, '__nonzero__'): pass +... if hasattr(str, '__bool__'): pass ... """ >>> t = timeit.Timer(stmt=s) >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 4.85 usec/pass >>> s = """\ ... try: -... int.__nonzero__ +... int.__bool__ ... except AttributeError: ... pass ... """ @@ -199,7 +199,7 @@ >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 1.97 usec/pass >>> s = """\ -... if hasattr(int, '__nonzero__'): pass +... if hasattr(int, '__bool__'): pass ... """ >>> t = timeit.Timer(stmt=s) >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) Modified: python/branches/p3yk/Doc/lib/libwinreg.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libwinreg.tex (original) +++ python/branches/p3yk/Doc/lib/libwinreg.tex Tue Nov 28 20:15:13 2006 @@ -375,7 +375,7 @@ also accept an integer, however, use of the handle object is encouraged. - Handle objects provide semantics for \method{__nonzero__()} - thus + Handle objects provide semantics for \method{__bool__()} - thus \begin{verbatim} if handle: print "Yes" Modified: python/branches/p3yk/Doc/lib/libxmlrpclib.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libxmlrpclib.tex (original) +++ python/branches/p3yk/Doc/lib/libxmlrpclib.tex Tue Nov 28 20:15:13 2006 @@ -171,7 +171,7 @@ This class may be initialized from any Python value; the instance returned depends only on its truth value. It supports various Python operators through \method{__cmp__()}, \method{__repr__()}, -\method{__int__()}, and \method{__nonzero__()} methods, all +\method{__int__()}, and \method{__bool__()} methods, all implemented in the obvious ways. It also has the following method, supported mainly for internal use by Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Tue Nov 28 20:15:13 2006 @@ -1313,13 +1313,13 @@ \withsubitem{(object method)}{\ttindex{__cmp__()}} \end{methoddesc} -\begin{methoddesc}[object]{__nonzero__}{self} +\begin{methoddesc}[object]{__bool__}{self} Called to implement truth value testing, and the built-in operation -\code{bool()}; should return \code{False} or \code{True}, or their -integer equivalents \code{0} or \code{1}. +\code{bool()}; should return \code{False} or \code{True}. When this method is not defined, \method{__len__()} is -called, if it is defined (see below). If a class defines neither -\method{__len__()} nor \method{__nonzero__()}, all its instances are +called, if it is defined (see below) and \code{True} is returned when +the length is not zero. If a class defines neither +\method{__len__()} nor \method{__bool__()}, all its instances are considered true. \withsubitem{(mapping object method)}{\ttindex{__len__()}} \end{methoddesc} @@ -1693,9 +1693,9 @@ Called to implement the built-in function \function{len()}\bifuncindex{len}. Should return the length of the object, an integer \code{>=} 0. Also, an object that doesn't define a -\method{__nonzero__()} method and whose \method{__len__()} method +\method{__bool__()} method and whose \method{__len__()} method returns zero is considered to be false in a Boolean context. -\withsubitem{(object method)}{\ttindex{__nonzero__()}} +\withsubitem{(object method)}{\ttindex{__bool__()}} \end{methoddesc} \begin{methoddesc}[container object]{__getitem__}{self, key} Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Tue Nov 28 20:15:13 2006 @@ -160,7 +160,7 @@ unaryfunc nb_negative; unaryfunc nb_positive; unaryfunc nb_absolute; - inquiry nb_nonzero; + inquiry nb_bool; unaryfunc nb_invert; binaryfunc nb_lshift; binaryfunc nb_rshift; Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Tue Nov 28 20:15:13 2006 @@ -633,14 +633,14 @@ return other return 0 - def __nonzero__(self): + def __bool__(self): """Is the number non-zero? 0 if self == 0 1 if self != 0 """ if self._is_special: - return 1 + return True return sum(self._int) != 0 def __cmp__(self, other, context=None): @@ -759,7 +759,7 @@ i = int(self) if self == Decimal(i): return hash(i) - assert self.__nonzero__() # '-0' handled by integer case + assert self.__bool__() # '-0' handled by integer case return hash(str(self.normalize())) def as_tuple(self): Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Tue Nov 28 20:15:13 2006 @@ -335,24 +335,51 @@ def test_convert_to_bool(self): # Verify that TypeError occurs when bad things are returned - # from __nonzero__(). This isn't really a bool test, but + # from __bool__(). This isn't really a bool test, but # it's related. check = lambda o: self.assertRaises(TypeError, bool, o) class Foo(object): - def __nonzero__(self): + def __bool__(self): return self check(Foo()) class Bar(object): - def __nonzero__(self): + def __bool__(self): return "Yes" check(Bar()) class Baz(int): - def __nonzero__(self): + def __bool__(self): return self check(Baz()) + # __bool__() must return a bool not an int + class Spam(int): + def __bool__(self): + return 1 + check(Spam()) + + class Eggs: + def __len__(self): + return -1 + self.assertRaises(ValueError, bool, Eggs()) + + def test_sane_len(self): + # this test just tests our assumptions about __len__ + # this will start failing if __len__ changes assertions + for badval in ['illegal', -1, 1 << 32]: + class A: + def __len__(self): + return badval + try: + bool(A()) + except (Exception), e_bool: + pass + try: + len(A()) + except (Exception), e_len: + pass + self.assertEqual(str(e_bool), str(e_len)) def test_main(): test_support.run_unittest(BoolTest) Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Tue Nov 28 20:15:13 2006 @@ -94,7 +94,7 @@ ] class TestFailingBool: - def __nonzero__(self): + def __bool__(self): raise RuntimeError class TestFailingIter: Modified: python/branches/p3yk/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decimal.py (original) +++ python/branches/p3yk/Lib/test/test_decimal.py Tue Nov 28 20:15:13 2006 @@ -990,7 +990,7 @@ checkSameDec("__mod__", True) checkSameDec("__mul__", True) checkSameDec("__neg__") - checkSameDec("__nonzero__") + checkSameDec("__bool__") checkSameDec("__pos__") checkSameDec("__pow__", True) checkSameDec("__radd__", True) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Tue Nov 28 20:15:13 2006 @@ -417,8 +417,8 @@ if verbose: print "Testing int operations..." numops(100, 3) # The following crashes in Python 2.2 - vereq((1).__nonzero__(), 1) - vereq((0).__nonzero__(), 0) + vereq((1).__bool__(), True) + vereq((0).__bool__(), False) # This returns 'NotImplemented' in Python 2.2 class C(int): def __add__(self, other): @@ -1682,7 +1682,7 @@ class Proxy(object): def __init__(self, x): self.x = x - def __nonzero__(self): + def __bool__(self): return not not self.x def __hash__(self): return hash(self.x) @@ -1722,7 +1722,7 @@ class DProxy(object): def __init__(self, x): self.x = x - def __nonzero__(self): + def __bool__(self): return not not self.x def __hash__(self): return hash(self.x) Modified: python/branches/p3yk/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iter.py (original) +++ python/branches/p3yk/Lib/test/test_iter.py Tue Nov 28 20:15:13 2006 @@ -327,10 +327,10 @@ class Boolean: def __init__(self, truth): self.truth = truth - def __nonzero__(self): + def __bool__(self): return self.truth - bTrue = Boolean(1) - bFalse = Boolean(0) + bTrue = Boolean(True) + bFalse = Boolean(False) class Seq: def __init__(self, *args): Modified: python/branches/p3yk/Lib/test/test_operator.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operator.py (original) +++ python/branches/p3yk/Lib/test/test_operator.py Tue Nov 28 20:15:13 2006 @@ -319,7 +319,7 @@ def test_truth(self): class C(object): - def __nonzero__(self): + def __bool__(self): raise SyntaxError self.failUnlessRaises(TypeError, operator.truth) self.failUnlessRaises(SyntaxError, operator.truth, C()) Modified: python/branches/p3yk/Lib/test/test_richcmp.py ============================================================================== --- python/branches/p3yk/Lib/test/test_richcmp.py (original) +++ python/branches/p3yk/Lib/test/test_richcmp.py Tue Nov 28 20:15:13 2006 @@ -51,7 +51,7 @@ def __hash__(self): raise TypeError, "Vectors cannot be hashed" - def __nonzero__(self): + def __bool__(self): raise TypeError, "Vectors cannot be used in Boolean contexts" def __cmp__(self, other): @@ -133,7 +133,7 @@ for ops in opmap.itervalues(): for op in ops: - # calls __nonzero__, which should fail + # calls __bool__, which should fail self.assertRaises(TypeError, bool, op(a, b)) class NumberTest(unittest.TestCase): @@ -208,13 +208,13 @@ self.assertRaises(RuntimeError, cmp, a, b) def test_not(self): - # Check that exceptions in __nonzero__ are properly + # Check that exceptions in __bool__ are properly # propagated by the not operator import operator class Exc(Exception): pass class Bad: - def __nonzero__(self): + def __bool__(self): raise Exc def do(bad): Modified: python/branches/p3yk/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/minidom.py (original) +++ python/branches/p3yk/Lib/xml/dom/minidom.py Tue Nov 28 20:15:13 2006 @@ -38,7 +38,7 @@ prefix = EMPTY_PREFIX # non-null only for NS elements and attributes - def __nonzero__(self): + def __bool__(self): return True def toxml(self, encoding = None): Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Nov 28 20:15:13 2006 @@ -36,6 +36,8 @@ Core and Builtins ----------------- +- Renamed nb_nonzero to nb_bool and __nonzero__ to __bool__ + - Classic classes are a thing of the past. All classes are new style. - Exceptions *must* derive from BaseException. Modified: python/branches/p3yk/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/_ctypes.c (original) +++ python/branches/p3yk/Modules/_ctypes/_ctypes.c Tue Nov 28 20:15:13 2006 @@ -4017,7 +4017,7 @@ { NULL, NULL }, }; -static int Simple_nonzero(CDataObject *self) +static int Simple_bool(CDataObject *self) { return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); } @@ -4032,7 +4032,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - (inquiry)Simple_nonzero, /* nb_nonzero */ + (inquiry)Simple_bool, /* nb_bool */ }; #if (PY_VERSION_HEX < 0x02040000) @@ -4364,7 +4364,7 @@ }; static int -Pointer_nonzero(CDataObject *self) +Pointer_bool(CDataObject *self) { return *(void **)self->b_ptr != NULL; } @@ -4379,7 +4379,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - (inquiry)Pointer_nonzero, /* nb_nonzero */ + (inquiry)Pointer_bool, /* nb_bool */ }; PyTypeObject Pointer_Type = { Modified: python/branches/p3yk/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk/Modules/datetimemodule.c (original) +++ python/branches/p3yk/Modules/datetimemodule.c Tue Nov 28 20:15:13 2006 @@ -1958,7 +1958,7 @@ } static int -delta_nonzero(PyDateTime_Delta *self) +delta_bool(PyDateTime_Delta *self) { return (GET_TD_DAYS(self) != 0 || GET_TD_SECONDS(self) != 0 @@ -2083,7 +2083,7 @@ (unaryfunc)delta_negative, /* nb_negative */ (unaryfunc)delta_positive, /* nb_positive */ (unaryfunc)delta_abs, /* nb_absolute */ - (inquiry)delta_nonzero, /* nb_nonzero */ + (inquiry)delta_bool, /* nb_bool */ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ @@ -2653,7 +2653,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - 0, /* nb_nonzero */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateType = { @@ -3324,7 +3324,7 @@ } static int -time_nonzero(PyDateTime_Time *self) +time_bool(PyDateTime_Time *self) { int offset; int none; @@ -3418,7 +3418,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - (inquiry)time_nonzero, /* nb_nonzero */ + (inquiry)time_bool, /* nb_bool */ }; static PyTypeObject PyDateTime_TimeType = { @@ -4501,7 +4501,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - 0, /* nb_nonzero */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateTimeType = { Modified: python/branches/p3yk/Objects/boolobject.c ============================================================================== --- python/branches/p3yk/Objects/boolobject.c (original) +++ python/branches/p3yk/Objects/boolobject.c Tue Nov 28 20:15:13 2006 @@ -112,7 +112,7 @@ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ - 0, /* nb_nonzero */ + 0, /* nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ Modified: python/branches/p3yk/Objects/complexobject.c ============================================================================== --- python/branches/p3yk/Objects/complexobject.c (original) +++ python/branches/p3yk/Objects/complexobject.c Tue Nov 28 20:15:13 2006 @@ -568,7 +568,7 @@ } static int -complex_nonzero(PyComplexObject *v) +complex_bool(PyComplexObject *v) { return v->cval.real != 0.0 || v->cval.imag != 0.0; } @@ -938,7 +938,7 @@ (unaryfunc)complex_neg, /* nb_negative */ (unaryfunc)complex_pos, /* nb_positive */ (unaryfunc)complex_abs, /* nb_absolute */ - (inquiry)complex_nonzero, /* nb_nonzero */ + (inquiry)complex_bool, /* nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ Modified: python/branches/p3yk/Objects/floatobject.c ============================================================================== --- python/branches/p3yk/Objects/floatobject.c (original) +++ python/branches/p3yk/Objects/floatobject.c Tue Nov 28 20:15:13 2006 @@ -837,7 +837,7 @@ } static int -float_nonzero(PyFloatObject *v) +float_bool(PyFloatObject *v) { return v->ob_fval != 0.0; } @@ -1087,7 +1087,7 @@ (unaryfunc)float_neg, /*nb_negative*/ (unaryfunc)float_pos, /*nb_positive*/ (unaryfunc)float_abs, /*nb_absolute*/ - (inquiry)float_nonzero, /*nb_nonzero*/ + (inquiry)float_bool, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Tue Nov 28 20:15:13 2006 @@ -780,7 +780,7 @@ } static int -int_nonzero(PyIntObject *v) +int_bool(PyIntObject *v) { return v->ob_ival != 0; } @@ -1034,14 +1034,14 @@ (unaryfunc)int_neg, /*nb_negative*/ (unaryfunc)int_pos, /*nb_positive*/ (unaryfunc)int_abs, /*nb_absolute*/ - (inquiry)int_nonzero, /*nb_nonzero*/ + (inquiry)int_bool, /*nb_bool*/ (unaryfunc)int_invert, /*nb_invert*/ (binaryfunc)int_lshift, /*nb_lshift*/ (binaryfunc)int_rshift, /*nb_rshift*/ (binaryfunc)int_and, /*nb_and*/ (binaryfunc)int_xor, /*nb_xor*/ (binaryfunc)int_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_coerce*/ (unaryfunc)int_int, /*nb_int*/ (unaryfunc)int_long, /*nb_long*/ (unaryfunc)int_float, /*nb_float*/ Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Tue Nov 28 20:15:13 2006 @@ -2886,7 +2886,7 @@ } static int -long_nonzero(PyLongObject *v) +long_bool(PyLongObject *v) { return ABS(v->ob_size) != 0; } @@ -3307,7 +3307,7 @@ (unaryfunc) long_neg, /*nb_negative*/ (unaryfunc) long_pos, /*tp_positive*/ (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_nonzero, /*tp_nonzero*/ + (inquiry) long_bool, /*tp_bool*/ (unaryfunc) long_invert, /*nb_invert*/ long_lshift, /*nb_lshift*/ (binaryfunc) long_rshift, /*nb_rshift*/ Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Tue Nov 28 20:15:13 2006 @@ -1246,8 +1246,8 @@ if (v == Py_None) return 0; else if (v->ob_type->tp_as_number != NULL && - v->ob_type->tp_as_number->nb_nonzero != NULL) - res = (*v->ob_type->tp_as_number->nb_nonzero)(v); + v->ob_type->tp_as_number->nb_bool != NULL) + res = (*v->ob_type->tp_as_number->nb_bool)(v); else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Tue Nov 28 20:15:13 2006 @@ -1784,7 +1784,7 @@ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ + 0, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ @@ -1894,7 +1894,7 @@ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ - 0, /*nb_nonzero*/ + 0, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Tue Nov 28 20:15:13 2006 @@ -2928,7 +2928,7 @@ COPYNUM(nb_negative); COPYNUM(nb_positive); COPYNUM(nb_absolute); - COPYNUM(nb_nonzero); + COPYNUM(nb_bool); COPYNUM(nb_invert); COPYNUM(nb_lshift); COPYNUM(nb_rshift); @@ -4206,32 +4206,39 @@ SLOT0(slot_nb_absolute, "__abs__") static int -slot_nb_nonzero(PyObject *self) +slot_nb_bool(PyObject *self) { PyObject *func, *args; - static PyObject *nonzero_str, *len_str; + static PyObject *bool_str, *len_str; int result = -1; + int from_len = 0; - func = lookup_maybe(self, "__nonzero__", &nonzero_str); + func = lookup_maybe(self, "__bool__", &bool_str); if (func == NULL) { if (PyErr_Occurred()) return -1; func = lookup_maybe(self, "__len__", &len_str); if (func == NULL) return PyErr_Occurred() ? -1 : 1; + from_len = 1; } args = PyTuple_New(0); if (args != NULL) { PyObject *temp = PyObject_Call(func, args, NULL); Py_DECREF(args); if (temp != NULL) { - if (PyInt_CheckExact(temp) || PyBool_Check(temp)) + if (from_len) { + /* enforced by slot_nb_len */ result = PyObject_IsTrue(temp); + } + else if (PyBool_Check(temp)) { + result = PyObject_IsTrue(temp); + } else { PyErr_Format(PyExc_TypeError, - "__nonzero__ should return " - "bool or int, returned %s", - temp->ob_type->tp_name); + "__bool__ should return " + "bool, returned %s", + temp->ob_type->tp_name); result = -1; } Py_DECREF(temp); @@ -4887,7 +4894,7 @@ UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, "abs(x)"), - UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred, + UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, "x != 0"), UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), Modified: python/branches/p3yk/Objects/weakrefobject.c ============================================================================== --- python/branches/p3yk/Objects/weakrefobject.c (original) +++ python/branches/p3yk/Objects/weakrefobject.c Tue Nov 28 20:15:13 2006 @@ -499,7 +499,7 @@ WRAP_BINARY(proxy_ior, PyNumber_InPlaceOr) static int -proxy_nonzero(PyWeakReference *proxy) +proxy_bool(PyWeakReference *proxy) { PyObject *o = PyWeakref_GET_OBJECT(proxy); if (!proxy_checkref(proxy)) @@ -596,7 +596,7 @@ proxy_neg, /*nb_negative*/ proxy_pos, /*nb_positive*/ proxy_abs, /*nb_absolute*/ - (inquiry)proxy_nonzero, /*nb_nonzero*/ + (inquiry)proxy_bool, /*nb_bool*/ proxy_invert, /*nb_invert*/ proxy_lshift, /*nb_lshift*/ proxy_rshift, /*nb_rshift*/ Modified: python/branches/p3yk/PC/_winreg.c ============================================================================== --- python/branches/p3yk/PC/_winreg.c (original) +++ python/branches/p3yk/PC/_winreg.c Tue Nov 28 20:15:13 2006 @@ -305,7 +305,7 @@ "handle - The integer Win32 handle.\n" "\n" "Operations:\n" -"__nonzero__ - Handles with an open object return true, otherwise false.\n" +"__bool__ - Handles with an open object return true, otherwise false.\n" "__int__ - Converting a handle to an integer returns the Win32 handle.\n" "__cmp__ - Handle objects are compared using the handle value."); @@ -375,7 +375,7 @@ } static int -PyHKEY_nonzeroFunc(PyObject *ob) +PyHKEY_boolFunc(PyObject *ob) { return ((PyHKEYObject *)ob)->hkey != 0; } @@ -437,7 +437,7 @@ PyHKEY_unaryFailureFunc, /* nb_negative */ PyHKEY_unaryFailureFunc, /* nb_positive */ PyHKEY_unaryFailureFunc, /* nb_absolute */ - PyHKEY_nonzeroFunc, /* nb_nonzero */ + PyHKEY_boolFunc, /* nb_bool */ PyHKEY_unaryFailureFunc, /* nb_invert */ PyHKEY_binaryFailureFunc, /* nb_lshift */ PyHKEY_binaryFailureFunc, /* nb_rshift */ From nnorwitz at gmail.com Tue Nov 28 23:05:53 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Tue, 28 Nov 2006 14:05:53 -0800 Subject: [Python-3000-checkins] r52853 - in python/branches/p3yk: Demo/classes/Complex.py Demo/classes/Rat.py Doc/lib/liboperator.tex Doc/lib/libstdtypes.tex Doc/lib/libtimeit.tex Doc/lib/libwinreg.tex Doc/lib/libxmlrpclib.tex Doc/ref/ref3.tex Include/obj Message-ID: On 11/28/06, jack.diederich wrote: > > Modified: python/branches/p3yk/Lib/decimal.py > ============================================================================== > --- python/branches/p3yk/Lib/decimal.py (original) > +++ python/branches/p3yk/Lib/decimal.py Tue Nov 28 20:15:13 2006 > @@ -633,14 +633,14 @@ > return other > return 0 > > - def __nonzero__(self): > + def __bool__(self): > """Is the number non-zero? > > 0 if self == 0 > 1 if self != 0 > """ > if self._is_special: > - return 1 > + return True > return sum(self._int) != 0 Should also update the docstring. Otherwise, looks good. Thanks! n From python-3000-checkins at python.org Tue Nov 28 23:22:35 2006 From: python-3000-checkins at python.org (jack.diederich) Date: Tue, 28 Nov 2006 23:22:35 +0100 (CET) Subject: [Python-3000-checkins] r52857 - python/branches/p3yk/Lib/decimal.py Message-ID: <20061128222235.4363D1E4002@bag.python.org> Author: jack.diederich Date: Tue Nov 28 23:22:22 2006 New Revision: 52857 Modified: python/branches/p3yk/Lib/decimal.py Log: updated docstring on __bool__ to match behavior Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Tue Nov 28 23:22:22 2006 @@ -634,10 +634,10 @@ return 0 def __bool__(self): - """Is the number non-zero? + """return True if the number is non-zero. - 0 if self == 0 - 1 if self != 0 + False if self == 0 + True if self != 0 """ if self._is_special: return True From python-3000-checkins at python.org Thu Nov 30 21:50:24 2006 From: python-3000-checkins at python.org (jack.diederich) Date: Thu, 30 Nov 2006 21:50:24 +0100 (CET) Subject: [Python-3000-checkins] r52875 - python/branches/p3yk/Misc/cheatsheet Message-ID: <20061130205024.470CC1E400E@bag.python.org> Author: jack.diederich Date: Thu Nov 30 21:50:23 2006 New Revision: 52875 Modified: python/branches/p3yk/Misc/cheatsheet Log: replace references to __nonzero__ with __bool__ Modified: python/branches/p3yk/Misc/cheatsheet ============================================================================== --- python/branches/p3yk/Misc/cheatsheet (original) +++ python/branches/p3yk/Misc/cheatsheet Thu Nov 30 21:50:23 2006 @@ -269,7 +269,7 @@ Notes : Truth testing behavior can be overridden for a given class by defining -special method __nonzero__. +special method __bool__. (1) Evaluate second arg only if necessary to determine outcome. None @@ -1143,7 +1143,7 @@ __cmp__(s, o) Compares s to o and returns <0, 0, or >0. Implements >, <, == etc... __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops - __nonzero__(s) Returns False or True for truth value testing + __bool__(s) Returns False or True for truth value testing __getattr__(s, name) called when attr lookup doesn't find __setattr__(s, name, val) called when setting an attr (inside, don't use "self.name = value" @@ -1167,7 +1167,7 @@ s&o = __and__(s,o) s^o = __xor__(s,o) s|o = __or__(s,o) s<>o = __rshift__(s,o) - nonzero(s) = __nonzero__(s) (used in boolean testing) + bool(s) = __bool__(s) (used in boolean testing) -s = __neg__(s) +s = __pos__(s) abs(s) = __abs__(s) ~s = __invert__(s) (bitwise) s+=o = __iadd__(s,o) s-=o = __isub__(s,o) From python-3000-checkins at python.org Thu Nov 30 23:13:52 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 30 Nov 2006 23:13:52 +0100 (CET) Subject: [Python-3000-checkins] r52877 - python/branches/p3yk/Python/bltinmodule.c Message-ID: <20061130221352.ECDFF1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Nov 30 23:13:52 2006 New Revision: 52877 Modified: python/branches/p3yk/Python/bltinmodule.c Log: Add built-in Print() function. This is PEP 3105 except for the name; I'll rename it to print() later. Now I can start working on the refactoring tool for print -> Print(). Also, sep and end should be required to be strings (or Unicode?). Someone please volunteer. Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Thu Nov 30 23:13:52 2006 @@ -1413,6 +1413,60 @@ +static PyObject * +builtin_print(PyObject *self, PyObject *args, PyObject *kwds) +{ + static char *kwlist[] = {"sep", "end", "file", 0}; + PyObject *dummy_args = PyTuple_New(0); + PyObject *sep = NULL, *end = NULL, *file = NULL; + int i, err; + + if (dummy_args == NULL) + return NULL; + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:Print", + kwlist, &sep, &end, &file)) + return NULL; + if (file == NULL || file == Py_None) + file = PySys_GetObject("stdout"); + + /* XXX Verify that sep and end are None, NULL or strings. */ + + for (i = 0; i < PyTuple_Size(args); i++) { + if (i > 0) { + if (sep == NULL || sep == Py_None) + err = PyFile_WriteString(" ", file); + else + err = PyFile_WriteObject(sep, file, + Py_PRINT_RAW); + if (err) + return NULL; + } + err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, + Py_PRINT_RAW); + if (err) + return NULL; + } + + if (end == NULL || end == Py_None) + err = PyFile_WriteString("\n", file); + else + err = PyFile_WriteObject(end, file, Py_PRINT_RAW); + if (err) + return NULL; + + Py_RETURN_NONE; +} + +PyDoc_STRVAR(print_doc, +"Print(value, ..., file=None, sep=' ', end='\\n')\n\ +\n\ +Prints the values to a stream, or to sys.stdout by default.\n\ +Optional keyword arguments:\n\ +file: a file-like object (stream); defaults to the current sys.stdout.\n\ +sep: string inserted between values, default a space.\n\ +end: string appended after the last value, default a newline."); + + /* Return number of items in range (lo, hi, step), when arguments are * PyInt or PyLong objects. step > 0 required. Return a value < 0 if * & only if the true value is too large to fit in a signed long. @@ -2014,6 +2068,7 @@ {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc}, {"ord", builtin_ord, METH_O, ord_doc}, {"pow", builtin_pow, METH_VARARGS, pow_doc}, + {"Print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, {"range", builtin_range, METH_VARARGS, range_doc}, {"reload", builtin_reload, METH_O, reload_doc}, {"repr", builtin_repr, METH_O, repr_doc}, From python-3000-checkins at python.org Thu Nov 30 23:46:03 2006 From: python-3000-checkins at python.org (georg.brandl) Date: Thu, 30 Nov 2006 23:46:03 +0100 (CET) Subject: [Python-3000-checkins] r52878 - python/branches/p3yk/Python/bltinmodule.c Message-ID: <20061130224603.C8D441E4005@bag.python.org> Author: georg.brandl Date: Thu Nov 30 23:46:03 2006 New Revision: 52878 Modified: python/branches/p3yk/Python/bltinmodule.c Log: Check "sep" and "end" for stringness in Print(). Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Thu Nov 30 23:46:03 2006 @@ -1429,7 +1429,20 @@ if (file == NULL || file == Py_None) file = PySys_GetObject("stdout"); - /* XXX Verify that sep and end are None, NULL or strings. */ + if (sep && sep != Py_None && !PyString_Check(sep) && + !PyUnicode_Check(sep)) { + PyErr_Format(PyExc_TypeError, + "sep must be None, str or unicode, not %.200s", + sep->ob_type->tp_name); + return NULL; + } + if (end && end != Py_None && !PyString_Check(end) && + !PyUnicode_Check(end)) { + PyErr_Format(PyExc_TypeError, + "end must be None, str or unicode, not %.200s", + end->ob_type->tp_name); + return NULL; + } for (i = 0; i < PyTuple_Size(args); i++) { if (i > 0) {