From rhettinger@users.sourceforge.net Sat Feb 1 00:10:12 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:12 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25990/Modules Added Files: itertoolsmodule.c Log Message: Move itertools module from the sandbox and into production. --- NEW FILE: itertoolsmodule.c --- #include "Python.h" /* Itertools module written and maintained by Raymond D. Hettinger Copyright (c) 2003 Python Software Foundation. All rights reserved. */ /* dropwhile object **********************************************************/ typedef struct { PyObject_HEAD PyObject *func; PyObject *it; long start; } dropwhileobject; PyTypeObject dropwhile_type; [...1493 lines suppressed...] if (PyType_Ready(&ifilter_type) < 0) return; Py_INCREF(&ifilter_type); PyModule_AddObject(m, "ifilter", (PyObject *)&ifilter_type); if (PyType_Ready(&count_type) < 0) return; Py_INCREF(&count_type); PyModule_AddObject(m, "count", (PyObject *)&count_type); if (PyType_Ready(&izip_type) < 0) return; Py_INCREF(&izip_type); PyModule_AddObject(m, "izip", (PyObject *)&izip_type); if (PyType_Ready(&repeat_type) < 0) return; Py_INCREF(&repeat_type); PyModule_AddObject(m, "repeat", (PyObject *)&repeat_type); } From rhettinger@users.sourceforge.net Sat Feb 1 00:10:12 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:12 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.633,1.634 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv25990/Misc Modified Files: NEWS Log Message: Move itertools module from the sandbox and into production. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.633 retrieving revision 1.634 diff -C2 -d -r1.633 -r1.634 *** NEWS 31 Jan 2003 22:27:15 -0000 1.633 --- NEWS 1 Feb 2003 00:10:09 -0000 1.634 *************** *** 31,34 **** --- 31,37 ---- ----------------- + - Added an itertools module containing high speed, memory efficient + looping constructs inspired by tools from Haskell and SML. + - The SSL module now handles sockets with a timeout set correctly (SF patch #675750, fixing SF bug #675552). From rhettinger@users.sourceforge.net Sat Feb 1 00:10:13 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:13 -0800 Subject: [Python-checkins] python/dist/src/PC config.c,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/PC In directory sc8-pr-cvs1:/tmp/cvs-serv25990/PC Modified Files: config.c Log Message: Move itertools module from the sandbox and into production. Index: config.c =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/config.c,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** config.c 30 Dec 2002 22:08:04 -0000 1.37 --- config.c 1 Feb 2003 00:10:10 -0000 1.38 *************** *** 46,49 **** --- 46,50 ---- extern void initzipimport(void); extern void init_random(void); + extern void inititertools(void); /* XXX tim: what's the purpose of ADDMODULE MARKER? */ *************** *** 98,101 **** --- 99,103 ---- {"_hotshot", init_hotshot}, {"_random", init_random}, + {"itertools", inititertools}, {"xxsubtype", initxxsubtype}, From rhettinger@users.sourceforge.net Sat Feb 1 00:10:11 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:11 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,NONE,1.1 lib.tex,1.213,1.214 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv25990/Doc/lib Modified Files: lib.tex Added Files: libitertools.tex Log Message: Move itertools module from the sandbox and into production. --- NEW FILE: libitertools.tex --- \section{\module{itertools} --- Functions creating iterators for efficient looping} \declaremodule{standard}{itertools} \modulesynopsis{Functions creating iterators for efficient looping.} \moduleauthor{Raymond Hettinger}{python@rcn.com} \sectionauthor{Raymond Hettinger}{python@rcn.com} \versionadded{2.3} This module implements a number of iterator building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python. With the advent of iterators and generators in Python 2.3, each of these tools can be expressed easily and succinctly in pure python. Rather duplicating what can already be done, this module emphasizes providing value in other ways: \begin{itemize} \item Instead of constructing an over-specialized toolset, this module provides basic building blocks that can be readily combined. For instance, SML provides a tabulation tool: \code{tabulate(\var{f})} which produces a sequence \code{f(0), f(1), ...}. This toolbox takes a different approach of providing \function{imap()} and \function{count()} which can be combined to form \code{imap(\var{f}, count())} and produce an equivalent result. \item Some tools were dropped because they offer no advantage over their pure python counterparts or because their behavior was too surprising. For instance, SML provides a tool: \code{cycle(\var{seq})} which loops over the sequence elements and then starts again when the sequence is exhausted. The surprising behavior is the need for significant auxiliary storage (unusual for iterators). Also, it is trivially implemented in python with almost no performance penalty. \item Another source of value comes from standardizing a core set of tools to avoid the readability and reliability problems that arise when many different individuals create their own slightly varying implementations each with their own quirks and naming conventions. \item Whether cast in pure python form or C code, tools that use iterators are more memory efficient (and faster) than their list based counterparts. Adopting the principles of just-in-time manufacturing, they create data when and where needed instead of consuming memory with the computer equivalent of ``inventory''. \end{itemize} \begin{seealso} \seetext{The Standard ML Basis Library, \citetitle[http://www.standardml.org/Basis/] {The Standard ML Basis Library}.} \seetext{Haskell, A Purely Functional Language, \citetitle[http://www.haskell.org/definition/] {Definition of Haskell and the Standard Libraries}.} \end{seealso} \subsection{Itertool functions \label{itertools-functions}} The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream. \begin{funcdesc}{count}{\optional{n}} Make an iterator that returns consecutive integers starting with \var{n}. Does not currently support python long integers. Often used as an argument to \function{imap()} to generate consecutive data points. Also, used in \function{izip()} to add sequence numbers. Equivalent to: \begin{verbatim} def count(n=0): cnt = n while True: yield cnt cnt += 1 \end{verbatim} \end{funcdesc} \begin{funcdesc}{dropwhile}{predicate, iterable} Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce \emph{any} output until the predicate is true, so it may have a lengthy start-up time. Equivalent to: \begin{verbatim} def dropwhile(predicate, iterable): iterable = iter(iterable) while True: x = iterable.next() if predicate(x): continue # drop when predicate is true yield x break while True: yield iterable.next() \end{verbatim} \end{funcdesc} \begin{funcdesc}{ifilter}{predicate, iterable \optional{, invert}} Make an iterator that filters elements from iterable returning only those for which the predicate is \code{True}. If \var{invert} is \code{True}, then reverse the process and pass through only those elements for which the predicate is \code{False}. If \var{predicate} is \code{None}, return the items that are true (or false if \var{invert} has been set). Equivalent to: \begin{verbatim} def ifilter(predicate, iterable, invert=False): iterable = iter(iterable) while True: x = iterable.next() if predicate is None: b = bool(x) else: b = bool(predicate(x)) if not invert and b or invert and not b: yield x \end{verbatim} \end{funcdesc} \begin{funcdesc}{imap}{function, *iterables} Make an iterator that computes the function using arguments from each of the iterables. If \var{function} is set to \code{None}, then \function{imap()} returns the arguments as a tuple. Like \function{map()} but stops when the shortest iterable is exhausted instead of filling in \code{None} for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for \function{map()} (because the output is fully evaluated) but represent a common and useful way of supplying arguments to \function{imap()}. Equivalent to: \begin{verbatim} def imap(function, *iterables): iterables = map(iter, iterables) while True: args = [i.next() for i in iterables] if function is None: yield tuple(args) else: yield function(*args) \end{verbatim} \end{funcdesc} \begin{funcdesc}{islice}{iterable, \optional{start,} stop \optional{, step}} Make an iterator that returns selected elements from the iterable. If \var{start} is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless \var{step} is set higher than one which results in items being skipped. If \var{stop} is specified, then iteration stops at the specified element position; otherwise, it continues indefinitely or until the iterable is exhausted. Unlike regular slicing, \function{islice()} does not support negative values for \var{start}, \var{stop}, or \var{step}. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Equivalent to: \begin{verbatim} def islice(iterable, *args): iterable = iter(iterable) s = slice(*args) next = s.start or 0 stop = s.stop step = s.step or 1 cnt = 0 while True: while cnt < next: dummy = iterable.next() cnt += 1 if cnt >= stop: break yield iterable.next() cnt += 1 next += step \end{verbatim} \end{funcdesc} \begin{funcdesc}{izip}{*iterables} Make an iterator that aggregates elements from each of the iterables. Like \function{zip()} except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to: \begin{verbatim} def izip(*iterables): iterables = map(iter, iterables) while True: result = [i.next() for i in iterables] yield tuple(result) \end{verbatim} \end{funcdesc} \begin{funcdesc}{repeat}{obj} Make an iterator that returns \var{obj} over and over again. Used as argument to \function{imap()} for invariant parameters to the called function. Also used with function{izip()} to create an invariant part of a tuple record. Equivalent to: \begin{verbatim} def repeat(x): while True: yield x \end{verbatim} \end{funcdesc} \begin{funcdesc}{starmap}{function, iterable} Make an iterator that computes the function using arguments tuples obtained from the iterable. Used instead of \function{imap()} when argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between \function{imap()} and \function{starmap} parallels the distinction between \code{function(a,b)} and \code{function(*c)}. Equivalent to: \begin{verbatim} def starmap(function, iterable): iterable = iter(iterable) while True: yield function(*iterable.next()) \end{verbatim} \end{funcdesc} \begin{funcdesc}{takewhile}{predicate, iterable} Make an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to: \begin{verbatim} def takewhile(predicate, iterable): iterable = iter(iterable) while True: x = iterable.next() if predicate(x): yield x else: break \end{verbatim} \end{funcdesc} \begin{funcdesc}{times}{n, \optional{object}} Make an iterator that returns \var{object} \var{n} times. \var{object} defaults to \code{None}. Used for looping a specific number of times without creating a number object on each pass. Equivalent to: \begin{verbatim} def times(n, object=None): if n<0 : raise ValueError for i in xrange(n): yield object \end{verbatim} \end{funcdesc} \subsection{Examples \label{itertools-example}} The following examples show common uses for each tool and demonstrate ways they can be combined. \begin{verbatim} >>> for i in times(3): ... print "Hello" ... Hello Hello Hello >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): ... print 'Check %d is for $%.2f' % (checknum, amount) ... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): ... print cube ... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, len(reportlines), 2): ... print name.title() ... Alex Laura Martin Walter Samuele \end{verbatim} This section has further examples of how itertools can be combined. Note that \function{enumerate()} and \method{iteritems()} already have highly efficient implementations in Python. They are only included here to illustrate how higher level tools can be created from building blocks. \begin{verbatim} >>> def enumerate(iterable): ... return izip(count(), iterable) >>> def tabulate(function): ... "Return function(0), function(1), ..." ... return imap(function, count()) >>> def iteritems(mapping): ... return izip(mapping.iterkeys(), mapping.itervalues()) >>> def nth(iterable, n): ... "Returns the nth item" ... return islice(iterable, n, n+1).next() \end{verbatim} Index: lib.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/lib.tex,v retrieving revision 1.213 retrieving revision 1.214 diff -C2 -d -r1.213 -r1.214 *** lib.tex 7 Jan 2003 22:36:04 -0000 1.213 --- lib.tex 1 Feb 2003 00:10:09 -0000 1.214 *************** *** 126,129 **** --- 126,130 ---- \input{libarray} \input{libsets} + \input{libitertools} \input{libcfgparser} \input{libfileinput} From rhettinger@users.sourceforge.net Sat Feb 1 00:10:11 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:11 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_itertools.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25990/Lib/test Added Files: test_itertools.py Log Message: Move itertools module from the sandbox and into production. --- NEW FILE: test_itertools.py --- import unittest from test import test_support from itertools import * class TestBasicOps(unittest.TestCase): def test_count(self): self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) self.assertRaises(TypeError, count, 2, 3) def test_ifilter(self): def isEven(x): return x%2==0 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4]) self.assertEqual(list(ifilter(isEven, range(6), True)), [1,3,5]) self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2]) self.assertRaises(TypeError, ifilter) self.assertRaises(TypeError, ifilter, 3) self.assertRaises(TypeError, ifilter, isEven, 3) self.assertRaises(TypeError, ifilter, isEven, [3], True, 4) def test_izip(self): ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertRaises(TypeError, izip) def test_repeat(self): self.assertEqual(zip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) self.assertRaises(TypeError, repeat) def test_times(self): self.assertEqual(list(times(3)), [None]*3) self.assertEqual(list(times(3, True)), [True]*3) self.assertRaises(ValueError, times, -1) def test_imap(self): import operator self.assertEqual(list(imap(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(imap(None, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertRaises(TypeError, imap) self.assertRaises(TypeError, imap, operator.neg) def test_starmap(self): import operator self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args)) for args, tgtargs in [ # Stop when seqn is exhausted ((10, 110, 3), ((10, 100, 3))), ((10, 110), ((10, 100))), ((110,), (100,)) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs)) self.assertRaises(TypeError, islice, xrange(10)) self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4) self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1) self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8]) libreftest = """ Doctest for examples in the library reference, libitertools.tex >>> for i in times(3): ... print "Hello" ... Hello Hello Hello >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): ... print 'Check %d is for $%.2f' % (checknum, amount) ... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> import operator >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): ... print cube ... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, len(reportlines), 2): ... print name.title() ... Alex Laura Martin Walter Samuele >>> def enumerate(iterable): ... return izip(count(), iterable) >>> def tabulate(function): ... "Return function(0), function(1), ..." ... return imap(function, count()) >>> def iteritems(mapping): ... return izip(mapping.iterkeys(), mapping.itervalues()) >>> def nth(iterable, n): ... "Returns the nth item" ... return islice(iterable, n, n+1).next() """ __test__ = {'libreftest' : libreftest} def test_main(verbose=None): import test_itertools suite = unittest.TestSuite() for testclass in (TestBasicOps, ): suite.addTest(unittest.makeSuite(testclass)) test_support.run_suite(suite) test_support.run_doctest(test_itertools, verbose) # verify reference counting import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [] for i in xrange(5): test_support.run_suite(suite) counts.append(sys.gettotalrefcount()) print counts if __name__ == "__main__": test_main(verbose=True) From rhettinger@users.sourceforge.net Sat Feb 1 00:10:13 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:13 -0800 Subject: [Python-checkins] python/dist/src/PCbuild pythoncore.dsp,1.41,1.42 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv25990/PCbuild Modified Files: pythoncore.dsp Log Message: Move itertools module from the sandbox and into production. Index: pythoncore.dsp =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/pythoncore.dsp,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** pythoncore.dsp 31 Dec 2002 02:09:08 -0000 1.41 --- pythoncore.dsp 1 Feb 2003 00:10:11 -0000 1.42 *************** *** 324,327 **** --- 324,331 ---- # Begin Source File + SOURCE=..\Modules\itertoolsmodule.c + # End Source File + # Begin Source File + SOURCE=..\Parser\listnode.c # End Source File From rhettinger@users.sourceforge.net Sat Feb 1 00:10:41 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 16:10:41 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.139,1.140 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv25990 Modified Files: setup.py Log Message: Move itertools module from the sandbox and into production. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.139 retrieving revision 1.140 diff -C2 -d -r1.139 -r1.140 *** setup.py 29 Jan 2003 03:49:42 -0000 1.139 --- setup.py 1 Feb 2003 00:10:09 -0000 1.140 *************** *** 325,328 **** --- 325,330 ---- # random number generator implemented in C exts.append( Extension("_random", ["_randommodule.c"]) ) + # fast iterator tools implemented in C + exts.append( Extension("itertools", ["itertoolsmodule.c"]) ) # operator.add() and similar goodies exts.append( Extension('operator', ['operator.c']) ) From tim_one@users.sourceforge.net Sat Feb 1 01:47:31 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 17:47:31 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.51,1.52 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv5895/Modules Modified Files: datetimemodule.c Log Message: delta_setstate(): This waS no longer referenced, so nukeit. delta_reduce(): Simplified. Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** datetimemodule.c 31 Jan 2003 22:27:17 -0000 1.51 --- datetimemodule.c 1 Feb 2003 01:47:29 -0000 1.52 *************** *** 1948,1954 **** } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. */ static PyObject * --- 1948,1952 ---- } ! /* Pickle support. This is a plain application of __reduce__. */ static PyObject * *************** *** 1960,2001 **** } - /* __setstate__ isn't exposed. */ - static PyObject * - delta_setstate(PyDateTime_Delta *self, PyObject *state) - { - int day; - int second; - int us; - - if (!PyArg_ParseTuple(state, "iii:__setstate__", &day, &second, &us)) - return NULL; - - self->hashcode = -1; - SET_TD_DAYS(self, day); - SET_TD_SECONDS(self, second); - SET_TD_MICROSECONDS(self, us); - - Py_INCREF(Py_None); - return Py_None; - } - static PyObject * delta_reduce(PyDateTime_Delta* self) { ! PyObject* result = NULL; ! PyObject* state = delta_getstate(self); ! ! if (state != NULL) { ! /* The funky "()" in the format string creates an empty ! * tuple as the 2nd component of the result 3-tuple. ! */ ! result = Py_BuildValue("O(iii)", ! self->ob_type, ! self->days, ! self->seconds, ! self->microseconds); ! Py_DECREF(state); ! } ! return result; } --- 1958,1965 ---- } static PyObject * delta_reduce(PyDateTime_Delta* self) { ! return Py_BuildValue("ON", self->ob_type, delta_getstate(self)); } From tim_one@users.sourceforge.net Sat Feb 1 01:52:52 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 17:52:52 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.52,1.53 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7601/Modules Modified Files: datetimemodule.c Log Message: All over: changed comments to reflect pickling is straightforward now, not the maze it was. Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** datetimemodule.c 1 Feb 2003 01:47:29 -0000 1.52 --- datetimemodule.c 1 Feb 2003 01:52:50 -0000 1.53 *************** *** 1948,1953 **** } ! /* Pickle support. This is a plain application of __reduce__. ! */ static PyObject * delta_getstate(PyDateTime_Delta *self) --- 1948,1953 ---- } ! /* Pickle support, a simple use of __reduce__. */ ! static PyObject * delta_getstate(PyDateTime_Delta *self) *************** *** 2524,2528 **** } ! /* Pickle support. Quite a maze! */ static PyObject * --- 2524,2528 ---- } ! /* Pickle support, a simple use of __reduce__. */ static PyObject * *************** *** 3336,3342 **** } ! /* ! * Pickle support. Quite a maze! ! */ /* Let basestate be the non-tzinfo data string. --- 3336,3340 ---- } ! /* Pickle support, a simple use of __reduce__. */ /* Let basestate be the non-tzinfo data string. *************** *** 4338,4342 **** } ! /* Pickle support. Quite a maze! */ /* Let basestate be the non-tzinfo data string. --- 4336,4340 ---- } ! /* Pickle support, a simple use of __reduce__. */ /* Let basestate be the non-tzinfo data string. From tim_one@users.sourceforge.net Sat Feb 1 02:16:39 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:16:39 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv14164/Lib Modified Files: copy_reg.py Log Message: Removed all uses of the out-of-favor __safe_for_unpickling__ magic attr, and copy_reg.safe_constructors. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** copy_reg.py 31 Jan 2003 20:34:07 -0000 1.12 --- copy_reg.py 1 Feb 2003 02:16:36 -0000 1.13 *************** *** 11,15 **** dispatch_table = {} - safe_constructors = {} def pickle(ob_type, pickle_function, constructor_ob=None): --- 11,14 ---- *************** *** 27,31 **** if not callable(object): raise TypeError("constructors must be callable") - safe_constructors[object] = 1 # Example: provide pickling support for complex numbers. --- 26,29 ---- *************** *** 42,46 **** base.__init__(obj, state) return obj - _reconstructor.__safe_for_unpickling__ = 1 _HEAPTYPE = 1<<9 --- 40,43 ---- From tim_one@users.sourceforge.net Sat Feb 1 02:16:39 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:16:39 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.30,1.31 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv14164/Lib/test Modified Files: pickletester.py Log Message: Removed all uses of the out-of-favor __safe_for_unpickling__ magic attr, and copy_reg.safe_constructors. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** pickletester.py 29 Jan 2003 17:58:44 -0000 1.30 --- pickletester.py 1 Feb 2003 02:16:36 -0000 1.31 *************** *** 16,21 **** class initarg(C): - __safe_for_unpickling__ = 1 - def __init__(self, a, b): self.a = a --- 16,19 ---- From tim_one@users.sourceforge.net Sat Feb 1 02:16:39 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:16:39 -0800 Subject: [Python-checkins] python/dist/src/Objects structseq.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv14164/Objects Modified Files: structseq.c Log Message: Removed all uses of the out-of-favor __safe_for_unpickling__ magic attr, and copy_reg.safe_constructors. Index: structseq.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/structseq.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** structseq.c 18 Dec 2002 23:20:39 -0000 1.11 --- structseq.c 1 Feb 2003 02:16:37 -0000 1.12 *************** *** 393,396 **** PyDict_SetItemString(dict, unnamed_fields_key, PyInt_FromLong((long) n_unnamed_members)); - PyDict_SetItemString(dict, "__safe_for_unpickling__", Py_True); } --- 393,395 ---- From tim_one@users.sourceforge.net Sat Feb 1 02:16:39 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:16:39 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.100,2.101 datetimemodule.c,1.53,1.54 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv14164/Modules Modified Files: cPickle.c datetimemodule.c Log Message: Removed all uses of the out-of-favor __safe_for_unpickling__ magic attr, and copy_reg.safe_constructors. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.100 retrieving revision 2.101 diff -C2 -d -r2.100 -r2.101 *** cPickle.c 31 Jan 2003 21:10:31 -0000 2.100 --- cPickle.c 1 Feb 2003 02:16:37 -0000 2.101 *************** *** 93,104 **** static PyObject *dispatch_table; - static PyObject *safe_constructors; static PyObject *empty_tuple; static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, ! *write_str, *__safe_for_unpickling___str, *append_str, *read_str, *readline_str, *__main___str, *__basicnew___str, ! *copy_reg_str, *dispatch_table_str, *safe_constructors_str; /************************************************************************* --- 93,103 ---- static PyObject *dispatch_table; static PyObject *empty_tuple; static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, ! *write_str, *append_str, *read_str, *readline_str, *__main___str, *__basicnew___str, ! *copy_reg_str, *dispatch_table_str; /************************************************************************* *************** *** 307,311 **** int buf_size; char *buf; - PyObject *safe_constructors; PyObject *find_class; } Unpicklerobject; --- 306,309 ---- *************** *** 3079,3084 **** Instance_New(PyObject *cls, PyObject *args) { ! int has_key; ! PyObject *safe=0, *r=0; if (PyClass_Check(cls)) { --- 3077,3081 ---- Instance_New(PyObject *cls, PyObject *args) { ! PyObject *r = 0; if (PyClass_Check(cls)) { *************** *** 3108,3126 **** } - /* Is safe_constructors always a dict? */ - has_key = cPickle_PyMapping_HasKey(safe_constructors, cls); - if (!has_key) { - safe = PyObject_GetAttr(cls, __safe_for_unpickling___str); - if (!safe || - !PyObject_IsTrue(safe)) { - cPickle_ErrFormat(UnpicklingError, - "%s is not safe for unpickling", - "O", cls); - Py_XDECREF(safe); - return NULL; - } - Py_DECREF(safe); - } - if (args==Py_None) { /* Special case, call cls.__basicnew__() */ --- 3105,3108 ---- *************** *** 4333,4337 **** self->read = NULL; self->readline = NULL; - self->safe_constructors = NULL; self->find_class = NULL; --- 4315,4318 ---- *************** *** 4374,4392 **** } - if (PyEval_GetRestricted()) { - /* Restricted execution, get private tables */ - PyObject *m; - - if (!( m=PyImport_Import(copy_reg_str))) goto err; - self->safe_constructors=PyObject_GetAttr(m, - safe_constructors_str); - Py_DECREF(m); - if (!( self->safe_constructors )) goto err; - } - else { - self->safe_constructors=safe_constructors; - Py_INCREF(safe_constructors); - } - return self; --- 4355,4358 ---- *************** *** 4419,4423 **** Py_XDECREF(self->arg); Py_XDECREF(self->last_string); - Py_XDECREF(self->safe_constructors); if (self->marks) { --- 4385,4388 ---- *************** *** 4694,4698 **** INIT_STR(__reduce__); INIT_STR(write); - INIT_STR(__safe_for_unpickling__); INIT_STR(append); INIT_STR(read); --- 4659,4662 ---- *************** *** 4700,4704 **** INIT_STR(copy_reg); INIT_STR(dispatch_table); - INIT_STR(safe_constructors); INIT_STR(__basicnew__); --- 4664,4667 ---- *************** *** 4706,4717 **** return -1; ! /* These next few are special because we want to use different ! ones in restricted mode. */ dispatch_table = PyObject_GetAttr(copy_reg, dispatch_table_str); if (!dispatch_table) - return -1; - - if (!( safe_constructors = PyObject_GetAttr(copy_reg, - safe_constructors_str))) return -1; --- 4669,4676 ---- return -1; ! /* This is special because we want to use a different ! one in restricted mode. */ dispatch_table = PyObject_GetAttr(copy_reg, dispatch_table_str); if (!dispatch_table) return -1; Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.53 retrieving revision 1.54 diff -C2 -d -r1.53 -r1.54 *** datetimemodule.c 1 Feb 2003 01:52:50 -0000 1.53 --- datetimemodule.c 1 Feb 2003 02:16:37 -0000 1.54 *************** *** 4517,4527 **** PyObject *x; - /* Types that use __reduce__ for pickling need to set the following - * magical attr in the type dict, with a true value. - */ - PyObject *safepickle = PyString_FromString("__safe_for_unpickling__"); - if (safepickle == NULL) - return; - m = Py_InitModule3("datetime", module_methods, "Fast implementation of the datetime type."); --- 4517,4520 ---- *************** *** 4578,4593 **** } - /* tzinfo values */ - d = PyDateTime_TZInfoType.tp_dict; - - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; - /* timedelta values */ d = PyDateTime_DeltaType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; - x = new_delta(0, 0, 1, 0); if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) --- 4571,4577 ---- *************** *** 4608,4614 **** d = PyDateTime_DateType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; - x = new_date(1, 1, 1); if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) --- 4592,4595 ---- *************** *** 4629,4635 **** d = PyDateTime_TimeType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; - x = new_time(0, 0, 0, 0, Py_None); if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) --- 4610,4613 ---- *************** *** 4650,4656 **** d = PyDateTime_DateTimeType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; - x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) --- 4628,4631 ---- *************** *** 4667,4672 **** return; Py_DECREF(x); - - Py_DECREF(safepickle); /* module initialization */ --- 4642,4645 ---- From rhettinger@users.sourceforge.net Sat Feb 1 02:33:48 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:33:48 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_itertools.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19431 Modified Files: test_itertools.py Log Message: Neaten ref count test. Index: test_itertools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_itertools.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_itertools.py 1 Feb 2003 00:10:09 -0000 1.1 --- test_itertools.py 1 Feb 2003 02:33:45 -0000 1.2 *************** *** 152,156 **** for i in xrange(5): test_support.run_suite(suite) ! counts.append(sys.gettotalrefcount()) print counts --- 152,156 ---- for i in xrange(5): test_support.run_suite(suite) ! counts.append(sys.gettotalrefcount()-i) print counts From tim_one@users.sourceforge.net Sat Feb 1 02:54:17 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:54:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23548/Lib/test Modified Files: test_datetime.py Log Message: There's no good reason for datetime objects to expose __getstate__() anymore either, so don't. This also allows to get rid of obscure code making __getnewargs__ identical to __getstate__ (hmm ... hope there wasn't more to this than I realize!). Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** test_datetime.py 31 Jan 2003 21:55:33 -0000 1.32 --- test_datetime.py 1 Feb 2003 02:54:14 -0000 1.33 *************** *** 279,284 **** args = 12, 34, 56 orig = timedelta(*args) - state = orig.__getstate__() - self.assertEqual(args, state) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 279,282 ---- *************** *** 833,838 **** args = 6, 7, 23 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17',), self.theclass) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 831,834 ---- *************** *** 1187,1192 **** args = 6, 7, 23, 20, 59, 1, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17\x14\x3b\x01\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1183,1186 ---- *************** *** 1568,1573 **** args = 20, 59, 16, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x14\x3b\x10\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1562,1565 ---- *************** *** 1878,1883 **** args = 20, 59, 16, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x14\x3b\x10\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1870,1873 ---- *************** *** 2081,2086 **** args = 6, 7, 23, 20, 59, 1, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17\x14\x3b\x01\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 2071,2074 ---- From tim_one@users.sourceforge.net Sat Feb 1 02:54:17 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:54:17 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.634,1.635 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23548/Misc Modified Files: NEWS Log Message: There's no good reason for datetime objects to expose __getstate__() anymore either, so don't. This also allows to get rid of obscure code making __getnewargs__ identical to __getstate__ (hmm ... hope there wasn't more to this than I realize!). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.634 retrieving revision 1.635 diff -C2 -d -r1.634 -r1.635 *** NEWS 1 Feb 2003 00:10:09 -0000 1.634 --- NEWS 1 Feb 2003 02:54:15 -0000 1.635 *************** *** 132,137 **** The pickle format of date, time and datetime objects has changed completely. The undocumented pickler and unpickler functions no ! longer exist. The undocumented __setstate__() methods no longer ! exist either. Library --- 132,137 ---- The pickle format of date, time and datetime objects has changed completely. The undocumented pickler and unpickler functions no ! longer exist. The undocumented __setstate__() and __getstate__() ! methods no longer exist either. Library From tim_one@users.sourceforge.net Sat Feb 1 02:54:18 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 18:54:18 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.54,1.55 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv23548/Modules Modified Files: datetimemodule.c Log Message: There's no good reason for datetime objects to expose __getstate__() anymore either, so don't. This also allows to get rid of obscure code making __getnewargs__ identical to __getstate__ (hmm ... hope there wasn't more to this than I realize!). Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** datetimemodule.c 1 Feb 2003 02:16:37 -0000 1.54 --- datetimemodule.c 1 Feb 2003 02:54:15 -0000 1.55 *************** *** 1950,1953 **** --- 1950,1954 ---- /* Pickle support, a simple use of __reduce__. */ + /* __getstate__ isn't exposed */ static PyObject * delta_getstate(PyDateTime_Delta *self) *************** *** 1980,1986 **** static PyMethodDef delta_methods[] = { - {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, - {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, PyDoc_STR("__reduce__() -> (cls, state)")}, --- 1981,1984 ---- *************** *** 2526,2529 **** --- 2524,2528 ---- /* Pickle support, a simple use of __reduce__. */ + /* __getstate__ isn't exposed */ static PyObject * date_getstate(PyDateTime_Date *self) *************** *** 2592,2598 **** PyDoc_STR("Return date with new specified fields.")}, - {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, - {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, PyDoc_STR("__reduce__() -> (cls, state)")}, --- 2591,2594 ---- *************** *** 3341,3344 **** --- 3337,3341 ---- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo). * So it's a tuple in any (non-error) case. + * __getstate__ isn't exposed. */ static PyObject * *************** *** 3387,3393 **** PyDoc_STR("Return time with new specified fields.")}, - {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, - {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, PyDoc_STR("__reduce__() -> (cls, state)")}, --- 3384,3387 ---- *************** *** 4341,4344 **** --- 4335,4339 ---- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo). * So it's a tuple in any (non-error) case. + * __getstate__ isn't exposed. */ static PyObject * *************** *** 4432,4438 **** PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, - {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, - {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, PyDoc_STR("__reduce__() -> (cls, state)")}, --- 4427,4430 ---- *************** *** 4530,4573 **** if (PyType_Ready(&PyDateTime_TZInfoType) < 0) return; - - /* Make __getnewargs__ a true alias for __getstate__ */ - { - PyObject *d, *f; - - d = PyDateTime_DateType.tp_dict; - f = PyDict_GetItemString(d, "__getstate__"); - if (f != NULL) { - if (PyDict_SetItemString(d, "__getnewargs__", f) < 0) - return; - } - - d = PyDateTime_DateTimeType.tp_dict; - f = PyDict_GetItemString(d, "__getstate__"); - if (f != NULL) { - if (PyDict_SetItemString(d, "__getnewargs__", f) < 0) - return; - } - - d = PyDateTime_DeltaType.tp_dict; - f = PyDict_GetItemString(d, "__getstate__"); - if (f != NULL) { - if (PyDict_SetItemString(d, "__getnewargs__", f) < 0) - return; - } - - d = PyDateTime_TimeType.tp_dict; - f = PyDict_GetItemString(d, "__getstate__"); - if (f != NULL) { - if (PyDict_SetItemString(d, "__getnewargs__", f) < 0) - return; - } - - d = PyDateTime_TZInfoType.tp_dict; - f = PyDict_GetItemString(d, "__getstate__"); - if (f != NULL) { - if (PyDict_SetItemString(d, "__getnewargs__", f) < 0) - return; - } - } /* timedelta values */ --- 4522,4525 ---- From tim_one@users.sourceforge.net Sat Feb 1 03:02:37 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 19:02:37 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.156,1.157 test_datetime.py,1.109,1.110 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25782 Modified Files: datetime.py test_datetime.py Log Message: __getstate__() isn't needed for pickling anymore, but is used for other things (like hashing and comparison), so make them private methods. This was done earlier for __setstate__() too. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.156 retrieving revision 1.157 diff -C2 -d -r1.156 -r1.157 *** datetime.py 31 Jan 2003 21:52:15 -0000 1.156 --- datetime.py 1 Feb 2003 03:02:33 -0000 1.157 *************** *** 601,608 **** raise TypeError, ("can't compare timedelta to %s instance" % type(other).__name__) ! return cmp(self.__getstate__(), other.__getstate__()) def __hash__(self): ! return hash(self.__getstate__()) def __nonzero__(self): --- 601,608 ---- raise TypeError, ("can't compare timedelta to %s instance" % type(other).__name__) ! return cmp(self.__getstate(), other.__getstate()) def __hash__(self): ! return hash(self.__getstate()) def __nonzero__(self): *************** *** 615,623 **** __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate__(self): return (self.__days, self.__seconds, self.__microseconds) def __reduce__(self): ! return (self.__class__, self.__getstate__()) timedelta.min = timedelta(-999999999) --- 615,623 ---- __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate(self): return (self.__days, self.__seconds, self.__microseconds) def __reduce__(self): ! return (self.__class__, self.__getstate()) timedelta.min = timedelta(-999999999) *************** *** 778,782 **** def __hash__(self): "Hash." ! return hash(self.__getstate__()) # Computations --- 778,782 ---- def __hash__(self): "Hash." ! return hash(self.__getstate()) # Computations *************** *** 853,857 **** __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate__(self): yhi, ylo = divmod(self.__year, 256) return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), ) --- 853,857 ---- __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate(self): yhi, ylo = divmod(self.__year, 256) return ("%c%c%c%c" % (yhi, ylo, self.__month, self.__day), ) *************** *** 865,869 **** def __reduce__(self): ! return (self.__class__, self.__getstate__()) _date_class = date # so functions w/ args named "date" can get at the class --- 865,869 ---- def __reduce__(self): ! return (self.__class__, self.__getstate()) _date_class = date # so functions w/ args named "date" can get at the class *************** *** 1038,1042 **** tzoff = self._utcoffset() if not tzoff: # zero or None ! return hash(self.__getstate__()[0]) h, m = divmod(self.hour * 60 + self.minute - tzoff, 60) if 0 <= h < 24: --- 1038,1042 ---- tzoff = self._utcoffset() if not tzoff: # zero or None ! return hash(self.__getstate()[0]) h, m = divmod(self.hour * 60 + self.minute - tzoff, 60) if 0 <= h < 24: *************** *** 1177,1181 **** __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate__(self): us2, us3 = divmod(self.__microsecond, 256) us1, us2 = divmod(us2, 256) --- 1177,1181 ---- __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate(self): us2, us3 = divmod(self.__microsecond, 256) us1, us2 = divmod(us2, 256) *************** *** 1201,1205 **** def __reduce__(self): ! return (self.__class__, self.__getstate__()) _time_class = time # so functions w/ args named "time" can get at the class --- 1201,1205 ---- def __reduce__(self): ! return (self.__class__, self.__getstate()) _time_class = time # so functions w/ args named "time" can get at the class *************** *** 1561,1565 **** tzoff = self._utcoffset() if tzoff is None: ! return hash(self.__getstate__()[0]) days = _ymd2ord(self.year, self.month, self.day) seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second --- 1561,1565 ---- tzoff = self._utcoffset() if tzoff is None: ! return hash(self.__getstate()[0]) days = _ymd2ord(self.year, self.month, self.day) seconds = self.hour * 3600 + (self.minute - tzoff) * 60 + self.second *************** *** 1570,1574 **** __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate__(self): yhi, ylo = divmod(self.__year, 256) us2, us3 = divmod(self.__microsecond, 256) --- 1570,1574 ---- __safe_for_unpickling__ = True # For Python 2.2 ! def __getstate(self): yhi, ylo = divmod(self.__year, 256) us2, us3 = divmod(self.__microsecond, 256) *************** *** 1597,1601 **** def __reduce__(self): ! return (self.__class__, self.__getstate__()) --- 1597,1601 ---- def __reduce__(self): ! return (self.__class__, self.__getstate()) Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.109 retrieving revision 1.110 diff -C2 -d -r1.109 -r1.110 *** test_datetime.py 31 Jan 2003 21:52:15 -0000 1.109 --- test_datetime.py 1 Feb 2003 03:02:34 -0000 1.110 *************** *** 277,282 **** args = 12, 34, 56 orig = timedelta(*args) - state = orig.__getstate__() - self.assertEqual(args, state) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 277,280 ---- *************** *** 831,836 **** args = 6, 7, 23 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17',), self.theclass) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 829,832 ---- *************** *** 1185,1190 **** args = 6, 7, 23, 20, 59, 1, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17\x14\x3b\x01\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1181,1184 ---- *************** *** 1566,1571 **** args = 20, 59, 16, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x14\x3b\x10\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1560,1563 ---- *************** *** 1876,1881 **** args = 20, 59, 16, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x14\x3b\x10\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 1868,1871 ---- *************** *** 2079,2084 **** args = 6, 7, 23, 20, 59, 1, 64**2 orig = self.theclass(*args) - state = orig.__getstate__() - self.assertEqual(state, ('\x00\x06\x07\x17\x14\x3b\x01\x00\x10\x00',)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) --- 2069,2072 ---- From tim_one@users.sourceforge.net Sat Feb 1 04:40:07 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 20:40:07 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.55,1.56 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv16118/Modules Modified Files: datetimemodule.c Log Message: New functions alloc_{time,datetime}. Got rid of all setstate-like functions. Reworked {time,datetime}_new() to do what their corresponding setstates used to do in their state-tuple-input paths, but directly, without constructing an object with throwaway state first. Tightened the "is this a state tuple input?" paths to check the presumed state string-length too, and to raise an exception if the optional second state element isn't a tzinfo instance (IOW, check these paths for type errors as carefully as the normal paths). Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** datetimemodule.c 1 Feb 2003 02:54:15 -0000 1.55 --- datetimemodule.c 1 Feb 2003 04:40:04 -0000 1.56 *************** *** 1226,1229 **** --- 1226,1265 ---- /* --------------------------------------------------------------------------- + * Basic object allocation. These allocate Python objects of the right + * size and type, and do the Python object-initialization bit. If there's + * not enough memory, they return NULL after setting MemoryError. All + * data members remain uninitialized trash. + */ + static PyDateTime_Time * + alloc_time(int aware) + { + PyDateTime_Time *self; + + self = (PyDateTime_Time *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_Time) : + sizeof(_PyDateTime_BaseTime)); + if (self == NULL) + return (PyDateTime_Time *)PyErr_NoMemory(); + PyObject_INIT(self, &PyDateTime_TimeType); + return self; + } + + static PyDateTime_DateTime * + alloc_datetime(int aware) + { + PyDateTime_DateTime *self; + + self = (PyDateTime_DateTime *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_DateTime) : + sizeof(_PyDateTime_BaseDateTime)); + if (self == NULL) + return (PyDateTime_DateTime *)PyErr_NoMemory(); + PyObject_INIT(self, &PyDateTime_DateTimeType); + return self; + } + + /* --------------------------------------------------------------------------- * Helpers for setting object fields. These work on pointers to the * appropriate base class. *************** *** 1264,1283 **** char aware = tzinfo != Py_None; ! self = (PyDateTime_DateTime *)PyObject_MALLOC(aware ? ! sizeof(PyDateTime_DateTime) : ! sizeof(_PyDateTime_BaseDateTime)); ! if (self == NULL) ! return PyErr_NoMemory(); ! self->hastzinfo = aware; ! set_date_fields((PyDateTime_Date *)self, year, month, day); ! DATE_SET_HOUR(self, hour); ! DATE_SET_MINUTE(self, minute); ! DATE_SET_SECOND(self, second); ! DATE_SET_MICROSECOND(self, usecond); ! if (aware) { ! Py_INCREF(tzinfo); ! self->tzinfo = tzinfo; } ! return (PyObject *)PyObject_INIT(self, &PyDateTime_DateTimeType); } --- 1300,1317 ---- char aware = tzinfo != Py_None; ! self = alloc_datetime(aware); ! if (self != NULL) { ! self->hastzinfo = aware; ! set_date_fields((PyDateTime_Date *)self, year, month, day); ! DATE_SET_HOUR(self, hour); ! DATE_SET_MINUTE(self, minute); ! DATE_SET_SECOND(self, second); ! DATE_SET_MICROSECOND(self, usecond); ! if (aware) { ! Py_INCREF(tzinfo); ! self->tzinfo = tzinfo; ! } } ! return (PyObject *)self; } *************** *** 1289,1308 **** char aware = tzinfo != Py_None; ! self = (PyDateTime_Time *)PyObject_MALLOC(aware ? ! sizeof(PyDateTime_Time) : ! sizeof(_PyDateTime_BaseTime)); ! if (self == NULL) ! return PyErr_NoMemory(); ! self->hastzinfo = aware; ! self->hashcode = -1; ! TIME_SET_HOUR(self, hour); ! TIME_SET_MINUTE(self, minute); ! TIME_SET_SECOND(self, second); ! TIME_SET_MICROSECOND(self, usecond); ! if (aware) { ! Py_INCREF(tzinfo); ! self->tzinfo = tzinfo; } ! return (PyObject *)PyObject_INIT(self, &PyDateTime_TimeType); } --- 1323,1340 ---- char aware = tzinfo != Py_None; ! self = alloc_time(aware); ! if (self != NULL) { ! self->hastzinfo = aware; ! self->hashcode = -1; ! TIME_SET_HOUR(self, hour); ! TIME_SET_MINUTE(self, minute); ! TIME_SET_SECOND(self, second); ! TIME_SET_MICROSECOND(self, usecond); ! if (aware) { ! Py_INCREF(tzinfo); ! self->tzinfo = tzinfo; ! } } ! return (PyObject *)self; } *************** *** 2109,2146 **** static char *date_kws[] = {"year", "month", "day", NULL}; - /* __setstate__ isn't exposed. */ - static PyObject * - date_setstate(PyDateTime_Date *self, PyObject *arg) - { - PyObject *state; - int len; - unsigned char *pdata; - - if (!PyTuple_Check(arg) || PyTuple_GET_SIZE(arg) != 1) - goto error; - state = PyTuple_GET_ITEM(arg, 0); - if (!PyString_Check(state)) - goto error; - - len = PyString_Size(state); - if (len != _PyDateTime_DATE_DATASIZE) - goto error; - - pdata = (unsigned char*)PyString_AsString(state); - memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE); - self->hashcode = -1; - - Py_INCREF(Py_None); - return Py_None; - error: - PyErr_SetString(PyExc_TypeError, - "bad argument to date.__setstate__"); - return NULL; - } - static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; int year; int month; --- 2141,2149 ---- static char *date_kws[] = {"year", "month", "day", NULL}; static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; + PyObject *state; int year; int month; *************** *** 2149,2166 **** /* Check for invocation from pickle with __getstate__ state */ if (PyTuple_GET_SIZE(args) == 1 && ! PyString_Check(PyTuple_GET_ITEM(args, 0))) { ! self = new_date(1, 1, 1); ! if (self != NULL) { ! PyObject *res = date_setstate( ! (PyDateTime_Date *)self, args); ! if (res == Py_None) ! Py_DECREF(res); ! else { ! Py_DECREF(self); ! self = NULL; ! } } ! return self; } --- 2152,2167 ---- /* Check for invocation from pickle with __getstate__ state */ if (PyTuple_GET_SIZE(args) == 1 && ! PyString_Check(state = PyTuple_GET_ITEM(args, 0)) && ! PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE) { ! PyDateTime_Date *me; ! ! me = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); ! if (me != NULL) { ! char *pdata = PyString_AS_STRING(state); ! memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); ! me->hashcode = -1; } ! return (PyObject *)me; } *************** *** 2970,3013 **** "tzinfo", NULL}; - /* __setstate__ isn't exposed. */ - static PyObject * - time_setstate(PyDateTime_Time *self, PyObject *state) - { - PyObject *basestate; - PyObject *tzinfo = Py_None; - - if (! PyArg_ParseTuple(state, "O!|O:__setstate__", - &PyString_Type, &basestate, - &tzinfo)) - return NULL; - if (PyString_Size(basestate) != _PyDateTime_TIME_DATASIZE || - check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, - "bad argument to time.__setstate__"); - return NULL; - } - if (tzinfo != Py_None && ! HASTZINFO(self)) { - PyErr_SetString(PyExc_ValueError, "time.__setstate__ can't " - "add a non-None tzinfo to a time object that " - "doesn't have one already"); - return NULL; - } - memcpy((char *)self->data, - PyString_AsString(basestate), - _PyDateTime_TIME_DATASIZE); - self->hashcode = -1; - if (HASTZINFO(self)) { - Py_INCREF(tzinfo); - Py_XDECREF(self->tzinfo); - self->tzinfo = tzinfo; - } - Py_INCREF(Py_None); - return Py_None; - } - static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; int hour = 0; int minute = 0; --- 2971,2979 ---- "tzinfo", NULL}; static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; + PyObject *state; int hour = 0; int minute = 0; *************** *** 3019,3038 **** if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2 && ! PyString_Check(PyTuple_GET_ITEM(args, 0))) { ! if (PyTuple_GET_SIZE(args) == 2) tzinfo = PyTuple_GET_ITEM(args, 1); ! self = new_time(0, 0, 0, 0, tzinfo); ! if (self != NULL) { ! PyObject *res = time_setstate( ! (PyDateTime_Time *)self, args); ! if (res == Py_None) ! Py_DECREF(res); ! else { ! Py_DECREF(self); ! self = NULL; } } ! return self; } --- 2985,3016 ---- if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2 && ! PyString_Check(state = PyTuple_GET_ITEM(args, 0)) && ! PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE) { ! PyDateTime_Time *me; ! char aware; ! ! if (PyTuple_GET_SIZE(args) == 2) { tzinfo = PyTuple_GET_ITEM(args, 1); ! if (check_tzinfo_subclass(tzinfo) < 0) { ! PyErr_SetString(PyExc_TypeError, "bad " ! "tzinfo state arg"); ! return NULL; } } ! aware = (char)(tzinfo != Py_None); ! me = alloc_time(aware); ! if (me != NULL) { ! char *pdata = PyString_AS_STRING(state); ! ! memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); ! me->hashcode = -1; ! me->hastzinfo = aware; ! if (aware) { ! Py_INCREF(tzinfo); ! me->tzinfo = tzinfo; ! } ! } ! return (PyObject *)me; } *************** *** 3509,3552 **** }; - /* __setstate__ isn't exposed. */ - static PyObject * - datetime_setstate(PyDateTime_DateTime *self, PyObject *state) - { - PyObject *basestate; - PyObject *tzinfo = Py_None; - - if (! PyArg_ParseTuple(state, "O!|O:__setstate__", - &PyString_Type, &basestate, - &tzinfo)) - return NULL; - if (PyString_Size(basestate) != _PyDateTime_DATETIME_DATASIZE || - check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, - "bad argument to datetime.__setstate__"); - return NULL; - } - if (tzinfo != Py_None && ! HASTZINFO(self)) { - PyErr_SetString(PyExc_ValueError, "datetime.__setstate__ " - "can't add a non-None tzinfo to a datetime " - "object that doesn't have one already"); - return NULL; - } - memcpy((char *)self->data, - PyString_AsString(basestate), - _PyDateTime_DATETIME_DATASIZE); - self->hashcode = -1; - if (HASTZINFO(self)) { - Py_INCREF(tzinfo); - Py_XDECREF(self->tzinfo); - self->tzinfo = tzinfo; - } - Py_INCREF(Py_None); - return Py_None; - } - static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; int year; int month; --- 3487,3495 ---- }; static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; + PyObject *state; int year; int month; *************** *** 3561,3580 **** if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2 && ! PyString_Check(PyTuple_GET_ITEM(args, 0))) { ! if (PyTuple_GET_SIZE(args) == 2) tzinfo = PyTuple_GET_ITEM(args, 1); ! self = new_datetime(1, 1, 1, 0, 0, 0, 0, tzinfo); ! if (self != NULL) { ! PyObject *res = datetime_setstate( ! (PyDateTime_DateTime *)self, args); ! if (res == Py_None) ! Py_DECREF(res); ! else { ! Py_DECREF(self); ! self = NULL; } } ! return self; } --- 3504,3535 ---- if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2 && ! PyString_Check(state = PyTuple_GET_ITEM(args, 0)) && ! PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE) { ! PyDateTime_DateTime *me; ! char aware; ! ! if (PyTuple_GET_SIZE(args) == 2) { tzinfo = PyTuple_GET_ITEM(args, 1); ! if (check_tzinfo_subclass(tzinfo) < 0) { ! PyErr_SetString(PyExc_TypeError, "bad " ! "tzinfo state arg"); ! return NULL; } } ! aware = (char)(tzinfo != Py_None); ! me = alloc_datetime(aware); ! if (me != NULL) { ! char *pdata = PyString_AS_STRING(state); ! ! memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); ! me->hashcode = -1; ! me->hastzinfo = aware; ! if (aware) { ! Py_INCREF(tzinfo); ! me->tzinfo = tzinfo; ! } ! } ! return (PyObject *)me; } From tim_one@users.sourceforge.net Sat Feb 1 06:22:39 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 22:22:39 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.101,2.102 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7748/Modules Modified Files: cPickle.c Log Message: Added #defines for proto 2 opcodes; gave the Pickler a proto member; removed woefully inadequate opcode docs and pointed to pickletools.py instead. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.101 retrieving revision 2.102 diff -C2 -d -r2.101 -r2.102 *** cPickle.c 1 Feb 2003 02:16:37 -0000 2.101 --- cPickle.c 1 Feb 2003 06:22:36 -0000 2.102 *************** *** 21,39 **** #define WRITE_BUF_SIZE 256 ! /* -------------------------------------------------------------------------- ! NOTES on format codes. ! XXX much more is needed here ! ! Integer types ! BININT1 8-bit unsigned integer; followed by 1 byte. ! BININT2 16-bit unsigned integer; followed by 2 bytes, little-endian. ! BININT 32-bit signed integer; followed by 4 bytes, little-endian. ! INT Integer; natural decimal string conversion, then newline. ! CAUTION: INT-reading code can't assume that what follows ! fits in a Python int, because the size of Python ints varies ! across platforms. ! LONG Long (unbounded) integer; repr(i), then newline. ! -------------------------------------------------------------------------- */ ! #define MARK '(' #define STOP '.' --- 21,28 ---- #define WRITE_BUF_SIZE 256 ! /* ! * Pickle opcodes. These must be kept in synch with pickle.py. Extensive ! * docs are in pickletools.py. ! */ #define MARK '(' #define STOP '.' *************** *** 77,80 **** --- 66,89 ---- #define EMPTY_TUPLE ')' #define SETITEMS 'u' + + /* Protocol 2. */ + #define PROTO '\x80' /* identify pickle protocol */ + #define NEWOBJ '\x81' /* build object by applying cls.__new__ to argtuple */ + #define EXT1 '\x82' /* push object from extension registry; 1-byte index */ + #define EXT2 '\x83' /* ditto, but 2-byte index */ + #define EXT4 '\x84' /* ditto, but 4-byte index */ + #define TUPLE1 '\x85' /* build 1-tuple from stack top */ + #define TUPLE2 '\x86' /* build 2-tuple from two topmost stack items */ + #define TUPLE3 '\x87' /* build 3-tuple from three topmost stack items */ + #define NEWTRUE '\x88' /* push True */ + #define NEWFALSE '\x89' /* push False */ + #define LONG1 '\x8a' /* push long from < 256 bytes */ + #define LONG4 '\x8b' /* push really big long */ + + /* There aren't opcodes -- they're ways to pickle bools before protocol 2, + * so that unpicklers written before bools were introduced unpickle them + * as ints, but unpicklers after can recognize that bools were intended. + * Note that protocol 2 added direct ways to pickle bools. + */ #undef TRUE #define TRUE "I01\n" *************** *** 82,86 **** #define FALSE "I00\n" - static char MARKv = MARK; --- 91,94 ---- *************** *** 270,274 **** --- 278,288 ---- PyObject *pers_func; PyObject *inst_pers_func; + + /* pickle protocol number, >= 0 */ + int proto; + + /* bool, true if proto > 0 */ int bin; + int fast; /* Fast mode doesn't save in memo, don't use if circ ref */ int nesting; From tim_one@users.sourceforge.net Sat Feb 1 06:24:38 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 22:24:38 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.102,2.103 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv8336/Modules Modified Files: cPickle.c Log Message: Trimmed trailing whitespace. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.102 retrieving revision 2.103 diff -C2 -d -r2.102 -r2.103 *** cPickle.c 1 Feb 2003 06:22:36 -0000 2.102 --- cPickle.c 1 Feb 2003 06:24:36 -0000 2.103 *************** *** 119,127 **** static void ! Pdata_dealloc(Pdata *self) { int i; PyObject **p; ! for (i=self->length, p=self->data; --i >= 0; p++) Py_DECREF(*p); --- 119,127 ---- [...2609 lines suppressed...] PickleError) < 0) --- 4745,4749 ---- UnpicklingError, NULL))) return -1; ! if (PyDict_SetItemString(module_dict, "PickleError", PickleError) < 0) *************** *** 4775,4779 **** #endif PyMODINIT_FUNC ! initcPickle(void) { PyObject *m, *d, *di, *v, *k; --- 4775,4779 ---- #endif PyMODINIT_FUNC ! initcPickle(void) { PyObject *m, *d, *di, *v, *k; From tim_one@users.sourceforge.net Sat Feb 1 06:28:01 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 22:28:01 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.103,2.104 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv8925/Modules Modified Files: cPickle.c Log Message: The module docstring had an RCS ID from 1999 embedded in it. Enough already . Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.103 retrieving revision 2.104 diff -C2 -d -r2.103 -r2.104 *** cPickle.c 1 Feb 2003 06:24:36 -0000 2.103 --- cPickle.c 1 Feb 2003 06:27:59 -0000 2.104 *************** *** 4,10 **** PyDoc_STRVAR(cPickle_module_documentation, ! "C implementation and optimization of the Python pickle module\n" ! "\n" ! "cPickle.c,v 1.71 1999/07/11 13:30:34 jim Exp\n"); #ifndef Py_eval_input --- 4,8 ---- PyDoc_STRVAR(cPickle_module_documentation, ! "C implementation and optimization of the Python pickle module."); #ifndef Py_eval_input From tim_one@users.sourceforge.net Sat Feb 1 06:30:14 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 31 Jan 2003 22:30:14 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.104,2.105 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9429/Modules Modified Files: cPickle.c Log Message: Removed needless include of errno.h. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.104 retrieving revision 2.105 diff -C2 -d -r2.104 -r2.105 *** cPickle.c 1 Feb 2003 06:27:59 -0000 2.104 --- cPickle.c 1 Feb 2003 06:30:12 -0000 2.105 *************** *** 11,18 **** #endif /* Py_eval_input */ - #include - - - #define DEL_LIST_SLICE(list, from, to) (PyList_SetSlice(list, from, to, NULL)) --- 11,14 ---- From jvr@users.sourceforge.net Sat Feb 1 08:34:49 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sat, 01 Feb 2003 00:34:49 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv2720/Lib/plat-mac Modified Files: bundlebuilder.py Log Message: icon support by Robin Dunn, closes patch #678218 Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** bundlebuilder.py 17 Jan 2003 20:02:06 -0000 1.4 --- bundlebuilder.py 1 Feb 2003 08:34:46 -0000 1.5 *************** *** 282,285 **** --- 282,289 ---- nibname = None + # The name of the icon file to be copied to Resources and used for + # the Finder icon. + iconfile = None + # Symlink the executable instead of copying it. symlink_exec = 0 *************** *** 370,373 **** --- 374,382 ---- os.chmod(bootstrappath, 0775) + if self.iconfile is not None: + iconbase = os.path.basename(self.iconfile) + self.plist.CFBundleIconFile = iconbase + self.files.append((self.iconfile, pathjoin(resdir, iconbase))) + def postProcess(self): if self.standalone: *************** *** 611,614 **** --- 620,625 ---- --nib=NAME main nib name -c, --creator=CCCC 4-char creator code (default: '????') + --iconfile=FILE filename of the icon (an .icns file) to be used + as the Finder icon -l, --link symlink files/folder instead of copying them --link-exec symlink the executable instead of copying it *************** *** 638,642 **** "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "standalone", ! "exclude=", "include=", "package=", "strip") try: --- 649,653 ---- "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "standalone", ! "exclude=", "include=", "package=", "strip", "iconfile=") try: *************** *** 658,661 **** --- 669,674 ---- elif opt in ('-c', '--creator'): builder.creator = arg + elif opt == '--iconfile': + builder.iconfile = arg elif opt == "--nib": builder.nibname = arg From jvr@users.sourceforge.net Sat Feb 1 10:07:30 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sat, 01 Feb 2003 02:07:30 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts buildpkg.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv25082/Mac/scripts Modified Files: buildpkg.py Log Message: patch #678211 from Robin Dunn Index: buildpkg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/buildpkg.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** buildpkg.py 6 Sep 2002 21:55:13 -0000 1.2 --- buildpkg.py 1 Feb 2003 10:07:28 -0000 1.3 *************** *** 71,74 **** --- 71,75 ---- InstallOnly RequiresReboot + RootVolumeOnly InstallFat\ """ *************** *** 148,151 **** --- 149,153 ---- 'InstallOnly': 'NO', 'RequiresReboot': 'NO', + 'RootVolumeOnly' : 'NO', 'InstallFat': 'NO'} *************** *** 281,291 **** # find pre-process and post-process scripts ! # naming convention: packageName.{pre,post}-{upgrade,install} ! # Alternatively the filenames can be {pre,post}-{upgrade,install} # in which case we prepend the package name packageName = self.packageInfo["Title"] ! for pat in ("*upgrade", "*install"): pattern = join(self.resourceFolder, packageName + pat) allFiles = allFiles + glob.glob(pattern) # check name patterns --- 283,295 ---- # find pre-process and post-process scripts ! # naming convention: packageName.{pre,post}_{upgrade,install} ! # Alternatively the filenames can be {pre,post}_{upgrade,install} # in which case we prepend the package name packageName = self.packageInfo["Title"] ! for pat in ("*upgrade", "*install", "*flight"): pattern = join(self.resourceFolder, packageName + pat) + pattern2 = join(self.resourceFolder, pat) allFiles = allFiles + glob.glob(pattern) + allFiles = allFiles + glob.glob(pattern2) # check name patterns *************** *** 297,309 **** if f[-6:] == ".lproj": files.append((f, f)) ! elif f in ["pre-upgrade", "pre-install", "post-upgrade", "post-install"]: ! files.append((f, self.packageInfo["Title"]+"."+f)) ! elif f[-8:] == "-upgrade": files.append((f,f)) ! elif f[-8:] == "-install": files.append((f,f)) # copy files for src, dst in files: f = join(self.resourceFolder, src) if isfile(f): --- 301,317 ---- if f[-6:] == ".lproj": files.append((f, f)) ! elif basename(f) in ["pre_upgrade", "pre_install", "post_upgrade", "post_install"]: ! files.append((f, packageName+"."+basename(f))) ! elif basename(f) in ["preflight", "postflight"]: ! files.append((f, f)) ! elif f[-8:] == "_upgrade": files.append((f,f)) ! elif f[-8:] == "_install": files.append((f,f)) # copy files for src, dst in files: + src = basename(src) + dst = basename(dst) f = join(self.resourceFolder, src) if isfile(f): From jvr@users.sourceforge.net Sat Feb 1 10:29:48 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sat, 01 Feb 2003 02:29:48 -0800 Subject: [Python-checkins] python/dist/src/Lib modulefinder.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv30044/Lib Modified Files: modulefinder.py Log Message: removed bizarre construct, no idea why it was there... Index: modulefinder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/modulefinder.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** modulefinder.py 29 Jan 2003 03:49:43 -0000 1.3 --- modulefinder.py 1 Feb 2003 10:29:45 -0000 1.4 *************** *** 413,417 **** keys.sort() for key in keys: - continue m = self.modules[key] if m.__path__: --- 413,416 ---- From tim_one@users.sourceforge.net Sat Feb 1 16:45:08 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 08:45:08 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.136,1.137 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv16979/Lib Modified Files: pickle.py Log Message: The C pickle now knows how to deal with a proto= argument. Assorted code cleanups, and purged more references to text-vs-binary modes. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.136 retrieving revision 1.137 diff -C2 -d -r1.136 -r1.137 *** pickle.py 31 Jan 2003 19:42:31 -0000 1.136 --- pickle.py 1 Feb 2003 16:45:05 -0000 1.137 *************** *** 175,179 **** protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text ! mode and read back successfully.) Protocol 1 is more efficient than protocol 0; protocol 2 is --- 175,181 ---- protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text ! mode and read back successfully. When using a protocol higher ! than 0, make sure the file is opened in binary mode, both when ! pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is *************** *** 181,185 **** Specifying a negative protocol version selects the highest ! protocol version supported. The file parameter must have a write() method that accepts a single --- 183,189 ---- Specifying a negative protocol version selects the highest ! protocol version supported. The higher the protocol used, the ! more recent the version of Python needed to read the pickle ! produced. The file parameter must have a write() method that accepts a single *************** *** 210,219 **** def dump(self, obj): ! """Write a pickled representation of obj to the open file. ! ! Either the binary or ASCII format will be used, depending on the ! value of the bin flag passed to the constructor. ! ! """ if self.proto >= 2: self.write(PROTO + chr(self.proto)) --- 214,218 ---- def dump(self, obj): ! """Write a pickled representation of obj to the open file.""" if self.proto >= 2: self.write(PROTO + chr(self.proto)) *************** *** 932,938 **** """This takes a file-like object for reading a pickle data stream. ! This class automatically determines whether the data stream was ! written in binary mode or not, so it does not need a flag as in ! the Pickler class factory. The file-like object must have two methods, a read() method that --- 931,936 ---- """This takes a file-like object for reading a pickle data stream. ! The protocol version of the pickle is detected automatically, so no ! proto argument is needed. The file-like object must have two methods, a read() method that From tim_one@users.sourceforge.net Sat Feb 1 16:45:10 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 08:45:10 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.105,2.106 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv16979/Modules Modified Files: cPickle.c Log Message: The C pickle now knows how to deal with a proto= argument. Assorted code cleanups, and purged more references to text-vs-binary modes. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.105 retrieving revision 2.106 diff -C2 -d -r2.105 -r2.106 *** cPickle.c 1 Feb 2003 06:30:12 -0000 2.105 --- cPickle.c 1 Feb 2003 16:45:06 -0000 2.106 *************** *** 15,18 **** --- 15,21 ---- #define WRITE_BUF_SIZE 256 + /* Bump this when new opcodes are added to the pickle protocol. */ + #define CURRENT_PROTOCOL_NUMBER 2 + /* * Pickle opcodes. These must be kept in synch with pickle.py. Extensive *************** *** 2317,2327 **** static Picklerobject * ! newPicklerobject(PyObject *file, int bin) { Picklerobject *self; ! if (!( self = PyObject_New(Picklerobject, &Picklertype))) return NULL; self->fp = NULL; self->write = NULL; --- 2320,2341 ---- static Picklerobject * ! newPicklerobject(PyObject *file, int proto) { Picklerobject *self; ! if (proto < 0) ! proto = CURRENT_PROTOCOL_NUMBER; ! if (proto > CURRENT_PROTOCOL_NUMBER) { ! PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; " ! "the highest available protocol is %d", ! proto, CURRENT_PROTOCOL_NUMBER); return NULL; + } + self = PyObject_New(Picklerobject, &Picklertype); + if (self == NULL) + return NULL; + self->proto = proto; + self->bin = proto > 0; self->fp = NULL; self->write = NULL; *************** *** 2331,2335 **** self->inst_pers_func = NULL; self->write_buf = NULL; - self->bin = bin; self->fast = 0; self->nesting = 0; --- 2345,2348 ---- *************** *** 2339,2349 **** self->dispatch_table = NULL; if (file) Py_INCREF(file); ! else ! file=Pdata_New(); ! ! if (!( self->file = file )) ! goto err; if (!( self->memo = PyDict_New())) --- 2352,2364 ---- self->dispatch_table = NULL; + self->file = NULL; if (file) Py_INCREF(file); ! else { ! file = Pdata_New(); ! if (file == NULL) ! goto err; ! } ! self->file = file; if (!( self->memo = PyDict_New())) *************** *** 2353,2357 **** self->fp = PyFile_AsFile(file); if (self->fp == NULL) { ! PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); goto err; } --- 2368,2373 ---- self->fp = PyFile_AsFile(file); if (self->fp == NULL) { ! PyErr_SetString(PyExc_ValueError, ! "I/O operation on closed file"); goto err; } *************** *** 2378,2383 **** } ! if (!( self->write_buf = ! (char *)malloc(WRITE_BUF_SIZE * sizeof(char)))) { PyErr_NoMemory(); goto err; --- 2394,2399 ---- } ! self->write_buf = (char *)PyMem_Malloc(WRITE_BUF_SIZE); ! if (self->write_buf == NULL) { PyErr_NoMemory(); goto err; *************** *** 2402,2406 **** err: ! Py_DECREF((PyObject *)self); return NULL; } --- 2418,2422 ---- err: ! Py_DECREF(self); return NULL; } *************** *** 2411,2423 **** { PyObject *file = NULL; ! int bin = 1; ! if (!PyArg_ParseTuple(args, "|i:Pickler", &bin)) { PyErr_Clear(); ! bin = 0; ! if (!PyArg_ParseTuple(args, "O|i:Pickler", &file, &bin)) return NULL; } ! return (PyObject *)newPicklerobject(file, bin); } --- 2427,2444 ---- { PyObject *file = NULL; ! int proto = 0; ! /* XXX What is this doing? The documented signature is ! * XXX Pickler(file, proto=0), but this accepts Pickler() and ! * XXX Pickler(integer) too. The meaning then is clear as mud. ! * XXX Bug? Feature? ! */ ! if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) { PyErr_Clear(); ! proto = 0; ! if (!PyArg_ParseTuple(args, "O|i:Pickler", &file, &proto)) return NULL; } ! return (PyObject *)newPicklerobject(file, proto); } *************** *** 2434,2442 **** Py_XDECREF(self->inst_pers_func); Py_XDECREF(self->dispatch_table); ! ! if (self->write_buf) { ! free(self->write_buf); ! } ! PyObject_Del(self); } --- 2455,2459 ---- Py_XDECREF(self->inst_pers_func); Py_XDECREF(self->dispatch_table); ! PyMem_Free(self->write_buf); PyObject_Del(self); } *************** *** 4488,4492 **** --- 4505,4513 ---- } + /* --------------------------------------------------------------------------- + * Module-level functions. + */ + /* dump(obj, file, proto=0). */ static PyObject * cpm_dump(PyObject *self, PyObject *args) *************** *** 4494,4503 **** PyObject *ob, *file, *res = NULL; Picklerobject *pickler = 0; ! int bin = 0; ! if (!( PyArg_ParseTuple(args, "OO|i", &ob, &file, &bin))) goto finally; ! if (!( pickler = newPicklerobject(file, bin))) goto finally; --- 4515,4524 ---- PyObject *ob, *file, *res = NULL; Picklerobject *pickler = 0; ! int proto = 0; ! if (!( PyArg_ParseTuple(args, "OO|i", &ob, &file, &proto))) goto finally; ! if (!( pickler = newPicklerobject(file, proto))) goto finally; *************** *** 4515,4518 **** --- 4536,4540 ---- + /* dumps(obj, proto=0). */ static PyObject * cpm_dumps(PyObject *self, PyObject *args) *************** *** 4520,4526 **** PyObject *ob, *file = 0, *res = NULL; Picklerobject *pickler = 0; ! int bin = 0; ! if (!( PyArg_ParseTuple(args, "O|i:dumps", &ob, &bin))) goto finally; --- 4542,4548 ---- PyObject *ob, *file = 0, *res = NULL; Picklerobject *pickler = 0; ! int proto = 0; ! if (!( PyArg_ParseTuple(args, "O|i:dumps", &ob, &proto))) goto finally; *************** *** 4528,4532 **** goto finally; ! if (!( pickler = newPicklerobject(file, bin))) goto finally; --- 4550,4554 ---- goto finally; ! if (!( pickler = newPicklerobject(file, proto))) goto finally; *************** *** 4544,4547 **** --- 4566,4570 ---- + /* load(fileobj). */ static PyObject * cpm_load(PyObject *self, PyObject *args) *************** *** 4565,4568 **** --- 4588,4592 ---- + /* loads(string) */ static PyObject * cpm_loads(PyObject *self, PyObject *args) *************** *** 4620,4651 **** static struct PyMethodDef cPickle_methods[] = { {"dump", (PyCFunction)cpm_dump, METH_VARARGS, ! PyDoc_STR("dump(object, file, [binary]) --" ! "Write an object in pickle format to the given file\n" "\n" ! "If the optional argument, binary, is provided and is true, then the\n" ! "pickle will be written in binary format, which is more space and\n" ! "computationally efficient. \n") }, {"dumps", (PyCFunction)cpm_dumps, METH_VARARGS, ! PyDoc_STR("dumps(object, [binary]) --" ! "Return a string containing an object in pickle format\n" "\n" ! "If the optional argument, binary, is provided and is true, then the\n" ! "pickle will be written in binary format, which is more space and\n" ! "computationally efficient. \n") }, {"load", (PyCFunction)cpm_load, METH_VARARGS, PyDoc_STR("load(file) -- Load a pickle from the given file")}, {"loads", (PyCFunction)cpm_loads, METH_VARARGS, PyDoc_STR("loads(string) -- Load a pickle from the given string")}, {"Pickler", (PyCFunction)get_Pickler, METH_VARARGS, ! PyDoc_STR("Pickler(file, [binary]) -- Create a pickler\n" "\n" ! "If the optional argument, binary, is provided and is true, then\n" ! "pickles will be written in binary format, which is more space and\n" ! "computationally efficient. \n") }, {"Unpickler", (PyCFunction)get_Unpickler, METH_VARARGS, ! PyDoc_STR("Unpickler(file) -- Create an unpickler")}, { NULL, NULL } }; --- 4644,4694 ---- static struct PyMethodDef cPickle_methods[] = { {"dump", (PyCFunction)cpm_dump, METH_VARARGS, ! PyDoc_STR("dump(object, file, proto=0) -- " ! "Write an object in pickle format to the given file.\n" "\n" ! "See the Pickler docstring for the meaning of optional argument proto.") }, + {"dumps", (PyCFunction)cpm_dumps, METH_VARARGS, ! PyDoc_STR("dumps(object, proto=0) -- " ! "Return a string containing an object in pickle format.\n" "\n" ! "See the Pickler docstring for the meaning of optional argument proto.") }, + {"load", (PyCFunction)cpm_load, METH_VARARGS, PyDoc_STR("load(file) -- Load a pickle from the given file")}, + {"loads", (PyCFunction)cpm_loads, METH_VARARGS, PyDoc_STR("loads(string) -- Load a pickle from the given string")}, + {"Pickler", (PyCFunction)get_Pickler, METH_VARARGS, ! PyDoc_STR("Pickler(file, proto=0) -- Create a pickler.\n" "\n" ! "This takes a file-like object for writing a pickle data stream.\n" ! "The optional proto argument tells the pickler to use the given\n" ! "protocol; supported protocols are 0, 1, 2. The default\n" ! "protocol is 0, to be backwards compatible. (Protocol 0 is the\n" ! "only protocol that can be written to a file opened in text\n" ! "mode and read back successfully. When using a protocol higher\n" ! "than 0, make sure the file is opened in binary mode, both when\n" ! "pickling and unpickling.)\n" ! "\n" ! "Protocol 1 is more efficient than protocol 0; protocol 2 is\n" ! "more efficient than protocol 1.\n" ! "\n" ! "Specifying a negative protocol version selects the highest\n" ! "protocol version supported. The higher the protocol used, the\n" ! "more recent the version of Python needed to read the pickle\n" ! "produced.\n" ! "\n" ! "The file parameter must have a write() method that accepts a single\n" ! "string argument. It can thus be an open file object, a StringIO\n" ! "object, or any other custom object that meets this interface.\n") }, + {"Unpickler", (PyCFunction)get_Unpickler, METH_VARARGS, ! PyDoc_STR("Unpickler(file) -- Create an unpickler.")}, ! { NULL, NULL } }; *************** *** 4684,4689 **** Py_DECREF(copy_reg); - - /* Down to here ********************************** */ if (!( empty_tuple = PyTuple_New(0))) --- 4727,4730 ---- From gvanrossum@users.sourceforge.net Sat Feb 1 19:02:12 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sat, 01 Feb 2003 11:02:12 -0800 Subject: [Python-checkins] python/nondist/peps pep-0283.txt,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv17078 Modified Files: pep-0283.txt Log Message: Remove text about new pickling; refer to PEP 307 instead. Index: pep-0283.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0283.txt,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** pep-0283.txt 7 Jan 2003 02:23:50 -0000 1.28 --- pep-0283.txt 1 Feb 2003 19:02:10 -0000 1.29 *************** *** 27,35 **** guidelines: ! alpha 2 -- late January ! beta 1 -- late February ! beta 2 -- late March ! rc 1 -- late April ! final -- early May --- 27,35 ---- guidelines: ! alpha 2 -- mid February ! beta 1 -- mid March ! beta 2 -- mid April ! rc 1 -- mid May ! final -- end of May *************** *** 39,72 **** - Open issues - - There are some issues that may need more work and/or thought - before the final release (and preferably before the first beta - release). For example: - - - Set API issues; is the sets module perfect? - - I expect it's good enough to stop polishing it until we've had - more widespread user experience. - - - A nicer API to open text files, replacing the ugly (in some - people's eyes) "U" mode flag. There's a proposal out there to - have a new built-in type textfile(filename, mode, encoding). - (Shouldn't it have a bufsize argument too?) - - Ditto. - - - Fredrik Lundh's basetime proposal: - http://effbot.org/ideas/time-type.htm - - I believe this is dead now. - - - New widgets for Tkinter??? - - Has anyone gotten the time for this? *Are* there any new - widgets in Tk 8.4? Note that we've got better Tix support - already (though not on Windows yet). - - Completed features for 2.3 --- 39,42 ---- *************** *** 179,217 **** life of the 2.3 development process. ! - reST is going to be used a lot in Zope3. Maybe it could become ! a standard library module? ! ! - I really, really, really would like to improve pickling of ! new-style classes. ! ! I've finally come to the conclusion that any solution to making ! pickled new-style class instances (and hence pickled datetime ! objects) more efficient will require adding new codes to the ! pickle protocol. ! ! We can do that in Python 2.3. Because this is backwards ! incompatible, I propose that you have to request this protocol ! explicitly. I propose to "upgrade' the binary flag to a general ! "protocol version" flag, with values: ! ! 0 - original protocol ! 1 - binary protocol ! 2 - new protocol ! ! The new protocol can contain an explicit pickle code for the new ! datetime objects. That's about all the thinking I've done so ! far. We need to decide on the new format, but first we must ! figure out ways how to efficiently pickle and unpickle subclass ! instances of (picklable) built-in types, preferably without ! having to copy all the data twice, and instances of new-style ! classes with slots. And we need to implement these twice: in ! Python for pickle.py and in C for cPickle.py. ! ! - I'd also like to get rid of __safe_for_unpickling__ and all ! other pseudo security features. Attempting to unpickle pickles ! from an untrusted source is insane, and nothing can help us ! there; I'd rather make the marshal protocol bulletproof (all it ! needs is a few more checks for inconsistent data and a little ! better error handling). - For a class defined inside another class, the __name__ should be --- 149,153 ---- life of the 2.3 development process. ! - A new pickling protocol. See PEP 307. - For a class defined inside another class, the __name__ should be *************** *** 248,252 **** --- 184,222 ---- + Open issues + + There are some issues that may need more work and/or thought + before the final release (and preferably before the first beta + release). For example: + + - Set API issues; is the sets module perfect? + + I expect it's good enough to stop polishing it until we've had + more widespread user experience. + + - A nicer API to open text files, replacing the ugly (in some + people's eyes) "U" mode flag. There's a proposal out there to + have a new built-in type textfile(filename, mode, encoding). + (Shouldn't it have a bufsize argument too?) + + Ditto. + + - Fredrik Lundh's basetime proposal: + http://effbot.org/ideas/time-type.htm + + I believe this is dead now. + + - New widgets for Tkinter??? + + Has anyone gotten the time for this? *Are* there any new + widgets in Tk 8.4? Note that we've got better Tix support + already (though not on Windows yet). + + Features unlikely to make it into Python 2.3 + + - reST is going to be used a lot in Zope3. Maybe it could become + a standard library module? (Since reST's author thinks it's too + instable, I'm inclined not to do this.) - Decide on a clearer deprecation policy (especially for modules) From gvanrossum@users.sourceforge.net Sat Feb 1 20:10:38 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sat, 01 Feb 2003 12:10:38 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv5868 Modified Files: pep-0307.txt Log Message: Add __newobj__ and TBD section. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** pep-0307.txt 31 Jan 2003 21:58:34 -0000 1.4 --- pep-0307.txt 1 Feb 2003 20:10:35 -0000 1.5 *************** *** 134,141 **** function A callable object (not necessarily a function) called ! to create the initial version of the object; state may ! be added to the object later to fully reconstruct the ! pickled state. This function must itself be ! picklable. arguments A tuple giving the argument list for the function. --- 134,142 ---- function A callable object (not necessarily a function) called ! to create the initial version of the object; state ! may be added to the object later to fully reconstruct ! the pickled state. This function must itself be ! picklable. See the section about __newobj__ for a ! special case (new in this PEP) here. arguments A tuple giving the argument list for the function. *************** *** 183,186 **** --- 184,213 ---- 2.3, __setstate__ will never be called when __reduce__ returns a state with value None. + + + The __newobj__ unpickling function + + When the unpickling function returned by __reduce__ (the first + item of the returned tuple) has the name __newobj__, something + special happens for pickle protocol 2. An unpickling function + named __newobj__ is assumed to have the following semantics: + + def __newobj__(cls, *args): + return cls.__new__(cls, *args) + + Pickle protocol 2 special-cases an unpickling function with this + name, and emits a pickling opcode that, given 'cls' and 'args', + will return cls.__new__(cls, *args) without also pickling a + reference to __newobj__. This is the main reason why protocol 2 + pickles are so much smaller than classic pickles. Of course, the + pickling code cannot verify that a function named __newobj__ + actually has the expected semantics. If you use an unpickling + function named __newobj__ that returns something different, you + deserve what you get. + + + TBD + + The rest of this PEP is still under construction! From neal@metaslash.com Sat Feb 1 23:01:32 2003 From: neal@metaslash.com (Neal Norwitz) Date: Sat, 01 Feb 2003 18:01:32 -0500 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.148,1.149 In-Reply-To: References: Message-ID: <20030201230132.GI24222@epoch.metaslash.com> > + _PyLong_Sign(PyObject *vv) > + { > + PyLongObject *v = (PyLongObject *)vv; > + const int ndigits = v->ob_size; > + > + assert(v != NULL); Not sure how useful this assert is since v was already dereferenced on the line above (v->ob_size). Neal From tim_one@email.msn.com Sat Feb 1 23:58:20 2003 From: tim_one@email.msn.com (Tim Peters) Date: Sat, 1 Feb 2003 18:58:20 -0500 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.148,1.149 In-Reply-To: <20030201230132.GI24222@epoch.metaslash.com> Message-ID: >> + _PyLong_Sign(PyObject *vv) >> + { >> + PyLongObject *v = (PyLongObject *)vv; >> + const int ndigits = v->ob_size; >> + >> + assert(v != NULL); [Neal Norwitz] > Not sure how useful this assert is since v was already > dereferenced on the line above (v->ob_size). Its only use is to the human reader, who, when this blows up, looks at the code. Then the assert() clearly communicates that v != NULL is a precondition for calling this internal API function. If the assert() weren't there, the reader would have to guess (or read the comment before the declaration in the .h file -- but that's too much to ask ). From tim_one@users.sourceforge.net Sun Feb 2 02:57:54 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 18:57:54 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.137,1.138 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv8448/Lib Modified Files: pickle.py Log Message: cPickle.c: Full support for the new LONG1 and LONG4. Added comments. Assorted code cleanups; e.g., sizeof(char) is 1 by definition, so there's no need to do things like multiply by sizeof(char) in hairy malloc arguments. Fixed an undetected-overflow bug in readline_file(). longobject.c: Fixed a really stupid bug in the new _PyLong_NumBits. pickle.py: Fixed stupid bug in save_long(): When proto is 2, it wrote LONG1 or LONG4, but forgot to return then -- it went on to append the proto 1 LONG opcode too. Fixed equally stupid cancelling bugs in load_long1() and load_long4(): they *returned* the unpickled long instead of pushing it on the stack. The return values were ignored. Tests passed before only because save_long() pickled the long twice. Fixed bugs in encode_long(). Noted that decode_long() is quadratic-time despite our hopes, because long(string, 16) is still quadratic-time in len(string). It's hex() that's linear-time. I don't know a way to make decode_long() linear-time in Python, short of maybe transforming the 256's-complement bytes into marshal's funky internal format, and letting marshal decode that. It would be more valuable to make long(string, 16) linear time. pickletester.py: Added a global "protocols" vector so tests can try all the protocols in a sane way. Changed test_ints() and test_unicode() to do so. Added a new test_long(), but the tail end of it is disabled because it "takes forever" under pickle.py (but runs very quickly under cPickle: cPickle proto 2 for longs is linear-time). Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.137 retrieving revision 1.138 diff -C2 -d -r1.137 -r1.138 *** pickle.py 1 Feb 2003 16:45:05 -0000 1.137 --- pickle.py 2 Feb 2003 02:57:52 -0000 1.138 *************** *** 554,557 **** --- 554,558 ---- else: self.write(LONG4 + pack(" 0 ashex = hex(x) ! if x >> (nbits - 1) == 0: # "looks positive", so need a byte of sign bits ! ashex = "0xff" + x[2:] if ashex.endswith('L'): --- 1412,1422 ---- assert x > 0 ashex = hex(x) ! njunkchars = 2 + ashex.endswith('L') ! newnibbles = len(ashex) - njunkchars ! if newnibbles < nibbles: ! ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:] ! if int(ashex[2], 16) < 8: # "looks positive", so need a byte of sign bits ! ashex = "0xff" + ashex[2:] if ashex.endswith('L'): *************** *** 1419,1426 **** else: ashex = ashex[2:] ! assert len(ashex) & 1 == 0 binary = _binascii.unhexlify(ashex) return binary[::-1] def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. --- 1424,1434 ---- else: ashex = ashex[2:] ! assert len(ashex) & 1 == 0, (x, ashex) binary = _binascii.unhexlify(ashex) return binary[::-1] + # XXX OOPS! This is still quadratic-time. While hex(n) is linear-time + # XXX in the # of digits in n, long(s, 16) is still quadratic-time + # XXX in len(s). def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. *************** *** 1446,1450 **** return 0L ashex = _binascii.hexlify(data[::-1]) ! n = long(ashex, 16) if data[-1] >= '\x80': n -= 1L << (nbytes * 8) --- 1454,1458 ---- return 0L ashex = _binascii.hexlify(data[::-1]) ! n = long(ashex, 16) # quadratic time if data[-1] >= '\x80': n -= 1L << (nbytes * 8) From tim_one@users.sourceforge.net Sun Feb 2 02:57:54 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 18:57:54 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv8448/Lib/test Modified Files: pickletester.py Log Message: cPickle.c: Full support for the new LONG1 and LONG4. Added comments. Assorted code cleanups; e.g., sizeof(char) is 1 by definition, so there's no need to do things like multiply by sizeof(char) in hairy malloc arguments. Fixed an undetected-overflow bug in readline_file(). longobject.c: Fixed a really stupid bug in the new _PyLong_NumBits. pickle.py: Fixed stupid bug in save_long(): When proto is 2, it wrote LONG1 or LONG4, but forgot to return then -- it went on to append the proto 1 LONG opcode too. Fixed equally stupid cancelling bugs in load_long1() and load_long4(): they *returned* the unpickled long instead of pushing it on the stack. The return values were ignored. Tests passed before only because save_long() pickled the long twice. Fixed bugs in encode_long(). Noted that decode_long() is quadratic-time despite our hopes, because long(string, 16) is still quadratic-time in len(string). It's hex() that's linear-time. I don't know a way to make decode_long() linear-time in Python, short of maybe transforming the 256's-complement bytes into marshal's funky internal format, and letting marshal decode that. It would be more valuable to make long(string, 16) linear time. pickletester.py: Added a global "protocols" vector so tests can try all the protocols in a sane way. Changed test_ints() and test_unicode() to do so. Added a new test_long(), but the tail end of it is disabled because it "takes forever" under pickle.py (but runs very quickly under cPickle: cPickle proto 2 for longs is linear-time). Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** pickletester.py 1 Feb 2003 02:16:36 -0000 1.31 --- pickletester.py 2 Feb 2003 02:57:52 -0000 1.32 *************** *** 2,5 **** --- 2,10 ---- from test.test_support import TestFailed, have_unicode, TESTFN + # Tests that try a number of pickle protocols should have a + # for proto in protocols: + # kind of outer loop. Bump the 3 to 4 if/when protocol 3 is invented. + protocols = range(3) + class C: def __cmp__(self, other): *************** *** 29,32 **** --- 34,40 ---- __metaclass__ = metaclass + # DATA and BINDATA are the protocol 0 and protocol 1 pickles of the object + # returned by create_data(). + # break into multiple strings to avoid confusing font-lock-mode DATA = """(lp1 *************** *** 211,228 **** endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'), unicode('<\n>'), unicode('<\\>')] ! for u in endcases: ! p = self.dumps(u) ! u2 = self.loads(p) ! self.assertEqual(u2, u) def test_ints(self): import sys ! n = sys.maxint ! while n: ! for expected in (-n, n): ! s = self.dumps(expected) ! n2 = self.loads(s) ! self.assertEqual(expected, n2) ! n = n >> 1 def test_maxint64(self): --- 219,238 ---- endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'), unicode('<\n>'), unicode('<\\>')] ! for proto in protocols: ! for u in endcases: ! p = self.dumps(u, proto) ! u2 = self.loads(p) ! self.assertEqual(u2, u) def test_ints(self): import sys ! for proto in protocols: ! n = sys.maxint ! while n: ! for expected in (-n, n): ! s = self.dumps(expected, proto) ! n2 = self.loads(s) ! self.assertEqual(expected, n2) ! n = n >> 1 def test_maxint64(self): *************** *** 235,238 **** --- 245,276 ---- data = 'I' + str(maxint64) + 'JUNK\n.' self.assertRaises(ValueError, self.loads, data) + + def test_long(self): + for proto in protocols: + # 256 bytes is where LONG4 begins + for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257: + nbase = 1L << nbits + for npos in nbase-1, nbase, nbase+1: + for n in npos, -npos: + pickle = self.dumps(n, proto) + got = self.loads(pickle) + self.assertEqual(n, got) + # Try a monster. This is quadratic-time in protos 0 & 1, so don't + # bother with those. + # XXX Damn. pickle.py is still quadratic-time here, due to + # XXX long(string, 16). cPickle runs this in an eyeblink, but I + # XXX gave up waiting for pickle.py to get beyond "loading". Giving + # XXX up for now. + return + print "building long" + nbase = long("deadbeeffeedface", 16) + nbase += nbase << 1000000 + for n in nbase, -nbase: + print "dumping" + p = self.dumps(n, 2) + print "loading" + got = self.loads(p) + print "checking" + self.assertEqual(n, got) def test_reduce(self): From tim_one@users.sourceforge.net Sun Feb 2 02:57:55 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 18:57:55 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.150,1.151 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv8448/Objects Modified Files: longobject.c Log Message: cPickle.c: Full support for the new LONG1 and LONG4. Added comments. Assorted code cleanups; e.g., sizeof(char) is 1 by definition, so there's no need to do things like multiply by sizeof(char) in hairy malloc arguments. Fixed an undetected-overflow bug in readline_file(). longobject.c: Fixed a really stupid bug in the new _PyLong_NumBits. pickle.py: Fixed stupid bug in save_long(): When proto is 2, it wrote LONG1 or LONG4, but forgot to return then -- it went on to append the proto 1 LONG opcode too. Fixed equally stupid cancelling bugs in load_long1() and load_long4(): they *returned* the unpickled long instead of pushing it on the stack. The return values were ignored. Tests passed before only because save_long() pickled the long twice. Fixed bugs in encode_long(). Noted that decode_long() is quadratic-time despite our hopes, because long(string, 16) is still quadratic-time in len(string). It's hex() that's linear-time. I don't know a way to make decode_long() linear-time in Python, short of maybe transforming the 256's-complement bytes into marshal's funky internal format, and letting marshal decode that. It would be more valuable to make long(string, 16) linear time. pickletester.py: Added a global "protocols" vector so tests can try all the protocols in a sane way. Changed test_ints() and test_unicode() to do so. Added a new test_long(), but the tail end of it is disabled because it "takes forever" under pickle.py (but runs very quickly under cPickle: cPickle proto 2 for longs is linear-time). Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.150 retrieving revision 1.151 diff -C2 -d -r1.150 -r1.151 *** longobject.c 31 Jan 2003 21:45:13 -0000 1.150 --- longobject.c 2 Feb 2003 02:57:53 -0000 1.151 *************** *** 265,269 **** { PyLongObject *v = (PyLongObject *)vv; ! const int ndigits = v->ob_size; assert(v != NULL); --- 265,269 ---- { PyLongObject *v = (PyLongObject *)vv; ! const int ndigits = ABS(v->ob_size); assert(v != NULL); *************** *** 271,275 **** assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); ! return ndigits == 0 ? 0 : (ndigits < 0 ? -1 : 1); } --- 271,275 ---- assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); ! return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1); } From tim_one@users.sourceforge.net Sun Feb 2 02:57:55 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 18:57:55 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.106,2.107 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv8448/Modules Modified Files: cPickle.c Log Message: cPickle.c: Full support for the new LONG1 and LONG4. Added comments. Assorted code cleanups; e.g., sizeof(char) is 1 by definition, so there's no need to do things like multiply by sizeof(char) in hairy malloc arguments. Fixed an undetected-overflow bug in readline_file(). longobject.c: Fixed a really stupid bug in the new _PyLong_NumBits. pickle.py: Fixed stupid bug in save_long(): When proto is 2, it wrote LONG1 or LONG4, but forgot to return then -- it went on to append the proto 1 LONG opcode too. Fixed equally stupid cancelling bugs in load_long1() and load_long4(): they *returned* the unpickled long instead of pushing it on the stack. The return values were ignored. Tests passed before only because save_long() pickled the long twice. Fixed bugs in encode_long(). Noted that decode_long() is quadratic-time despite our hopes, because long(string, 16) is still quadratic-time in len(string). It's hex() that's linear-time. I don't know a way to make decode_long() linear-time in Python, short of maybe transforming the 256's-complement bytes into marshal's funky internal format, and letting marshal decode that. It would be more valuable to make long(string, 16) linear time. pickletester.py: Added a global "protocols" vector so tests can try all the protocols in a sane way. Changed test_ints() and test_unicode() to do so. Added a new test_long(), but the tail end of it is disabled because it "takes forever" under pickle.py (but runs very quickly under cPickle: cPickle proto 2 for longs is linear-time). Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.106 retrieving revision 2.107 diff -C2 -d -r2.106 -r2.107 *** cPickle.c 1 Feb 2003 16:45:06 -0000 2.106 --- cPickle.c 2 Feb 2003 02:57:52 -0000 2.107 *************** *** 465,469 **** static int ! read_file(Unpicklerobject *self, char **s, int n) { size_t nbytesread; --- 465,469 ---- static int ! read_file(Unpicklerobject *self, char **s, int n) { size_t nbytesread; *************** *** 473,477 **** size = ((n < 32) ? 32 : n); ! if (!( self->buf = (char *)malloc(size * sizeof(char)))) { PyErr_NoMemory(); return -1; --- 473,477 ---- size = ((n < 32) ? 32 : n); ! if (!( self->buf = (char *)malloc(size))) { PyErr_NoMemory(); return -1; *************** *** 481,490 **** } else if (n > self->buf_size) { ! self->buf = (char *)realloc(self->buf, n * sizeof(char)); if (!self->buf) { PyErr_NoMemory(); return -1; } - self->buf_size = n; } --- 481,489 ---- } else if (n > self->buf_size) { ! self->buf = (char *)realloc(self->buf, n); if (!self->buf) { PyErr_NoMemory(); return -1; } self->buf_size = n; } *************** *** 515,523 **** if (self->buf_size == 0) { ! if (!( self->buf = (char *)malloc(40 * sizeof(char)))) { PyErr_NoMemory(); return -1; } - self->buf_size = 40; } --- 514,521 ---- if (self->buf_size == 0) { ! if (!( self->buf = (char *)malloc(40))) { PyErr_NoMemory(); return -1; } self->buf_size = 40; } *************** *** 525,528 **** --- 523,527 ---- i = 0; while (1) { + int bigger; for (; i < (self->buf_size - 1); i++) { if (feof(self->fp) || *************** *** 533,544 **** } } ! self->buf = (char *)realloc(self->buf, ! (self->buf_size * 2) * sizeof(char)); if (!self->buf) { PyErr_NoMemory(); return -1; } ! ! self->buf_size *= 2; } } --- 532,546 ---- } } ! bigger = self->buf_size << 1; ! if (bigger <= 0) { /* overflow */ ! PyErr_NoMemory(); ! return -1; ! } ! self->buf = (char *)realloc(self->buf, bigger); if (!self->buf) { PyErr_NoMemory(); return -1; } ! self->buf_size = bigger; } } *************** *** 621,632 **** } ! static char * ! pystrndup(char *s, int l) { ! char *r; ! if (!( r=malloc((l+1)*sizeof(char)))) return (char*)PyErr_NoMemory(); ! memcpy(r,s,l); ! r[l]=0; return r; } --- 623,638 ---- } ! /* Copy the first n bytes from s into newly malloc'ed memory, plus a ! * trailing 0 byte. Return a pointer to that, or NULL if out of memory. ! * The caller is responsible for free()'ing the return value. ! */ static char * ! pystrndup(char *s, int n) { ! char *r = (char *)malloc(n+1); ! if (r == NULL) ! return (char*)PyErr_NoMemory(); ! memcpy(r, s, n); ! r[n] = 0; return r; } *************** *** 1013,1021 **** save_long(Picklerobject *self, PyObject *args) { ! int size, res = -1; ! PyObject *repr = 0; static char l = LONG; if (!( repr = PyObject_Repr(args))) goto finally; --- 1019,1109 ---- save_long(Picklerobject *self, PyObject *args) { ! int size; ! int res = -1; ! PyObject *repr = NULL; static char l = LONG; + if (self->proto >= 2) { + /* Linear-time pickling. */ + size_t nbits; + size_t nbytes; + unsigned char *pdata; + char c_str[5]; + int i; + int sign = _PyLong_Sign(args); + + if (sign == 0) { + /* It's 0 -- an empty bytestring. */ + c_str[0] = LONG1; + c_str[1] = 0; + i = self->write_func(self, c_str, 2); + if (i < 0) goto finally; + res = 0; + goto finally; + } + nbits = _PyLong_NumBits(args); + if (nbits == (size_t)-1 && PyErr_Occurred()) + goto finally; + /* How many bytes do we need? There are nbits >> 3 full + * bytes of data, and nbits & 7 leftover bits. If there + * are any leftover bits, then we clearly need another + * byte. Wnat's not so obvious is that we *probably* + * need another byte even if there aren't any leftovers: + * the most-significant bit of the most-significant byte + * acts like a sign bit, and it's usually got a sense + * opposite of the one we need. The exception is longs + * of the form -(2**(8*j-1)) for j > 0. Such a long is + * its own 256's-complement, so has the right sign bit + * even without the extra byte. That's a pain to check + * for in advance, though, so we always grab an extra + * byte at the start, and cut it back later if possible. + */ + nbytes = (nbits >> 3) + 1; + if ((int)nbytes < 0 || (size_t)(int)nbytes != nbytes) { + PyErr_SetString(PyExc_OverflowError, "long too large " + "to pickle"); + goto finally; + } + repr = PyString_FromStringAndSize(NULL, (int)nbytes); + if (repr == NULL) goto finally; + pdata = (unsigned char *)PyString_AS_STRING(repr); + i = _PyLong_AsByteArray((PyLongObject *)args, + pdata, nbytes, + 1 /* little endian */, 1 /* signed */); + if (i < 0) goto finally; + /* If the long is negative, this may be a byte more than + * needed. This is so iff the MSB is all redundant sign + * bits. + */ + if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff && + (pdata[nbytes - 2] & 0x80) != 0) + --nbytes; + + if (nbytes < 256) { + c_str[0] = LONG1; + c_str[1] = (char)nbytes; + size = 2; + } + else { + c_str[0] = LONG4; + size = (int)nbytes; + for (i = 1; i < 5; i++) { + c_str[i] = (char)(size & 0xff); + size >>= 8; + } + size = 5; + } + i = self->write_func(self, c_str, size); + if (i < 0) goto finally; + i = self->write_func(self, (char *)pdata, (int)nbytes); + if (i < 0) goto finally; + res = 0; + goto finally; + } + + /* proto < 2: write the repr and newline. This is quadratic-time + * (in the number of digits), in both directions. + */ if (!( repr = PyObject_Repr(args))) goto finally; *************** *** 1039,1043 **** finally: Py_XDECREF(repr); - return res; } --- 1127,1130 ---- *************** *** 2688,2694 **** } ! static long ! calc_binint(char *s, int x) { unsigned char c; --- 2775,2785 ---- } ! /* s contains x bytes of a little-endian integer. Return its value as a ! * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian ! * int, but when x is 4 it's a signed one. This is an historical source ! * of x-platform bugs. ! */ static long ! calc_binint(char *s, int x) { unsigned char c; *************** *** 2787,2790 **** --- 2878,2920 ---- } + /* 'size' bytes contain the # of bytes of little-endian 256's-complement + * data following. + */ + static int + load_counted_long(Unpicklerobject *self, int size) + { + int i; + char *nbytes; + unsigned char *pdata; + PyObject *along; + + assert(size == 1 || size == 4); + i = self->read_func(self, &nbytes, size); + if (i < 0) return -1; + + size = calc_binint(nbytes, size); + if (size < 0) { + /* Corrupt or hostile pickle -- we never write one like + * this. + */ + PyErr_SetString(PyExc_ValueError, "LONG pickle has negative " + "byte count"); + return -1; + } + + if (size == 0) + along = PyLong_FromLong(0L); + else { + /* Read the raw little-endian bytes & convert. */ + i = self->read_func(self, &(char *)pdata, size); + if (i < 0) return -1; + along = _PyLong_FromByteArray(pdata, (size_t)size, + 1 /* little endian */, 1 /* signed */); + } + if (along == NULL) + return -1; + PDATA_PUSH(self->stack, along, -1); + return 0; + } static int *************** *** 3782,3785 **** --- 3912,3925 ---- case LONG: if (load_long(self) < 0) + break; + continue; + + case LONG1: + if (load_counted_long(self, 1) < 0) + break; + continue; + + case LONG4: + if (load_counted_long(self, 4) < 0) break; continue; From fdrake@users.sourceforge.net Sun Feb 2 03:54:19 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Sat, 01 Feb 2003 19:54:19 -0800 Subject: [Python-checkins] python/dist/src/Modules pyexpat.c,2.79,2.80 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv22705/Modules Modified Files: pyexpat.c Log Message: Fix memory leak: free memory storing the content model passed to the ElementDeclHandler by Expat. Fixes SF bug #676990. Index: pyexpat.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/pyexpat.c,v retrieving revision 2.79 retrieving revision 2.80 diff -C2 -d -r2.79 -r2.80 *** pyexpat.c 21 Jan 2003 11:09:21 -0000 2.79 --- pyexpat.c 2 Feb 2003 03:54:17 -0000 2.80 *************** *** 684,716 **** } ! static PyObject * ! conv_content_model_utf8(XML_Content * const model) { ! return conv_content_model(model, conv_string_to_utf8); ! } ! #ifdef Py_USING_UNICODE ! static PyObject * ! conv_content_model_unicode(XML_Content * const model) ! { ! return conv_content_model(model, conv_string_to_unicode); ! } ! VOID_HANDLER(ElementDecl, ! (void *userData, ! const XML_Char *name, ! XML_Content *model), ! ("NO&", ! string_intern(self, name), ! (self->returns_unicode ? conv_content_model_unicode ! : conv_content_model_utf8),model)) #else ! VOID_HANDLER(ElementDecl, ! (void *userData, ! const XML_Char *name, ! XML_Content *model), ! ("NO&", ! string_intern(self, name), conv_content_model_utf8,model)) #endif VOID_HANDLER(AttlistDecl, --- 684,740 ---- } ! static void ! my_ElementDeclHandler(void *userData, ! const XML_Char *name, ! XML_Content *model) { ! xmlparseobject *self = (xmlparseobject *)userData; ! PyObject *args = NULL; ! if (have_handler(self, ElementDecl)) { ! PyObject *rv = NULL; ! PyObject *modelobj, *nameobj; ! if (flush_character_buffer(self) < 0) ! goto finally; ! #ifdef Py_USING_UNICODE ! modelobj = conv_content_model(model, ! (self->returns_unicode ! ? conv_string_to_unicode ! : conv_string_to_utf8)); #else ! modelobj = conv_content_model(model, conv_string_to_utf8); #endif + if (modelobj == NULL) { + flag_error(self); + goto finally; + } + nameobj = string_intern(self, name); + if (nameobj == NULL) { + Py_DECREF(modelobj); + flag_error(self); + goto finally; + } + args = Py_BuildValue("NN", string_intern(self, name), modelobj); + if (args == NULL) { + Py_DECREF(modelobj); + flag_error(self); + goto finally; + } + self->in_callback = 1; + rv = call_with_frame(getcode(ElementDecl, "ElementDecl", __LINE__), + self->handlers[ElementDecl], args); + self->in_callback = 0; + if (rv == NULL) { + flag_error(self); + goto finally; + } + Py_DECREF(rv); + } + finally: + Py_XDECREF(args); + XML_FreeContentModel(self->itself, model); + return; + } VOID_HANDLER(AttlistDecl, From tim_one@users.sourceforge.net Sun Feb 2 07:51:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 23:51:34 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv7771/Lib/test Modified Files: pickletester.py Log Message: long(string, base) now takes time linear in len(string) when base is a power of 2. Enabled the tail end of test_long() in pickletester.py because it no longer takes forever when run from test_pickle.py. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** pickletester.py 2 Feb 2003 02:57:52 -0000 1.32 --- pickletester.py 2 Feb 2003 07:51:32 -0000 1.33 *************** *** 248,252 **** def test_long(self): for proto in protocols: ! # 256 bytes is where LONG4 begins for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257: nbase = 1L << nbits --- 248,252 ---- def test_long(self): for proto in protocols: ! # 256 bytes is where LONG4 begins. for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257: nbase = 1L << nbits *************** *** 258,275 **** # Try a monster. This is quadratic-time in protos 0 & 1, so don't # bother with those. - # XXX Damn. pickle.py is still quadratic-time here, due to - # XXX long(string, 16). cPickle runs this in an eyeblink, but I - # XXX gave up waiting for pickle.py to get beyond "loading". Giving - # XXX up for now. - return - print "building long" nbase = long("deadbeeffeedface", 16) nbase += nbase << 1000000 for n in nbase, -nbase: - print "dumping" p = self.dumps(n, 2) - print "loading" got = self.loads(p) - print "checking" self.assertEqual(n, got) --- 258,266 ---- From tim_one@users.sourceforge.net Sun Feb 2 07:51:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 23:51:34 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.138,1.139 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv7771/Lib Modified Files: pickle.py Log Message: long(string, base) now takes time linear in len(string) when base is a power of 2. Enabled the tail end of test_long() in pickletester.py because it no longer takes forever when run from test_pickle.py. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.138 retrieving revision 1.139 diff -C2 -d -r1.138 -r1.139 *** pickle.py 2 Feb 2003 02:57:52 -0000 1.138 --- pickle.py 2 Feb 2003 07:51:32 -0000 1.139 *************** *** 1428,1434 **** return binary[::-1] - # XXX OOPS! This is still quadratic-time. While hex(n) is linear-time - # XXX in the # of digits in n, long(s, 16) is still quadratic-time - # XXX in len(s). def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. --- 1428,1431 ---- *************** *** 1454,1458 **** return 0L ashex = _binascii.hexlify(data[::-1]) ! n = long(ashex, 16) # quadratic time if data[-1] >= '\x80': n -= 1L << (nbytes * 8) --- 1451,1455 ---- return 0L ashex = _binascii.hexlify(data[::-1]) ! n = long(ashex, 16) # quadratic time before Python 2.3; linear now if data[-1] >= '\x80': n -= 1L << (nbytes * 8) From tim_one@users.sourceforge.net Sun Feb 2 07:51:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 23:51:34 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.635,1.636 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv7771/Misc Modified Files: NEWS Log Message: long(string, base) now takes time linear in len(string) when base is a power of 2. Enabled the tail end of test_long() in pickletester.py because it no longer takes forever when run from test_pickle.py. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.635 retrieving revision 1.636 diff -C2 -d -r1.635 -r1.636 *** NEWS 1 Feb 2003 02:54:15 -0000 1.635 --- NEWS 2 Feb 2003 07:51:32 -0000 1.636 *************** *** 13,16 **** --- 13,19 ---- ----------------- + - long(string, base) takes time linear in len(string) when base is a power + of 2 now. It used to take time quadratic in len(string). + - filter returns now Unicode results for Unicode arguments. From tim_one@users.sourceforge.net Sun Feb 2 07:51:35 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 01 Feb 2003 23:51:35 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.151,1.152 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv7771/Objects Modified Files: longobject.c Log Message: long(string, base) now takes time linear in len(string) when base is a power of 2. Enabled the tail end of test_long() in pickletester.py because it no longer takes forever when run from test_pickle.py. Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.151 retrieving revision 1.152 diff -C2 -d -r1.151 -r1.152 *** longobject.c 2 Feb 2003 02:57:53 -0000 1.151 --- longobject.c 2 Feb 2003 07:51:32 -0000 1.152 *************** *** 1091,1094 **** --- 1091,1183 ---- } + /* *str points to the first digit in a string of base base digits. base + * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first + * non-digit (which may be *str!). A normalized long is returned. + * The point to this routine is that it takes time linear in the number of + * string characters. + */ + static PyLongObject * + long_from_binary_base(char **str, int base) + { + char *p = *str; + char *start = p; + int bits_per_char; + int n; + PyLongObject *z; + twodigits accum; + int bits_in_accum; + digit *pdigit; + + assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); + n = base; + for (bits_per_char = -1; n; ++bits_per_char) + n >>= 1; + /* n <- total # of bits needed, while setting p to end-of-string */ + n = 0; + for (;;) { + int k = -1; + char ch = *p; + + if (ch <= '9') + k = ch - '0'; + else if (ch >= 'a') + k = ch - 'a' + 10; + else if (ch >= 'A') + k = ch - 'A' + 10; + if (k < 0 || k >= base) + break; + n += bits_per_char; + if (n < 0) { + PyErr_SetString(PyExc_ValueError, + "long string too large to convert"); + return NULL; + } + ++p; + } + *str = p; + /* n <- # of Python digits needed, = ceiling(n/SHIFT). */ + n = (n + SHIFT - 1) / SHIFT; + z = _PyLong_New(n); + if (z == NULL) + return NULL; + /* Read string from right, and fill in long from left; i.e., + * from least to most significant in both. + */ + accum = 0; + bits_in_accum = 0; + pdigit = z->ob_digit; + while (--p >= start) { + unsigned char ch = (unsigned char)*p; + digit k; + + if (ch <= '9') + k = ch - '0'; + else if (ch >= 'a') + k = ch - 'a' + 10; + else { + assert(ch >= 'A'); + k = ch - 'A' + 10; + } + assert(k >= 0 && k <= base); + accum |= k << bits_in_accum; + bits_in_accum += bits_per_char; + if (bits_in_accum >= SHIFT) { + *pdigit++ = (digit)(accum & MASK); + assert(pdigit - z->ob_digit <= n); + accum >>= SHIFT; + bits_in_accum -= SHIFT; + assert(bits_in_accum < SHIFT); + } + } + if (bits_in_accum) { + assert(bits_in_accum <= SHIFT); + *pdigit++ = (digit)accum; + assert(pdigit - z->ob_digit <= n); + } + while (pdigit - z->ob_digit < n) + *pdigit++ = 0; + return long_normalize(z); + } + PyObject * PyLong_FromString(char *str, char **pend, int base) *************** *** 1123,1143 **** if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) str += 2; - z = _PyLong_New(0); start = str; ! for ( ; z != NULL; ++str) { ! int k = -1; ! PyLongObject *temp; ! if (*str <= '9') ! k = *str - '0'; ! else if (*str >= 'a') ! k = *str - 'a' + 10; ! else if (*str >= 'A') ! k = *str - 'A' + 10; ! if (k < 0 || k >= base) ! break; ! temp = muladd1(z, (digit)base, (digit)k); ! Py_DECREF(z); ! z = temp; } if (z == NULL) --- 1212,1236 ---- if (base == 16 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) str += 2; start = str; ! if ((base & (base - 1)) == 0) ! z = long_from_binary_base(&str, base); ! else { ! z = _PyLong_New(0); ! for ( ; z != NULL; ++str) { ! int k = -1; ! PyLongObject *temp; ! if (*str <= '9') ! k = *str - '0'; ! else if (*str >= 'a') ! k = *str - 'a' + 10; ! else if (*str >= 'A') ! k = *str - 'A' + 10; ! if (k < 0 || k >= base) ! break; ! temp = muladd1(z, (digit)base, (digit)k); ! Py_DECREF(z); ! z = temp; ! } } if (z == NULL) From tim_one@users.sourceforge.net Sun Feb 2 08:05:35 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 00:05:35 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.152,1.153 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv10850/Objects Modified Files: longobject.c Log Message: Tightened a too-generous assert. Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.152 retrieving revision 1.153 diff -C2 -d -r1.152 -r1.153 *** longobject.c 2 Feb 2003 07:51:32 -0000 1.152 --- longobject.c 2 Feb 2003 08:05:32 -0000 1.153 *************** *** 1159,1163 **** k = ch - 'A' + 10; } ! assert(k >= 0 && k <= base); accum |= k << bits_in_accum; bits_in_accum += bits_per_char; --- 1159,1163 ---- k = ch - 'A' + 10; } ! assert(k < base); accum |= k << bits_in_accum; bits_in_accum += bits_per_char; From davecole@users.sourceforge.net Sun Feb 2 09:59:26 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 01:59:26 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv10853 Modified Files: csv.py Log Message: Added reply comment to andrewm about lineterminator strangeness. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** csv.py 31 Jan 2003 21:30:20 -0000 1.8 --- csv.py 2 Feb 2003 09:59:24 -0000 1.9 *************** *** 11,14 **** --- 11,16 ---- # XXX - andrewm - This is causing weird errors from the _csv module - needs # investigation: + # XXX - davecole - I just noticed that I was saving a string arg 's' + # instead of an object arg 'O'. What do you see now? # lineterminator = '\r\n' quoting = QUOTE_MINIMAL From davecole@users.sourceforge.net Sun Feb 2 10:02:42 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 02:02:42 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv10998 Modified Files: _csv.c Log Message: Change comments which refer to "MS double quote" to doublequote. Fixed stupid bug (introduced while porting Object Craft module) where p.join(['ab"cdef"h']) did not obey doublequote. Fixed PyArg_ParseTupleAndKeywords() type character for lineterminator - was 's', should have been 'O'. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** _csv.c 30 Jan 2003 13:36:06 -0000 1.4 --- _csv.c 2 Feb 2003 10:02:40 -0000 1.5 *************** *** 212,216 **** else if (c == self->quotechar) { if (self->doublequote) { ! /* microsoft style double quotes; " represented by "" */ self->state = QUOTE_IN_QUOTED_FIELD; } --- 212,216 ---- else if (c == self->quotechar) { if (self->doublequote) { ! /* doublequote; " represented by "" */ self->state = QUOTE_IN_QUOTED_FIELD; } *************** *** 235,239 **** case QUOTE_IN_QUOTED_FIELD: ! /* microsoft double quotes - seen a quote in an quoted field */ if (self->have_quotechar && c == self->quotechar) { /* save "" as " */ --- 235,239 ---- case QUOTE_IN_QUOTED_FIELD: ! /* doublequote - seen a quote in an quoted field */ if (self->have_quotechar && c == self->quotechar) { /* save "" as " */ *************** *** 404,411 **** if (c == '\0') break; ! /* If in MS double quote mode we escape quote chars with a * quote. */ ! if (c == self->have_quotechar && self->doublequote) { if (copy_phase) self->rec[rec_len] = self->quotechar; --- 404,412 ---- if (c == '\0') break; ! /* If in doublequote mode we escape quote chars with a * quote. */ ! if (self->have_quotechar ! && c == self->quotechar && self->doublequote) { if (copy_phase) self->rec[rec_len] = self->quotechar; *************** *** 774,778 **** quotechar = escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|OcOisiiii", keywords, "echar, &self->delimiter, --- 775,779 ---- quotechar = escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|OcOiOiiii", keywords, "echar, &self->delimiter, From davecole@users.sourceforge.net Sun Feb 2 10:54:01 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 02:54:01 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv25862 Modified Files: csv.py Log Message: Added QUOTE_NONE - I know I said it wasn't necessary. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** csv.py 2 Feb 2003 09:59:24 -0000 1.9 --- csv.py 2 Feb 2003 10:53:59 -0000 1.10 *************** *** 2,6 **** from _csv import Error as CSVError ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC = range(3) class Dialect: --- 2,6 ---- from _csv import Error as CSVError ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) class Dialect: From davecole@users.sourceforge.net Sun Feb 2 11:01:51 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:01:51 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv28709 Modified Files: _csv.c Log Message: Implemented all quoting styles. Added code to return quotechar and escapechar as None when have_quotechar and have_escapechar false respectively. Added checks on the values for quoting. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** _csv.c 2 Feb 2003 10:02:40 -0000 1.5 --- _csv.c 2 Feb 2003 11:01:46 -0000 1.6 *************** *** 25,29 **** typedef enum { ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC } QuoteStyle; --- 25,29 ---- typedef enum { ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE } QuoteStyle; *************** *** 393,402 **** rec_len++; } ! /* We only know about quoted in the copy phase. */ ! if (copy_phase && *quoted) { ! self->rec[rec_len] = self->quotechar; rec_len++; } for (i = 0;; i++) { char c = field[i]; --- 393,419 ---- rec_len++; } ! /* Handle preceding quote. */ ! switch (self->quoting) { ! case QUOTE_ALL: ! *quoted = 1; ! if (copy_phase) ! self->rec[rec_len] = self->quotechar; rec_len++; + break; + case QUOTE_MINIMAL: + case QUOTE_NONNUMERIC: + /* We only know about quoted in the copy phase. + */ + if (copy_phase && *quoted) { + self->rec[rec_len] = self->quotechar; + rec_len++; + } + break; + case QUOTE_NONE: + break; } + /* Copy/count field data. + */ for (i = 0;; i++) { char c = field[i]; *************** *** 413,417 **** *quoted = 1; rec_len++; ! } /* Some special characters need to be escaped. If we have a * quote character switch to quoted field instead of escaping --- 430,437 ---- *quoted = 1; rec_len++; ! } else if (self->quoting == QUOTE_NONNUMERIC ! && !*quoted && !isdigit(c)) ! *quoted = 1; ! /* Some special characters need to be escaped. If we have a * quote character switch to quoted field instead of escaping *************** *** 421,425 **** && (c == self->delimiter || c == self->escapechar || c == '\n' || c == '\r')) { ! if (self->have_quotechar) *quoted = 1; else if (self->escapechar) { --- 441,446 ---- && (c == self->delimiter || c == self->escapechar || c == '\n' || c == '\r')) { ! if (self->have_quotechar ! && self->quoting != QUOTE_NONE) *quoted = 1; else if (self->escapechar) { *************** *** 428,431 **** --- 449,456 ---- rec_len++; } + else { + raise_exception("delimter must be quoted or escaped"); + return -1; + } } /* Copy field character into record buffer. *************** *** 464,467 **** --- 489,494 ---- quoted = 0; rec_len = join_append_data(self, field, quote_empty, "ed, 0); + if (rec_len < 0) + return 0; /* grow record buffer if necessary */ *************** *** 599,602 **** --- 626,635 ---- PyObject *rv; + if ((strcmp(name, "quotechar") == 0 && !self->have_quotechar) + || (strcmp(name, "escapechar") == 0 && !self->have_escapechar)) { + Py_INCREF(Py_None); + return Py_None; + } + rv = PyMember_Get((char *)self, Parser_memberlist, name); if (rv) *************** *** 615,623 **** if (v == Py_None) { - *attr = 0; - *have_attr = 0; - return 0; - } - else if (PyInt_Check(v) && PyInt_AsLong(v) == 0) { *have_attr = 0; *attr = 0; --- 648,651 ---- *************** *** 642,652 **** return -1; } ! if (strcmp(name, "delimiter") == 0) { ! int have_delimiter; ! ! return _set_char_attr(&self->delimiter, ! &have_delimiter, v); ! } ! else if (strcmp(name, "quotechar") == 0) return _set_char_attr(&self->quotechar, &self->have_quotechar, v); --- 670,674 ---- return -1; } ! if (strcmp(name, "quotechar") == 0) return _set_char_attr(&self->quotechar, &self->have_quotechar, v); *************** *** 654,657 **** --- 676,691 ---- return _set_char_attr(&self->escapechar, &self->have_escapechar, v); + else if (strcmp(name, "quoting") == 0 && PyInt_Check(v)) { + int n = PyInt_AsLong(v); + + if (n < 0 || n > QUOTE_NONE) { + PyErr_BadArgument(); + return -1; + } + if (n == QUOTE_NONE) + self->have_quotechar = 0; + self->quoting = n; + return 0; + } else return PyMember_Set((char *)self, Parser_memberlist, name, v); *************** *** 785,790 **** &self->have_quotechar, quotechar) && !_set_char_attr(&self->escapechar, ! &self->have_escapechar, escapechar)) ! return (PyObject*)self; Py_DECREF(self); --- 819,833 ---- &self->have_quotechar, quotechar) && !_set_char_attr(&self->escapechar, ! &self->have_escapechar, escapechar)) { ! if (self->quoting < 0 || self->quoting > QUOTE_NONE) ! PyErr_SetString(PyExc_ValueError, "bad quoting value"); ! else { ! if (self->quoting == QUOTE_NONE) ! self->have_quotechar = 0; ! else if (!self->have_quotechar) ! self->quoting = QUOTE_NONE; ! return (PyObject*)self; ! } ! } Py_DECREF(self); From davecole@users.sourceforge.net Sun Feb 2 11:06:04 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:06:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv350 Modified Files: _csv.c Log Message: Spelling errors in exception text. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** _csv.c 2 Feb 2003 11:01:46 -0000 1.6 --- _csv.c 2 Feb 2003 11:06:01 -0000 1.7 *************** *** 319,323 **** } self->had_parse_error = 1; ! return raise_exception("Newline inside string"); } if (c == '\n') { --- 319,323 ---- } self->had_parse_error = 1; ! return raise_exception("newline inside string"); } if (c == '\n') { *************** *** 327,331 **** break; self->had_parse_error = 1; ! return raise_exception("Newline inside string"); } parse_process_char(self, c); --- 327,331 ---- break; self->had_parse_error = 1; ! return raise_exception("newline inside string"); } parse_process_char(self, c); *************** *** 450,454 **** } else { ! raise_exception("delimter must be quoted or escaped"); return -1; } --- 450,454 ---- } else { ! raise_exception("delimiter must be quoted or escaped"); return -1; } From davecole@users.sourceforge.net Sun Feb 2 11:14:30 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:14:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv2429 Modified Files: _csv.c Log Message: Implemented skipinitialspace. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** _csv.c 2 Feb 2003 11:06:01 -0000 1.7 --- _csv.c 2 Feb 2003 11:14:28 -0000 1.8 *************** *** 163,166 **** --- 163,169 ---- parse_save_field(self); } + else if (c == ' ' && self->skipinitialspace) + /* ignore space at start of field */ + ; else { /* begin new unquoted field */ From davecole@users.sourceforge.net Sun Feb 2 11:55:43 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:55:43 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv11819 Modified Files: _csv.c Log Message: Fixed refcount bug in constructor regarding lineterminator string. Implemented lineterminator functionality - appends lineterminator to end of joined record. Not sure what to do with \n which do not match the lineterminator string... Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** _csv.c 2 Feb 2003 11:14:28 -0000 1.8 --- _csv.c 2 Feb 2003 11:55:41 -0000 1.9 *************** *** 486,499 **** static int ! join_append(ParserObj *self, char *field, int quote_empty) { - int rec_len, quoted; - - quoted = 0; - rec_len = join_append_data(self, field, quote_empty, "ed, 0); - if (rec_len < 0) - return 0; - - /* grow record buffer if necessary */ if (rec_len > self->rec_size) { if (self->rec_size == 0) { --- 486,491 ---- static int ! join_check_rec_size(ParserObj *self, int rec_len) { if (rec_len > self->rec_size) { if (self->rec_size == 0) { *************** *** 514,517 **** --- 506,525 ---- } } + return 1; + } + + static int + join_append(ParserObj *self, char *field, int quote_empty) + { + int rec_len, quoted; + + quoted = 0; + rec_len = join_append_data(self, field, quote_empty, "ed, 0); + if (rec_len < 0) + return 0; + + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, rec_len)) + return 0; self->rec_len = join_append_data(self, field, quote_empty, "ed, 1); *************** *** 521,524 **** --- 529,550 ---- } + static int + join_append_lineterminator(ParserObj *self) + { + int terminator_len; + + terminator_len = PyString_Size(self->lineterminator); + + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, self->rec_len + terminator_len)) + return 0; + + memmove(self->rec + self->rec_len, + PyString_AsString(self->lineterminator), terminator_len); + self->rec_len += terminator_len; + + return 1; + } + static PyObject * join_string(ParserObj *self) *************** *** 548,551 **** --- 574,579 ---- return NULL; + /* Join all fields in internal buffer. + */ join_reset(self); for (i = 0; i < len; i++) { *************** *** 580,583 **** --- 608,616 ---- } + /* Add line terminator. + */ + if (!join_append_lineterminator(self)) + return 0; + return join_string(self); } *************** *** 691,694 **** --- 724,731 ---- return 0; } + else if (strcmp(name, "lineterminator") == 0 && !PyString_Check(v)) { + PyErr_BadArgument(); + return -1; + } else return PyMember_Set((char *)self, Parser_memberlist, name, v); *************** *** 788,792 **** self->have_escapechar = 0; self->skipinitialspace = 0; ! self->lineterminator = PyString_FromString("\r\n"); self->quoting = QUOTE_MINIMAL; self->doublequote = 1; --- 825,829 ---- self->have_escapechar = 0; self->skipinitialspace = 0; ! self->lineterminator = NULL; self->quoting = QUOTE_MINIMAL; self->doublequote = 1; *************** *** 796,799 **** --- 833,841 ---- self->state = START_RECORD; self->fields = PyList_New(0); + if (self->fields == NULL) { + Py_DECREF(self); + return NULL; + } + self->had_parse_error = 0; self->field = NULL; *************** *** 806,816 **** self->num_fields = 0; - if (self->lineterminator == NULL || self->fields == NULL) { - Py_DECREF(self); - return NULL; - } - quotechar = escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|OcOiOiiii", keywords, "echar, &self->delimiter, --- 848,853 ---- self->num_fields = 0; quotechar = escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|OcOiSiiii", keywords, "echar, &self->delimiter, *************** *** 823,826 **** --- 860,869 ---- && !_set_char_attr(&self->escapechar, &self->have_escapechar, escapechar)) { + if (self->lineterminator == NULL) + self->lineterminator = PyString_FromString("\r\n"); + else { + Py_INCREF(self->lineterminator); + } + if (self->quoting < 0 || self->quoting > QUOTE_NONE) PyErr_SetString(PyExc_ValueError, "bad quoting value"); From davecole@users.sourceforge.net Sun Feb 2 11:57:31 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:57:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv12500 Modified Files: csv.py Log Message: Implemented lineterminator in _csv. * Removed append of '\n' in csv.writer.write() * Fixed tests to look for records terminated by '\r\n'. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** csv.py 2 Feb 2003 10:53:59 -0000 1.10 --- csv.py 2 Feb 2003 11:57:28 -0000 1.11 *************** *** 9,17 **** escapechar = None skipinitialspace = False ! # XXX - andrewm - This is causing weird errors from the _csv module - needs ! # investigation: ! # XXX - davecole - I just noticed that I was saving a string arg 's' ! # instead of an object arg 'O'. What do you see now? ! # lineterminator = '\r\n' quoting = QUOTE_MINIMAL --- 9,13 ---- escapechar = None skipinitialspace = False ! lineterminator = '\r\n' quoting = QUOTE_MINIMAL *************** *** 75,79 **** except (TypeError, AttributeError): pass ! self.fileobj.write(self.parser.join(fields) + '\n') def writelines(self, lines): --- 71,75 ---- except (TypeError, AttributeError): pass ! self.fileobj.write(self.parser.join(fields)) def writelines(self, lines): From davecole@users.sourceforge.net Sun Feb 2 11:57:31 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 03:57:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv12500/test Modified Files: test_csv.py Log Message: Implemented lineterminator in _csv. * Removed append of '\n' in csv.writer.write() * Fixed tests to look for records terminated by '\r\n'. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_csv.py 31 Jan 2003 21:30:43 -0000 1.3 --- test_csv.py 2 Feb 2003 11:57:28 -0000 1.4 *************** *** 98,114 **** def test_single(self): ! self.writerAssertEqual([['abc']], 'abc\n') def test_simple(self): ! self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\n') def test_quotes(self): ! self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\n') def test_quote_fieldsep(self): ! self.writerAssertEqual([['abc,def']], '"abc,def"\n') def test_newlines(self): ! self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\n') class TestDictFields(unittest.TestCase): --- 98,114 ---- def test_single(self): ! self.writerAssertEqual([['abc']], 'abc\r\n') def test_simple(self): ! self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n') def test_quotes(self): ! self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n') def test_quote_fieldsep(self): ! self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') def test_newlines(self): ! self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') class TestDictFields(unittest.TestCase): *************** *** 118,122 **** fieldnames = ["f1", "f2", "f3"]) writer.write({"f1": 10, "f3": "abc"}) ! self.assertEqual(fileobj.getvalue(), "10,,abc\n") def test_no_fields(self): --- 118,122 ---- fieldnames = ["f1", "f2", "f3"]) writer.write({"f1": 10, "f3": "abc"}) ! self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") def test_no_fields(self): From davecole@users.sourceforge.net Sun Feb 2 12:05:10 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 04:05:10 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv14624 Modified Files: csv.py Log Message: Added doublequote to the default Dialect and reordered parameters to match the documentation in _csv. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** csv.py 2 Feb 2003 11:57:28 -0000 1.11 --- csv.py 2 Feb 2003 12:05:07 -0000 1.12 *************** *** 5,11 **** class Dialect: - quotechar = '"' delimiter = ',' escapechar = None skipinitialspace = False lineterminator = '\r\n' --- 5,12 ---- class Dialect: delimiter = ',' + quotechar = '"' escapechar = None + doublequote = True skipinitialspace = False lineterminator = '\r\n' From davecole@users.sourceforge.net Sun Feb 2 12:16:28 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 04:16:28 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv17084 Modified Files: _csv.c Log Message: Oops - forgot to check for '+-.' when quoting is QUOTE_NONNUMERIC. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** _csv.c 2 Feb 2003 11:55:41 -0000 1.9 --- _csv.c 2 Feb 2003 12:16:26 -0000 1.10 *************** *** 433,438 **** *quoted = 1; rec_len++; ! } else if (self->quoting == QUOTE_NONNUMERIC ! && !*quoted && !isdigit(c)) *quoted = 1; --- 433,438 ---- *quoted = 1; rec_len++; ! } else if (self->quoting == QUOTE_NONNUMERIC && !*quoted ! && !(isdigit(c) || c == '+' || c == '-' || c == '.')) *quoted = 1; From davecole@users.sourceforge.net Sun Feb 2 12:25:26 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 04:25:26 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv18578 Modified Files: pep-0305.txt Log Message: Changed the csv.reader() fileobj argument to interable. This give us much more flexibility in processing filtered data. Made the example excel dialect match the dialect in csv.py. Added explanation of doublequote. Added explanation of csv.QUOTE_NONE. Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** pep-0305.txt 31 Jan 2003 21:55:38 -0000 1.9 --- pep-0305.txt 2 Feb 2003 12:25:23 -0000 1.10 *************** *** 90,98 **** writing. The basic reading interface is:: ! obj = reader(fileobj [, dialect='excel2000'] [optional keyword args]) ! A reader object is an iterable which takes a file-like object opened ! for reading as the sole required parameter. The optional dialect parameter is discussed below. It also accepts several optional keyword arguments which define specific format settings for the parser --- 90,98 ---- writing. The basic reading interface is:: ! obj = reader(iterable [, dialect='excel2000'] [optional keyword args]) ! A reader object is an iterable which takes an interable object which ! returns lines as the sole required parameter. The optional dialect parameter is discussed below. It also accepts several optional keyword arguments which define specific format settings for the parser *************** *** 154,160 **** class excel: - quotechar = '"' delimiter = ',' escapechar = None skipinitialspace = False lineterminator = '\r\n' --- 154,161 ---- class excel: delimiter = ',' + quotechar = '"' escapechar = None + doublequote = True skipinitialspace = False lineterminator = '\r\n' *************** *** 189,198 **** - ``quotechar`` specifies a one-character string to use as the quoting ! character. It defaults to '"'. - ``delimiter`` specifies a one-character string to use as the field separator. It defaults to ','. ! - ``escapechar`` specifies a one character string used to escape the delimiter when quotechar is set to None. --- 190,200 ---- - ``quotechar`` specifies a one-character string to use as the quoting ! character. It defaults to '"'. Setting this to None has the same ! effect as setting quoting to csv.QUOTE_NONE. - ``delimiter`` specifies a one-character string to use as the field separator. It defaults to ','. ! - ``escapechar`` specifies a one-character string used to escape the delimiter when quotechar is set to None. *************** *** 216,220 **** fields which contain characters other than [+-0-9.]. ! - ``doublequote`` (tbd) - are there more to come? --- 218,227 ---- fields which contain characters other than [+-0-9.]. ! csv.QUOTE_NONE means that quotes are never placed around ! fields. ! ! - ``doublequote`` controls the handling of quotes inside fields. When ! True two consecutive quotes are interpreted as one during read, and ! when writing, each quote is written as two quotes. - are there more to come? From davecole@users.sourceforge.net Sun Feb 2 12:58:42 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 02 Feb 2003 04:58:42 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv27784 Modified Files: _csv.c Log Message: Better use of METH_ flags. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** _csv.c 2 Feb 2003 12:16:26 -0000 1.10 --- _csv.c 2 Feb 2003 12:58:40 -0000 1.11 *************** *** 357,365 **** static PyObject * ! Parser_clear(ParserObj *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "")) - return NULL; - clear_fields_and_status(self); --- 357,362 ---- static PyObject * ! Parser_clear(ParserObj *self) { clear_fields_and_status(self); *************** *** 560,570 **** static PyObject * ! Parser_join(ParserObj *self, PyObject *args) { - PyObject *seq; int len, i; - if (!PyArg_ParseTuple(args, "O", &seq)) - return NULL; if (!PySequence_Check(seq)) return raise_exception("sequence expected"); --- 557,564 ---- static PyObject * ! Parser_join(ParserObj *self, PyObject *seq) { int len, i; if (!PySequence_Check(seq)) return raise_exception("sequence expected"); *************** *** 619,625 **** { "parse", (PyCFunction)Parser_parse, METH_VARARGS, Parser_parse_doc }, ! { "clear", (PyCFunction)Parser_clear, METH_VARARGS, Parser_clear_doc }, ! { "join", (PyCFunction)Parser_join, METH_VARARGS, Parser_join_doc }, { NULL, NULL } --- 613,619 ---- { "parse", (PyCFunction)Parser_parse, METH_VARARGS, Parser_parse_doc }, ! { "clear", (PyCFunction)Parser_clear, METH_NOARGS, Parser_clear_doc }, ! { "join", (PyCFunction)Parser_join, METH_O, Parser_join_doc }, { NULL, NULL } From rhettinger@users.sourceforge.net Sun Feb 2 14:27:21 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sun, 02 Feb 2003 06:27:21 -0800 Subject: [Python-checkins] python/dist/src/Lib sets.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv25238 Modified Files: sets.py Log Message: SF patch #678899: Save time and memory by using itertools in sets module. Index: sets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sets.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** sets.py 14 Jan 2003 16:40:06 -0000 1.37 --- sets.py 2 Feb 2003 14:27:19 -0000 1.38 *************** *** 58,62 **** __all__ = ['BaseSet', 'Set', 'ImmutableSet'] ! class BaseSet(object): --- 58,62 ---- __all__ = ['BaseSet', 'Set', 'ImmutableSet'] ! from itertools import ifilter class BaseSet(object): *************** *** 183,187 **** else: little, big = other, self ! common = filter(big._data.has_key, little._data) return self.__class__(common) --- 183,187 ---- else: little, big = other, self ! common = ifilter(big._data.has_key, little) return self.__class__(common) *************** *** 205,214 **** selfdata = self._data otherdata = other._data ! for elt in selfdata: ! if elt not in otherdata: ! data[elt] = value ! for elt in otherdata: ! if elt not in selfdata: ! data[elt] = value return result --- 205,212 ---- selfdata = self._data otherdata = other._data ! for elt in ifilter(otherdata.has_key, selfdata, True): ! data[elt] = value ! for elt in ifilter(selfdata.has_key, otherdata, True): ! data[elt] = value return result *************** *** 229,237 **** result = self.__class__() data = result._data - otherdata = other._data value = True ! for elt in self: ! if elt not in otherdata: ! data[elt] = value return result --- 227,233 ---- result = self.__class__() data = result._data value = True ! for elt in ifilter(other._data.has_key, self, True): ! data[elt] = value return result *************** *** 265,272 **** if len(self) > len(other): # Fast check for obvious cases return False ! otherdata = other._data ! for elt in self: ! if elt not in otherdata: ! return False return True --- 261,266 ---- if len(self) > len(other): # Fast check for obvious cases return False ! for elt in ifilter(other._data.has_key, self, True): ! return False return True *************** *** 276,282 **** if len(self) < len(other): # Fast check for obvious cases return False ! selfdata = self._data ! for elt in other: ! if elt not in selfdata: return False return True --- 270,274 ---- if len(self) < len(other): # Fast check for obvious cases return False ! for elt in ifilter(self._data.has_key, other, True): return False return True From rhettinger@users.sourceforge.net Sun Feb 2 16:07:55 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sun, 02 Feb 2003 08:07:55 -0800 Subject: [Python-checkins] python/dist/src/Lib sets.py,1.38,1.39 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv7462 Modified Files: sets.py Log Message: One more use of ifilter() Index: sets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sets.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** sets.py 2 Feb 2003 14:27:19 -0000 1.38 --- sets.py 2 Feb 2003 16:07:53 -0000 1.39 *************** *** 437,443 **** self._binary_sanity_check(other) data = self._data ! for elt in other: ! if elt in data: ! del data[elt] return self --- 437,442 ---- self._binary_sanity_check(other) data = self._data ! for elt in ifilter(data.has_key, other): ! del data[elt] return self From tim_one@users.sourceforge.net Sun Feb 2 16:09:07 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 08:09:07 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6130/Lib/test Modified Files: pickletester.py Log Message: Add cPickle support for PROTO. Duplicated PROTO/LONG1/LONG4 code in the hitherto unknown (to me) noload() cPickle function, which is (a) something we don't test at all, and (b) pickle.py doesn't have. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** pickletester.py 2 Feb 2003 07:51:32 -0000 1.33 --- pickletester.py 2 Feb 2003 16:09:05 -0000 1.34 *************** *** 1,3 **** --- 1,5 ---- import unittest + import pickle + from test.test_support import TestFailed, have_unicode, TESTFN *************** *** 297,300 **** --- 299,321 ---- # Tests for protocol 2 + def test_proto(self): + build_none = pickle.NONE + pickle.STOP + for proto in protocols: + expected = build_none + if proto >= 2: + expected = pickle.PROTO + chr(proto) + expected + p = self.dumps(None, proto) + self.assertEqual(p, expected) + + oob = protocols[-1] + 1 # a future protocol + badpickle = pickle.PROTO + chr(oob) + build_none + try: + self.loads(badpickle) + except ValueError, detail: + self.failUnless(str(detail).startswith( + "unsupported pickle protocol")) + else: + self.fail("expected bad protocol number to raise ValueError") + def test_long1(self): x = 12345678910111213141516178920L *************** *** 315,319 **** d = (1, 2, 3) e = (1, 2, 3, 4) ! for proto in 0, 1, 2: for x in a, b, c, d, e: s = self.dumps(x, proto) --- 336,340 ---- d = (1, 2, 3) e = (1, 2, 3, 4) ! for proto in protocols: for x in a, b, c, d, e: s = self.dumps(x, proto) *************** *** 322,326 **** def test_singletons(self): ! for proto in 0, 1, 2: for x in None, False, True: s = self.dumps(x, proto) --- 343,347 ---- def test_singletons(self): ! for proto in protocols: for x in None, False, True: s = self.dumps(x, proto) From tim_one@users.sourceforge.net Sun Feb 2 16:09:08 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 08:09:08 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.107,2.108 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv6130/Modules Modified Files: cPickle.c Log Message: Add cPickle support for PROTO. Duplicated PROTO/LONG1/LONG4 code in the hitherto unknown (to me) noload() cPickle function, which is (a) something we don't test at all, and (b) pickle.py doesn't have. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.107 retrieving revision 2.108 diff -C2 -d -r2.107 -r2.108 *** cPickle.c 2 Feb 2003 02:57:52 -0000 2.107 --- cPickle.c 2 Feb 2003 16:09:05 -0000 2.108 *************** *** 2214,2224 **** static char stop = STOP; if (save(self, args, 0) < 0) return -1; ! if ((*self->write_func)(self, &stop, 1) < 0) return -1; ! if ((*self->write_func)(self, NULL, 0) < 0) return -1; --- 2214,2233 ---- static char stop = STOP; + if (self->proto >= 2) { + char bytes[2]; + + bytes[0] = PROTO; + bytes[1] = CURRENT_PROTOCOL_NUMBER; + if (self->write_func(self, bytes, 2) < 0) + return -1; + } + if (save(self, args, 0) < 0) return -1; ! if (self->write_func(self, &stop, 1) < 0) return -1; ! if (self->write_func(self, NULL, 0) < 0) return -1; *************** *** 3871,3874 **** --- 3880,3908 ---- } + /* Just raises an error if we don't know the protocol specified. PROTO + * is the first opcode for protocols >= 2. + */ + static int + load_proto(Unpicklerobject *self) + { + int i; + char *protobyte; + + i = self->read_func(self, &protobyte, 1); + if (i < 0) + return -1; + + i = calc_binint(protobyte, 1); + /* No point checking for < 0, since calc_binint returns an unsigned + * int when chewing on 1 byte. + */ + assert(i >= 0); + if (i <= CURRENT_PROTOCOL_NUMBER) + return 0; + + PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i); + return -1; + } + static PyObject * load(Unpicklerobject *self) *************** *** 4100,4103 **** --- 4134,4142 ---- continue; + case PROTO: + if (load_proto(self) < 0) + break; + continue; + case '\0': /* end of file */ *************** *** 4228,4231 **** --- 4267,4280 ---- continue; + case LONG1: + if (load_counted_long(self, 1) < 0) + break; + continue; + + case LONG4: + if (load_counted_long(self, 4) < 0) + break; + continue; + case FLOAT: if (load_float(self) < 0) *************** *** 4400,4403 **** --- 4449,4457 ---- case REDUCE: if (noload_reduce(self) < 0) + break; + continue; + + case PROTO: + if (load_proto(self) < 0) break; continue; From tim_one@users.sourceforge.net Sun Feb 2 16:14:25 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 08:14:25 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.108,2.109 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv10796/Modules Modified Files: cPickle.c Log Message: dump(): Fixed a stupid bug in new code. It wasn't possible for the bug to have an effect before protocol 3 is invented, so no test can be written for this (yet). Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.108 retrieving revision 2.109 diff -C2 -d -r2.108 -r2.109 *** cPickle.c 2 Feb 2003 16:09:05 -0000 2.108 --- cPickle.c 2 Feb 2003 16:14:23 -0000 2.109 *************** *** 2218,2222 **** bytes[0] = PROTO; ! bytes[1] = CURRENT_PROTOCOL_NUMBER; if (self->write_func(self, bytes, 2) < 0) return -1; --- 2218,2222 ---- bytes[0] = PROTO; ! bytes[1] = self->proto; if (self->write_func(self, bytes, 2) < 0) return -1; From tim_one@users.sourceforge.net Sun Feb 2 16:16:32 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 08:16:32 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.109,2.110 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv13585/Modules Modified Files: cPickle.c Log Message: dump(): Added asserts that self->proto is sane. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.109 retrieving revision 2.110 diff -C2 -d -r2.109 -r2.110 *** cPickle.c 2 Feb 2003 16:14:23 -0000 2.109 --- cPickle.c 2 Feb 2003 16:16:30 -0000 2.110 *************** *** 2218,2222 **** bytes[0] = PROTO; ! bytes[1] = self->proto; if (self->write_func(self, bytes, 2) < 0) return -1; --- 2218,2223 ---- bytes[0] = PROTO; ! assert(self->proto >= 0 && self->proto < 256); ! bytes[1] = (char)self->proto; if (self->write_func(self, bytes, 2) < 0) return -1; From nnorwitz@users.sourceforge.net Sun Feb 2 17:08:35 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:08:35 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.110,2.111 _ssl.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv13868/Modules Modified Files: cPickle.c _ssl.c Log Message: Fix compiler warning Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.110 retrieving revision 2.111 diff -C2 -d -r2.110 -r2.111 *** cPickle.c 2 Feb 2003 16:16:30 -0000 2.110 --- cPickle.c 2 Feb 2003 17:08:32 -0000 2.111 *************** *** 2917,2921 **** else { /* Read the raw little-endian bytes & convert. */ ! i = self->read_func(self, &(char *)pdata, size); if (i < 0) return -1; along = _PyLong_FromByteArray(pdata, (size_t)size, --- 2917,2921 ---- else { /* Read the raw little-endian bytes & convert. */ ! i = self->read_func(self, (char **)&pdata, size); if (i < 0) return -1; along = _PyLong_FromByteArray(pdata, (size_t)size, Index: _ssl.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_ssl.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** _ssl.c 31 Jan 2003 18:13:18 -0000 1.10 --- _ssl.c 2 Feb 2003 17:08:33 -0000 1.11 *************** *** 65,68 **** --- 65,69 ---- static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); + static int wait_for_timeout(PySocketSockObject *s, int writing); #define PySSLObject_Check(v) ((v)->ob_type == &PySSL_Type) From nnorwitz@users.sourceforge.net Sun Feb 2 17:10:07 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:10:07 -0800 Subject: [Python-checkins] python/dist/src/Misc AIX-NOTES,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv14490a/Misc Modified Files: AIX-NOTES Log Message: Add some notes that got python to work on the snake farm Index: AIX-NOTES =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/AIX-NOTES,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** AIX-NOTES 26 Oct 2000 17:07:01 -0000 1.9 --- AIX-NOTES 2 Feb 2003 17:10:04 -0000 1.10 *************** *** 138,140 **** --- 138,156 ---- for ld_so_aix. + According to Gary Hook from IBM, the format of the export file changed + in AIX 4.2. For AIX 4.2 and later, a period "." is required on the + first line after "#!". If python crashes while importing a shared + library, you can try modifying the LINKCC variable in the Makefile. + It probably looks like this: + + LINKCC= $(srcdir)/Modules/makexp_aix Modules/python.exp \"\" $(LIBRARY); $(PURIFY) $(CXX) + + You should modify the \"\" to be a period: + + LINKCC= $(srcdir)/Modules/makexp_aix Modules/python.exp . $(LIBRARY); $(PURIFY) $(CXX) + + Using a period fixed the problem in the snake farm. YMMV. + After testing with different versions of AIX, a fix should + be checked in. Hopefully, this fix be incorporated into Python 2.3. + ============================================================================== From tim_one@users.sourceforge.net Sun Feb 2 17:26:42 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:26:42 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.111,2.112 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv22945/Modules Modified Files: cPickle.c Log Message: Beefed up the tests by putting in more "for proto in protocols:" outer loops. Renamed DATA and BINDATA to DATA0 and DATA1. Included disassemblies, but noted why we can't test them. Added XXX comment to cPickle about a mysterious comment, where pickle and cPickle diverge in how they number PUT indices. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.111 retrieving revision 2.112 diff -C2 -d -r2.111 -r2.112 *** cPickle.c 2 Feb 2003 17:08:32 -0000 2.111 --- cPickle.c 2 Feb 2003 17:26:40 -0000 2.112 *************** *** 720,723 **** --- 720,728 ---- /* Make sure memo keys are positive! */ + /* XXX Why? + * XXX And does "positive" really mean non-negative? + * XXX pickle.py starts with PUT index 0, not 1. This makes for + * XXX gratuitous differences between the pickling modules. + */ p++; From tim_one@users.sourceforge.net Sun Feb 2 17:26:42 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:26:42 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22945/Lib/test Modified Files: pickletester.py Log Message: Beefed up the tests by putting in more "for proto in protocols:" outer loops. Renamed DATA and BINDATA to DATA0 and DATA1. Included disassemblies, but noted why we can't test them. Added XXX comment to cPickle about a mysterious comment, where pickle and cPickle diverge in how they number PUT indices. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** pickletester.py 2 Feb 2003 16:09:05 -0000 1.34 --- pickletester.py 2 Feb 2003 17:26:39 -0000 1.35 *************** *** 36,44 **** __metaclass__ = metaclass ! # DATA and BINDATA are the protocol 0 and protocol 1 pickles of the object ! # returned by create_data(). # break into multiple strings to avoid confusing font-lock-mode ! DATA = """(lp1 I0 aL1L --- 36,45 ---- __metaclass__ = metaclass ! # DATA0 .. DATA2 are the pickles we expect under the various protocols, for ! # the object returned by create_data(). ! # XXX DATA2 doesn't exist yet, as it's not fully implemented in cPickle. # break into multiple strings to avoid confusing font-lock-mode ! DATA0 = """(lp1 I0 aL1L *************** *** 85,96 **** """ ! BINDATA = ']q\x01(K\x00L1L\nG@\x00\x00\x00\x00\x00\x00\x00' + \ ! 'c__builtin__\ncomplex\nq\x02(G@\x08\x00\x00\x00\x00\x00' + \ ! '\x00G\x00\x00\x00\x00\x00\x00\x00\x00tRq\x03K\x01J\xff\xff' + \ ! '\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xff' + \ ! 'J\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00' + \ ! '\x00\x80J\x00\x00\x00\x80(U\x03abcq\x04h\x04(c__main__\n' + \ ! 'C\nq\x05oq\x06}q\x07(U\x03fooq\x08K\x01U\x03barq\tK\x02ubh' + \ ! '\x06tq\nh\nK\x05e.' def create_data(): --- 86,228 ---- """ ! # Disassembly of DATA0. ! DATA0_DIS = """\ ! 0: ( MARK ! 1: l LIST (MARK at 0) ! 2: p PUT 1 ! 5: I INT 0 ! 8: a APPEND ! 9: L LONG 1L ! 13: a APPEND ! 14: F FLOAT 2.0 ! 17: a APPEND ! 18: c GLOBAL '__builtin__ complex' ! 39: p PUT 2 ! 42: ( MARK ! 43: F FLOAT 3.0 ! 46: F FLOAT 0.0 ! 49: t TUPLE (MARK at 42) ! 50: R REDUCE ! 51: p PUT 3 ! 54: a APPEND ! 55: I INT 1 ! 58: a APPEND ! 59: I INT -1 ! 63: a APPEND ! 64: I INT 255 ! 69: a APPEND ! 70: I INT -255 ! 76: a APPEND ! 77: I INT -256 ! 83: a APPEND ! 84: I INT 65535 ! 91: a APPEND ! 92: I INT -65535 ! 100: a APPEND ! 101: I INT -65536 ! 109: a APPEND ! 110: I INT 2147483647 ! 122: a APPEND ! 123: I INT -2147483647 ! 136: a APPEND ! 137: I INT -2147483648 ! 150: a APPEND ! 151: ( MARK ! 152: S STRING 'abc' ! 159: p PUT 4 ! 162: g GET 4 ! 165: ( MARK ! 166: i INST '__main__ C' (MARK at 165) ! 178: p PUT 5 ! 181: ( MARK ! 182: d DICT (MARK at 181) ! 183: p PUT 6 ! 186: S STRING 'foo' ! 193: p PUT 7 ! 196: I INT 1 ! 199: s SETITEM ! 200: S STRING 'bar' ! 207: p PUT 8 ! 210: I INT 2 ! 213: s SETITEM ! 214: b BUILD ! 215: g GET 5 ! 218: t TUPLE (MARK at 151) ! 219: p PUT 9 ! 222: a APPEND ! 223: g GET 9 ! 226: a APPEND ! 227: I INT 5 ! 230: a APPEND ! 231: . STOP ! highest protocol among opcodes = 0 ! """ ! ! DATA1 = (']q\x01(K\x00L1L\nG@\x00\x00\x00\x00\x00\x00\x00' ! 'c__builtin__\ncomplex\nq\x02(G@\x08\x00\x00\x00\x00\x00' ! '\x00G\x00\x00\x00\x00\x00\x00\x00\x00tRq\x03K\x01J\xff\xff' ! '\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xff' ! 'J\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00' ! '\x00\x80J\x00\x00\x00\x80(U\x03abcq\x04h\x04(c__main__\n' ! 'C\nq\x05oq\x06}q\x07(U\x03fooq\x08K\x01U\x03barq\tK\x02ubh' ! '\x06tq\nh\nK\x05e.' ! ) ! ! # Disassembly of DATA1. ! DATA1_DIS = """\ ! 0: ] EMPTY_LIST ! 1: q BINPUT 1 ! 3: ( MARK ! 4: K BININT1 0 ! 6: L LONG 1L ! 10: G BINFLOAT 2.0 ! 19: c GLOBAL '__builtin__ complex' ! 40: q BINPUT 2 ! 42: ( MARK ! 43: G BINFLOAT 3.0 ! 52: G BINFLOAT 0.0 ! 61: t TUPLE (MARK at 42) ! 62: R REDUCE ! 63: q BINPUT 3 ! 65: K BININT1 1 ! 67: J BININT -1 ! 72: K BININT1 255 ! 74: J BININT -255 ! 79: J BININT -256 ! 84: M BININT2 65535 ! 87: J BININT -65535 ! 92: J BININT -65536 ! 97: J BININT 2147483647 ! 102: J BININT -2147483647 ! 107: J BININT -2147483648 ! 112: ( MARK ! 113: U SHORT_BINSTRING 'abc' ! 118: q BINPUT 4 ! 120: h BINGET 4 ! 122: ( MARK ! 123: c GLOBAL '__main__ C' ! 135: q BINPUT 5 ! 137: o OBJ (MARK at 122) ! 138: q BINPUT 6 ! 140: } EMPTY_DICT ! 141: q BINPUT 7 ! 143: ( MARK ! 144: U SHORT_BINSTRING 'foo' ! 149: q BINPUT 8 ! 151: K BININT1 1 ! 153: U SHORT_BINSTRING 'bar' ! 158: q BINPUT 9 ! 160: K BININT1 2 ! 162: u SETITEMS (MARK at 143) ! 163: b BUILD ! 164: h BINGET 6 ! 166: t TUPLE (MARK at 112) ! 167: q BINPUT 10 ! 169: h BINGET 10 ! 171: K BININT1 5 ! 173: e APPENDS (MARK at 3) ! 174: . STOP ! highest protocol among opcodes = 1 ! """ def create_data(): *************** *** 115,186 **** class AbstractPickleTests(unittest.TestCase): _testdata = create_data() def setUp(self): - # subclass must define self.dumps, self.loads, self.error pass def test_misc(self): # test various datatypes not tested by testdata ! x = myint(4) ! s = self.dumps(x) ! y = self.loads(s) ! self.assertEqual(x, y) ! x = (1, ()) ! s = self.dumps(x) ! y = self.loads(s) ! self.assertEqual(x, y) ! x = initarg(1, x) ! s = self.dumps(x) ! y = self.loads(s) ! self.assertEqual(x, y) # XXX test __reduce__ protocol? ! def test_identity(self): ! s = self.dumps(self._testdata) ! x = self.loads(s) ! self.assertEqual(x, self._testdata) ! def test_constant(self): ! x = self.loads(DATA) ! self.assertEqual(x, self._testdata) ! x = self.loads(BINDATA) ! self.assertEqual(x, self._testdata) ! def test_binary(self): ! s = self.dumps(self._testdata, 1) ! x = self.loads(s) ! self.assertEqual(x, self._testdata) def test_recursive_list(self): l = [] l.append(l) ! s = self.dumps(l) ! x = self.loads(s) ! self.assertEqual(x, l) ! self.assertEqual(x, x[0]) ! self.assertEqual(id(x), id(x[0])) def test_recursive_dict(self): d = {} d[1] = d ! s = self.dumps(d) ! x = self.loads(s) ! self.assertEqual(x, d) ! self.assertEqual(x[1], x) ! self.assertEqual(id(x[1]), id(x)) def test_recursive_inst(self): i = C() i.attr = i ! s = self.dumps(i) ! x = self.loads(s) ! self.assertEqual(x, i) ! self.assertEqual(x.attr, x) ! self.assertEqual(id(x.attr), id(x)) def test_recursive_multi(self): --- 247,336 ---- class AbstractPickleTests(unittest.TestCase): + # Subclass must define self.dumps, self.loads, self.error. _testdata = create_data() def setUp(self): pass def test_misc(self): # test various datatypes not tested by testdata ! for proto in protocols: ! x = myint(4) ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(x, y) ! x = (1, ()) ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(x, y) ! x = initarg(1, x) ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(x, y) # XXX test __reduce__ protocol? ! def test_roundtrip_equality(self): ! expected = self._testdata ! for proto in protocols: ! s = self.dumps(expected, proto) ! got = self.loads(s) ! self.assertEqual(expected, got) ! def test_load_from_canned_string(self): ! expected = self._testdata ! for canned in DATA0, DATA1: ! got = self.loads(canned) ! self.assertEqual(expected, got) ! # There are gratuitous differences between pickles produced by ! # pickle and cPickle, largely because cPickle starts PUT indices at ! # 1 and pickle starts them at 0. See XXX comment in cPickle's put2() -- ! # there's a comment with an exclamation point there whose meaning ! # is a mystery. cPickle also suppresses PUT for objects with a refcount ! # of 1. ! def dont_test_disassembly(self): ! from cStringIO import StringIO ! from pickletools import dis ! ! for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS): ! s = self.dumps(self._testdata, proto) ! filelike = StringIO() ! dis(s, out=filelike) ! got = filelike.getvalue() ! self.assertEqual(expected, got) def test_recursive_list(self): l = [] l.append(l) ! for proto in protocols: ! s = self.dumps(l, proto) ! x = self.loads(s) ! self.assertEqual(x, l) ! self.assertEqual(x, x[0]) ! self.assertEqual(id(x), id(x[0])) def test_recursive_dict(self): d = {} d[1] = d ! for proto in protocols: ! s = self.dumps(d, proto) ! x = self.loads(s) ! self.assertEqual(x, d) ! self.assertEqual(x[1], x) ! self.assertEqual(id(x[1]), id(x)) def test_recursive_inst(self): i = C() i.attr = i ! for proto in protocols: ! s = self.dumps(i, 2) ! x = self.loads(s) ! self.assertEqual(x, i) ! self.assertEqual(x.attr, x) ! self.assertEqual(id(x.attr), id(x)) def test_recursive_multi(self): *************** *** 190,201 **** i.attr = d l.append(i) ! s = self.dumps(l) ! x = self.loads(s) ! self.assertEqual(x, l) ! self.assertEqual(x[0], i) ! self.assertEqual(x[0].attr, d) ! self.assertEqual(x[0].attr[1], x) ! self.assertEqual(x[0].attr[1][0], i) ! self.assertEqual(x[0].attr[1][0].attr, d) def test_garyp(self): --- 340,352 ---- i.attr = d l.append(i) ! for proto in protocols: ! s = self.dumps(l, proto) ! x = self.loads(s) ! self.assertEqual(x, l) ! self.assertEqual(x[0], i) ! self.assertEqual(x[0].attr, d) ! self.assertEqual(x[0].attr[1], x) ! self.assertEqual(x[0].attr[1][0], i) ! self.assertEqual(x[0].attr[1][0].attr, d) def test_garyp(self): *************** *** 275,299 **** def test_metaclass(self): a = use_metaclass() ! s = self.dumps(a) ! b = self.loads(s) ! self.assertEqual(a.__class__, b.__class__) def test_structseq(self): import time - t = time.localtime() - s = self.dumps(t) - u = self.loads(s) - self.assertEqual(t, u) import os ! if hasattr(os, "stat"): ! t = os.stat(os.curdir) ! s = self.dumps(t) ! u = self.loads(s) ! self.assertEqual(t, u) ! if hasattr(os, "statvfs"): ! t = os.statvfs(os.curdir) ! s = self.dumps(t) u = self.loads(s) self.assertEqual(t, u) # Tests for protocol 2 --- 426,453 ---- def test_metaclass(self): a = use_metaclass() ! for proto in protocols: ! s = self.dumps(a, proto) ! b = self.loads(s) ! self.assertEqual(a.__class__, b.__class__) def test_structseq(self): import time import os ! ! t = time.localtime() ! for proto in protocols: ! s = self.dumps(t, proto) u = self.loads(s) self.assertEqual(t, u) + if hasattr(os, "stat"): + t = os.stat(os.curdir) + s = self.dumps(t, proto) + u = self.loads(s) + self.assertEqual(t, u) + if hasattr(os, "statvfs"): + t = os.statvfs(os.curdir) + s = self.dumps(t, proto) + u = self.loads(s) + self.assertEqual(t, u) # Tests for protocol 2 *************** *** 357,363 **** self.assertEqual(tuple(x), tuple(y)) self.assertEqual(x.__dict__, y.__dict__) - ## import pickletools - ## print - ## pickletools.dis(s) def test_newobj_list(self): --- 511,514 ---- *************** *** 369,375 **** self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) - ## import pickletools - ## print - ## pickletools.dis(s) def test_newobj_generic(self): --- 520,523 ---- *************** *** 380,386 **** x.foo = 42 s = self.dumps(x, proto) - ## import pickletools - ## print - ## pickletools.dis(s) y = self.loads(s) detail = (proto, C, B, x, y, type(y)) --- 528,531 ---- From tim_one@users.sourceforge.net Sun Feb 2 17:33:55 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:33:55 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.153,1.154 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv26400/Objects Modified Files: longobject.c Log Message: long_from_binary_base(): Sped this a little by computing the # of bits needed outside the first loop. Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.153 retrieving revision 1.154 diff -C2 -d -r1.153 -r1.154 *** longobject.c 2 Feb 2003 08:05:32 -0000 1.153 --- longobject.c 2 Feb 2003 17:33:53 -0000 1.154 *************** *** 1127,1139 **** if (k < 0 || k >= base) break; - n += bits_per_char; - if (n < 0) { - PyErr_SetString(PyExc_ValueError, - "long string too large to convert"); - return NULL; - } ++p; } *str = p; /* n <- # of Python digits needed, = ceiling(n/SHIFT). */ n = (n + SHIFT - 1) / SHIFT; --- 1127,1139 ---- if (k < 0 || k >= base) break; ++p; } *str = p; + n = (p - start) * bits_per_char; + if (n / bits_per_char != p - start) { + PyErr_SetString(PyExc_ValueError, + "long string too large to convert"); + return NULL; + } /* n <- # of Python digits needed, = ceiling(n/SHIFT). */ n = (n + SHIFT - 1) / SHIFT; From nnorwitz@users.sourceforge.net Sun Feb 2 17:59:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:59:08 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.140,1.141 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv7239 Modified Files: setup.py Log Message: Get ossaudiodev to compile on freebsd 4.7 Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.140 retrieving revision 1.141 diff -C2 -d -r1.140 -r1.141 *** setup.py 1 Feb 2003 00:10:09 -0000 1.140 --- setup.py 2 Feb 2003 17:59:05 -0000 1.141 *************** *** 743,748 **** exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) ) # ossaudiodev currently doesn't work, so don't build. ! ## # XXX should also build this on FreeBSD! ## exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) ) --- 743,749 ---- exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) ) + if platform in ('linux2', 'freebsd4'): # ossaudiodev currently doesn't work, so don't build. ! pass ## exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) ) From nnorwitz@users.sourceforge.net Sun Feb 2 17:59:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:59:08 -0800 Subject: [Python-checkins] python/dist/src/Modules ossaudiodev.c,1.21,1.22 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7239/Modules Modified Files: ossaudiodev.c Log Message: Get ossaudiodev to compile on freebsd 4.7 Index: ossaudiodev.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/ossaudiodev.c,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** ossaudiodev.c 10 Jan 2003 21:27:54 -0000 1.21 --- ossaudiodev.c 2 Feb 2003 17:59:06 -0000 1.22 *************** *** 77,81 **** --- 77,83 ---- { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" }, { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" }, + #ifdef AFMT_S16_NE { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" }, + #endif }; *************** *** 964,968 **** --- 966,972 ---- _EXPORT_INT(m, AFMT_MPEG); _EXPORT_INT(m, AFMT_AC3); + #ifdef AFMT_S16_NE _EXPORT_INT(m, AFMT_S16_NE); + #endif /* Expose the sound mixer device numbers. */ *************** *** 1006,1014 **** --- 1010,1022 ---- _EXPORT_INT(m, SNDCTL_COPR_WCODE); _EXPORT_INT(m, SNDCTL_COPR_WDATA); + #ifdef SNDCTL_DSP_BIND_CHANNEL _EXPORT_INT(m, SNDCTL_DSP_BIND_CHANNEL); + #endif _EXPORT_INT(m, SNDCTL_DSP_CHANNELS); _EXPORT_INT(m, SNDCTL_DSP_GETBLKSIZE); _EXPORT_INT(m, SNDCTL_DSP_GETCAPS); + #ifdef SNDCTL_DSP_GETCHANNELMASK _EXPORT_INT(m, SNDCTL_DSP_GETCHANNELMASK); + #endif _EXPORT_INT(m, SNDCTL_DSP_GETFMTS); _EXPORT_INT(m, SNDCTL_DSP_GETIPTR); *************** *** 1025,1029 **** --- 1033,1039 ---- _EXPORT_INT(m, SNDCTL_DSP_NONBLOCK); _EXPORT_INT(m, SNDCTL_DSP_POST); + #ifdef SNDCTL_DSP_PROFILE _EXPORT_INT(m, SNDCTL_DSP_PROFILE); + #endif _EXPORT_INT(m, SNDCTL_DSP_RESET); _EXPORT_INT(m, SNDCTL_DSP_SAMPLESIZE); *************** *** 1049,1053 **** --- 1059,1065 ---- _EXPORT_INT(m, SNDCTL_SEQ_GETINCOUNT); _EXPORT_INT(m, SNDCTL_SEQ_GETOUTCOUNT); + #ifdef SNDCTL_SEQ_GETTIME _EXPORT_INT(m, SNDCTL_SEQ_GETTIME); + #endif _EXPORT_INT(m, SNDCTL_SEQ_NRMIDIS); _EXPORT_INT(m, SNDCTL_SEQ_NRSYNTHS); *************** *** 1060,1068 **** --- 1072,1086 ---- _EXPORT_INT(m, SNDCTL_SEQ_TESTMIDI); _EXPORT_INT(m, SNDCTL_SEQ_THRESHOLD); + #ifdef SNDCTL_SYNTH_CONTROL _EXPORT_INT(m, SNDCTL_SYNTH_CONTROL); + #endif + #ifdef SNDCTL_SYNTH_ID _EXPORT_INT(m, SNDCTL_SYNTH_ID); + #endif _EXPORT_INT(m, SNDCTL_SYNTH_INFO); _EXPORT_INT(m, SNDCTL_SYNTH_MEMAVL); + #ifdef SNDCTL_SYNTH_REMOVESAMPLE _EXPORT_INT(m, SNDCTL_SYNTH_REMOVESAMPLE); + #endif _EXPORT_INT(m, SNDCTL_TMR_CONTINUE); _EXPORT_INT(m, SNDCTL_TMR_METRONOME); From tim_one@users.sourceforge.net Sun Feb 2 17:59:13 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:59:13 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.35,1.36 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv7126/Lib/test Modified Files: pickletester.py Log Message: Implemented proto 2 NEWTRUE and NEWFALSE in cPickle. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** pickletester.py 2 Feb 2003 17:26:39 -0000 1.35 --- pickletester.py 2 Feb 2003 17:59:11 -0000 1.36 *************** *** 503,506 **** --- 503,512 ---- self.assert_(x is y, (proto, x, s, y)) + # Test that proto >= 2 really uses the bool opcodes. + if proto >= 2 and x in (False, True): + expected = x and pickle.NEWTRUE or pickle.NEWFALSE + # Skip the PROTO opcode at the start. + self.assertEqual(s[2], expected) + def test_newobj_tuple(self): x = MyTuple([1, 2, 3]) From tim_one@users.sourceforge.net Sun Feb 2 17:59:13 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 09:59:13 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.112,2.113 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7126/Modules Modified Files: cPickle.c Log Message: Implemented proto 2 NEWTRUE and NEWFALSE in cPickle. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.112 retrieving revision 2.113 diff -C2 -d -r2.112 -r2.113 *** cPickle.c 2 Feb 2003 17:26:40 -0000 2.112 --- cPickle.c 2 Feb 2003 17:59:11 -0000 2.113 *************** *** 964,970 **** long l = PyInt_AS_LONG((PyIntObject *)args); ! if ((*self->write_func)(self, buf[l], len[l]) < 0) return -1; - return 0; } --- 964,974 ---- long l = PyInt_AS_LONG((PyIntObject *)args); ! if (self->proto >= 2) { ! char opcode = l ? NEWTRUE : NEWFALSE; ! if (self->write_func(self, &opcode, 1) < 0) ! return -1; ! } ! else if (self->write_func(self, buf[l], len[l]) < 0) return -1; return 0; } *************** *** 2790,2793 **** --- 2794,2806 ---- } + static int + load_bool(Unpicklerobject *self, PyObject *boolean) + { + assert(boolean == Py_True || boolean == Py_False); + Py_INCREF(boolean); + PDATA_PUSH(self->stack, boolean, -1); + return 0; + } + /* s contains x bytes of a little-endian integer. Return its value as a * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian *************** *** 4145,4148 **** --- 4158,4171 ---- continue; + case NEWTRUE: + if (load_bool(self, Py_True) < 0) + break; + continue; + + case NEWFALSE: + if (load_bool(self, Py_False) < 0) + break; + continue; + case '\0': /* end of file */ *************** *** 4463,4466 **** --- 4486,4498 ---- continue; + case NEWTRUE: + if (load_bool(self, Py_True) < 0) + break; + continue; + + case NEWFALSE: + if (load_bool(self, Py_False) < 0) + break; + continue; default: cPickle_ErrFormat(UnpicklingError, From tim_one@users.sourceforge.net Sun Feb 2 18:08:36 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 10:08:36 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.113,2.114 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv10761/Modules Modified Files: cPickle.c Log Message: Minor cleanup, mostly adding horizontal whitespace, and breaking apart embedded assignments, for readability. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.113 retrieving revision 2.114 diff -C2 -d -r2.113 -r2.114 *** cPickle.c 2 Feb 2003 17:59:11 -0000 2.113 --- cPickle.c 2 Feb 2003 18:08:34 -0000 2.114 *************** *** 2281,2313 **** /* set up an array to hold get/put status */ ! if ((lm=PyDict_Size(self->memo)) < 0) return NULL; lm++; ! if (! (have_get=malloc((lm)*sizeof(char)))) return PyErr_NoMemory(); ! memset(have_get,0,lm); /* Scan for gets. */ ! for (rsize=0, i=l; --i >= 0; ) { ! k=data->data[i]; ! if (PyString_Check(k)) { rsize += PyString_GET_SIZE(k); - } else if (PyInt_Check(k)) { /* put */ ! ik=PyInt_AS_LONG((PyIntObject*)k); ! if (ik >= lm || ik==0) { PyErr_SetString(PicklingError, "Invalid get data"); return NULL; } ! if (have_get[ik]) { /* with matching get */ ! if (ik < 256) rsize += 2; ! else rsize+=5; ! } } else if (! (PyTuple_Check(k) && PyTuple_GET_SIZE(k) == 2 && ! PyInt_Check((k=PyTuple_GET_ITEM(k,0)))) ) { PyErr_SetString(PicklingError, --- 2281,2312 ---- /* set up an array to hold get/put status */ ! lm = PyDict_Size(self->memo); ! if (lm < 0) return NULL; lm++; ! have_get = malloc(lm); ! if (have_get == NULL) return PyErr_NoMemory(); ! memset(have_get, 0, lm); /* Scan for gets. */ ! for (rsize = 0, i = l; --i >= 0; ) { ! k = data->data[i]; ! if (PyString_Check(k)) rsize += PyString_GET_SIZE(k); else if (PyInt_Check(k)) { /* put */ ! ik = PyInt_AS_LONG((PyIntObject*)k); ! if (ik >= lm || ik == 0) { PyErr_SetString(PicklingError, "Invalid get data"); return NULL; } ! if (have_get[ik]) /* with matching get */ ! rsize += ik < 256 ? 2 : 5; } else if (! (PyTuple_Check(k) && PyTuple_GET_SIZE(k) == 2 && ! PyInt_Check((k = PyTuple_GET_ITEM(k, 0)))) ) { PyErr_SetString(PicklingError, *************** *** 2317,2350 **** else { /* put */ ! ik=PyInt_AS_LONG((PyIntObject*)k); ! if (ik >= lm || ik==0) { PyErr_SetString(PicklingError, "Invalid get data"); return NULL; } ! have_get[ik]=1; ! if (ik < 256) rsize += 2; ! else rsize+=5; } - } /* Now generate the result */ ! if (!( r=PyString_FromStringAndSize(NULL,rsize))) goto err; ! s=PyString_AS_STRING((PyStringObject*)r); ! for (i=0; idata[i]; if (PyString_Check(k)) { ! ssize=PyString_GET_SIZE(k); if (ssize) { ! p=PyString_AS_STRING((PyStringObject*)k); ! while (--ssize >= 0) *s++=*p++; } } else if (PyTuple_Check(k)) { /* get */ ! ik=PyInt_AS_LONG((PyIntObject*)PyTuple_GET_ITEM(k,0)); if (ik < 256) { *s++ = BINGET; --- 2316,2350 ---- else { /* put */ ! ik = PyInt_AS_LONG((PyIntObject *)k); ! if (ik >= lm || ik == 0) { PyErr_SetString(PicklingError, "Invalid get data"); return NULL; } ! have_get[ik] = 1; ! rsize += ik < 256 ? 2 : 5; } } /* Now generate the result */ ! r = PyString_FromStringAndSize(NULL, rsize); ! if (r == NULL) goto err; ! s = PyString_AS_STRING((PyStringObject *)r); ! for (i = 0; i < l; i++) { ! k = data->data[i]; if (PyString_Check(k)) { ! ssize = PyString_GET_SIZE(k); if (ssize) { ! p=PyString_AS_STRING((PyStringObject *)k); ! while (--ssize >= 0) ! *s++ = *p++; } } else if (PyTuple_Check(k)) { /* get */ ! ik = PyInt_AS_LONG((PyIntObject *) ! PyTuple_GET_ITEM(k, 0)); if (ik < 256) { *s++ = BINGET; *************** *** 2361,2365 **** else { /* put */ ! ik=PyInt_AS_LONG((PyIntObject*)k); if (have_get[ik]) { /* with matching get */ --- 2361,2365 ---- else { /* put */ ! ik = PyInt_AS_LONG((PyIntObject*)k); if (have_get[ik]) { /* with matching get */ *************** *** 2377,2386 **** } } - } if (clear) { PyDict_Clear(self->memo); ! Pdata_clear(data,0); } --- 2377,2385 ---- } } } if (clear) { PyDict_Clear(self->memo); ! Pdata_clear(data, 0); } From tim_one@users.sourceforge.net Sun Feb 2 18:29:35 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 10:29:35 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.114,2.115 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv16785/Modules Modified Files: cPickle.c Log Message: Massive edits. If p is a pointer to a struct, and p->f is a pointer to a function, then p->f(arg1, arg2, ...) is semantically the same as (*p->f)(arg1, arg2, ...) Changed all instances of the latter into the former. Given how often the code embeds this kind of expression in an if test, the unnecessary parens and dereferening operator were a real drag on readability. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.114 retrieving revision 2.115 diff -C2 -d -r2.114 -r2.115 *** cPickle.c 2 Feb 2003 18:08:34 -0000 2.114 --- cPickle.c 2 Feb 2003 18:29:33 -0000 2.115 *************** *** 687,691 **** } ! if ((*self->write_func)(self, s, len) < 0) return -1; --- 687,691 ---- } ! if (self->write_func(self, s, len) < 0) return -1; *************** *** 771,775 **** } ! if ((*self->write_func)(self, c_str, len) < 0) goto finally; --- 771,775 ---- } ! if (self->write_func(self, c_str, len) < 0) goto finally; *************** *** 951,955 **** { static char none = NONE; ! if ((*self->write_func)(self, &none, 1) < 0) return -1; --- 951,955 ---- { static char none = NONE; ! if (self->write_func(self, &none, 1) < 0) return -1; *************** *** 992,996 **** c_str[0] = INT; PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l); ! if ((*self->write_func)(self, c_str, strlen(c_str)) < 0) return -1; } --- 992,996 ---- c_str[0] = INT; PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l); ! if (self->write_func(self, c_str, strlen(c_str)) < 0) return -1; } *************** *** 1017,1021 **** } ! if ((*self->write_func)(self, c_str, len) < 0) return -1; } --- 1017,1021 ---- } ! if (self->write_func(self, c_str, len) < 0) return -1; } *************** *** 1121,1133 **** goto finally; ! if ((*self->write_func)(self, &l, 1) < 0) goto finally; ! if ((*self->write_func)(self, ! PyString_AS_STRING((PyStringObject *)repr), ! size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; --- 1121,1133 ---- goto finally; ! if (self->write_func(self, &l, 1) < 0) goto finally; ! if (self->write_func(self, ! PyString_AS_STRING((PyStringObject *)repr), ! size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; *************** *** 1233,1237 **** *p = (unsigned char) (flo & 0xFF); ! if ((*self->write_func)(self, str, 9) < 0) return -1; } --- 1233,1237 ---- *p = (unsigned char) (flo & 0xFF); ! if (self->write_func(self, str, 9) < 0) return -1; } *************** *** 1241,1245 **** PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%.17g\n", x); ! if ((*self->write_func)(self, c_str, strlen(c_str)) < 0) return -1; } --- 1241,1245 ---- PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%.17g\n", x); ! if (self->write_func(self, c_str, strlen(c_str)) < 0) return -1; } *************** *** 1270,1280 **** repr_str = PyString_AS_STRING((PyStringObject *)repr); ! if ((*self->write_func)(self, &string, 1) < 0) goto err; ! if ((*self->write_func)(self, repr_str, len) < 0) goto err; ! if ((*self->write_func)(self, "\n", 1) < 0) goto err; --- 1270,1280 ---- repr_str = PyString_AS_STRING((PyStringObject *)repr); ! if (self->write_func(self, &string, 1) < 0) goto err; ! if (self->write_func(self, repr_str, len) < 0) goto err; ! if (self->write_func(self, "\n", 1) < 0) goto err; *************** *** 1300,1304 **** } ! if ((*self->write_func)(self, c_str, len) < 0) return -1; --- 1300,1304 ---- } ! if (self->write_func(self, c_str, len) < 0) return -1; *************** *** 1308,1313 **** } else { ! if ((*self->write_func)(self, ! PyString_AS_STRING((PyStringObject *)args), size) < 0) return -1; } --- 1308,1315 ---- } else { ! if (self->write_func(self, ! PyString_AS_STRING( ! (PyStringObject *)args), ! size) < 0) return -1; } *************** *** 1388,1398 **** repr_str = PyString_AS_STRING((PyStringObject *)repr); ! if ((*self->write_func)(self, &string, 1) < 0) goto err; ! if ((*self->write_func)(self, repr_str, len) < 0) goto err; ! if ((*self->write_func)(self, "\n", 1) < 0) goto err; --- 1390,1400 ---- repr_str = PyString_AS_STRING((PyStringObject *)repr); ! if (self->write_func(self, &string, 1) < 0) goto err; ! if (self->write_func(self, repr_str, len) < 0) goto err; ! if (self->write_func(self, "\n", 1) < 0) goto err; *************** *** 1414,1418 **** len = 5; ! if ((*self->write_func)(self, c_str, len) < 0) goto err; --- 1416,1420 ---- len = 5; ! if (self->write_func(self, c_str, len) < 0) goto err; *************** *** 1423,1428 **** } else { ! if ((*self->write_func)(self, PyString_AS_STRING(repr), ! size) < 0) goto err; } --- 1425,1430 ---- } else { ! if (self->write_func(self, PyString_AS_STRING(repr), ! size) < 0) goto err; } *************** *** 1452,1456 **** static char tuple = TUPLE; ! if ((*self->write_func)(self, &MARKv, 1) < 0) goto finally; --- 1454,1458 ---- static char tuple = TUPLE; ! if (self->write_func(self, &MARKv, 1) < 0) goto finally; *************** *** 1474,1478 **** static char pop_mark = POP_MARK; ! if ((*self->write_func)(self, &pop_mark, 1) < 0) goto finally; } --- 1476,1480 ---- static char pop_mark = POP_MARK; ! if (self->write_func(self, &pop_mark, 1) < 0) goto finally; } *************** *** 1481,1485 **** for (i = 0; i <= len; i++) { ! if ((*self->write_func)(self, &pop, 1) < 0) goto finally; } --- 1483,1487 ---- for (i = 0; i <= len; i++) { ! if (self->write_func(self, &pop, 1) < 0) goto finally; } *************** *** 1494,1498 **** } ! if ((*self->write_func)(self, &tuple, 1) < 0) { goto finally; } --- 1496,1500 ---- } ! if (self->write_func(self, &tuple, 1) < 0) { goto finally; } *************** *** 1514,1518 **** static char tuple = EMPTY_TUPLE; ! return (*self->write_func)(self, &tuple, 1); } --- 1516,1520 ---- static char tuple = EMPTY_TUPLE; ! return self->write_func(self, &tuple, 1); } *************** *** 1543,1547 **** goto finally; ! if ((*self->write_func)(self, s, s_len) < 0) goto finally; --- 1545,1549 ---- goto finally; ! if (self->write_func(self, s, s_len) < 0) goto finally; *************** *** 1556,1560 **** if ((using_appends = (self->bin && (len > 1)))) ! if ((*self->write_func)(self, &MARKv, 1) < 0) goto finally; --- 1558,1562 ---- if ((using_appends = (self->bin && (len > 1)))) ! if (self->write_func(self, &MARKv, 1) < 0) goto finally; *************** *** 1567,1571 **** if (!using_appends) { ! if ((*self->write_func)(self, &append, 1) < 0) goto finally; } --- 1569,1573 ---- if (!using_appends) { ! if (self->write_func(self, &append, 1) < 0) goto finally; } *************** *** 1573,1577 **** if (using_appends) { ! if ((*self->write_func)(self, &appends, 1) < 0) goto finally; } --- 1575,1579 ---- if (using_appends) { ! if (self->write_func(self, &appends, 1) < 0) goto finally; } *************** *** 1609,1613 **** } ! if ((*self->write_func)(self, s, len) < 0) goto finally; --- 1611,1615 ---- } ! if (self->write_func(self, s, len) < 0) goto finally; *************** *** 1625,1629 **** if ((using_setitems = (self->bin && (PyDict_Size(args) > 1)))) ! if ((*self->write_func)(self, &MARKv, 1) < 0) goto finally; --- 1627,1631 ---- if ((using_setitems = (self->bin && (PyDict_Size(args) > 1)))) ! if (self->write_func(self, &MARKv, 1) < 0) goto finally; *************** *** 1637,1641 **** if (!using_setitems) { ! if ((*self->write_func)(self, &setitem, 1) < 0) goto finally; } --- 1639,1643 ---- if (!using_setitems) { ! if (self->write_func(self, &setitem, 1) < 0) goto finally; } *************** *** 1643,1647 **** if (using_setitems) { ! if ((*self->write_func)(self, &setitems, 1) < 0) goto finally; } --- 1645,1649 ---- if (using_setitems) { ! if (self->write_func(self, &setitems, 1) < 0) goto finally; } *************** *** 1670,1674 **** goto finally; ! if ((*self->write_func)(self, &MARKv, 1) < 0) goto finally; --- 1672,1676 ---- goto finally; ! if (self->write_func(self, &MARKv, 1) < 0) goto finally; *************** *** 1725,1744 **** name_str = PyString_AS_STRING((PyStringObject *)name); ! if ((*self->write_func)(self, &inst, 1) < 0) goto finally; ! if ((*self->write_func)(self, module_str, module_size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; ! if ((*self->write_func)(self, name_str, name_size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; } ! else if ((*self->write_func)(self, &obj, 1) < 0) { goto finally; } --- 1727,1746 ---- name_str = PyString_AS_STRING((PyStringObject *)name); ! if (self->write_func(self, &inst, 1) < 0) goto finally; ! if (self->write_func(self, module_str, module_size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; ! if (self->write_func(self, name_str, name_size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; } ! else if (self->write_func(self, &obj, 1) < 0) { goto finally; } *************** *** 1771,1775 **** goto finally; ! if ((*self->write_func)(self, &build, 1) < 0) goto finally; --- 1773,1777 ---- goto finally; ! if (self->write_func(self, &build, 1) < 0) goto finally; *************** *** 1844,1860 **** Py_DECREF(klass); ! if ((*self->write_func)(self, &global, 1) < 0) goto finally; ! if ((*self->write_func)(self, module_str, module_size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; ! if ((*self->write_func)(self, name_str, name_size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; --- 1846,1862 ---- Py_DECREF(klass); ! if (self->write_func(self, &global, 1) < 0) goto finally; ! if (self->write_func(self, module_str, module_size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; ! if (self->write_func(self, name_str, name_size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; *************** *** 1896,1900 **** } ! if ((*self->write_func)(self, &persid, 1) < 0) goto finally; --- 1898,1902 ---- } ! if (self->write_func(self, &persid, 1) < 0) goto finally; *************** *** 1902,1910 **** goto finally; ! if ((*self->write_func)(self, ! PyString_AS_STRING((PyStringObject *)pid), size) < 0) goto finally; ! if ((*self->write_func)(self, "\n", 1) < 0) goto finally; --- 1904,1914 ---- goto finally; ! if (self->write_func(self, ! PyString_AS_STRING( ! (PyStringObject *)pid), ! size) < 0) goto finally; ! if (self->write_func(self, "\n", 1) < 0) goto finally; *************** *** 1913,1917 **** } else if (save(self, pid, 1) >= 0) { ! if ((*self->write_func)(self, &binpersid, 1) < 0) res = -1; else --- 1917,1921 ---- } else if (save(self, pid, 1) >= 0) { ! if (self->write_func(self, &binpersid, 1) < 0) res = -1; else *************** *** 1943,1947 **** return -1; ! if ((*self->write_func)(self, &reduce, 1) < 0) return -1; --- 1947,1951 ---- return -1; ! if (self->write_func(self, &reduce, 1) < 0) return -1; *************** *** 1961,1965 **** return -1; ! if ((*self->write_func)(self, &build, 1) < 0) return -1; } --- 1965,1969 ---- return -1; ! if (self->write_func(self, &build, 1) < 0) return -1; } *************** *** 2756,2760 **** long l; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; --- 2760,2764 ---- long l; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; *************** *** 2851,2855 **** char *s; ! if ((*self->read_func)(self, &s, 4) < 0) return -1; --- 2855,2859 ---- char *s; ! if (self->read_func(self, &s, 4) < 0) return -1; *************** *** 2863,2867 **** char *s; ! if ((*self->read_func)(self, &s, 1) < 0) return -1; --- 2867,2871 ---- char *s; ! if (self->read_func(self, &s, 1) < 0) return -1; *************** *** 2875,2879 **** char *s; ! if ((*self->read_func)(self, &s, 2) < 0) return -1; --- 2879,2883 ---- char *s; ! if (self->read_func(self, &s, 2) < 0) return -1; *************** *** 2888,2892 **** int len, res = -1; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; --- 2892,2896 ---- int len, res = -1; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; *************** *** 2953,2957 **** double d; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; --- 2957,2961 ---- double d; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; *************** *** 2988,2992 **** char *p; ! if ((*self->read_func)(self, &p, 8) < 0) return -1; --- 2992,2996 ---- char *p; ! if (self->read_func(self, &p, 8) < 0) return -1; *************** *** 3052,3056 **** char *s, *p; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; --- 3056,3060 ---- char *s, *p; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (!( s=pystrndup(s,len))) return -1; *************** *** 3094,3102 **** char *s; ! if ((*self->read_func)(self, &s, 4) < 0) return -1; l = calc_binint(s, 4); ! if ((*self->read_func)(self, &s, l) < 0) return -1; --- 3098,3106 ---- char *s; ! if (self->read_func(self, &s, 4) < 0) return -1; l = calc_binint(s, 4); ! if (self->read_func(self, &s, l) < 0) return -1; *************** *** 3116,3125 **** char *s; ! if ((*self->read_func)(self, &s, 1) < 0) return -1; l = (unsigned char)s[0]; ! if ((*self->read_func)(self, &s, l) < 0) return -1; if (!( py_string = PyString_FromStringAndSize(s, l))) return -1; --- 3120,3129 ---- char *s; ! if (self->read_func(self, &s, 1) < 0) return -1; l = (unsigned char)s[0]; ! if (self->read_func(self, &s, l) < 0) return -1; if (!( py_string = PyString_FromStringAndSize(s, l))) return -1; *************** *** 3138,3142 **** char *s; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 1) return bad_readline(); --- 3142,3146 ---- char *s; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 1) return bad_readline(); *************** *** 3161,3169 **** char *s; ! if ((*self->read_func)(self, &s, 4) < 0) return -1; l = calc_binint(s, 4); ! if ((*self->read_func)(self, &s, l) < 0) return -1; --- 3165,3173 ---- char *s; ! if (self->read_func(self, &s, 4) < 0) return -1; l = calc_binint(s, 4); ! if (self->read_func(self, &s, l) < 0) return -1; *************** *** 3345,3354 **** if ((i = marker(self)) < 0) return -1; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); module_name = PyString_FromStringAndSize(s, len - 1); if (!module_name) return -1; ! if ((len = (*self->readline_func)(self, &s)) >= 0) { if (len < 2) return bad_readline(); if ((class_name = PyString_FromStringAndSize(s, len - 1))) { --- 3349,3358 ---- if ((i = marker(self)) < 0) return -1; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); module_name = PyString_FromStringAndSize(s, len - 1); if (!module_name) return -1; ! if ((len = self->readline_func(self, &s)) >= 0) { if (len < 2) return bad_readline(); if ((class_name = PyString_FromStringAndSize(s, len - 1))) { *************** *** 3382,3391 **** char *s; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); module_name = PyString_FromStringAndSize(s, len - 1); if (!module_name) return -1; ! if ((len = (*self->readline_func)(self, &s)) >= 0) { if (len < 2) { Py_DECREF(module_name); --- 3386,3395 ---- char *s; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); module_name = PyString_FromStringAndSize(s, len - 1); if (!module_name) return -1; ! if ((len = self->readline_func(self, &s)) >= 0) { if (len < 2) { Py_DECREF(module_name); *************** *** 3414,3418 **** if (self->pers_func) { ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); --- 3418,3422 ---- if (self->pers_func) { ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); *************** *** 3547,3551 **** int rc; ! if ((len = (*self->readline_func)(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); --- 3551,3555 ---- int rc; ! if ((len = self->readline_func(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); *************** *** 3574,3578 **** int rc; ! if ((*self->read_func)(self, &s, 1) < 0) return -1; key = (unsigned char)s[0]; --- 3578,3582 ---- int rc; ! if (self->read_func(self, &s, 1) < 0) return -1; key = (unsigned char)s[0]; *************** *** 3602,3606 **** int rc; ! if ((*self->read_func)(self, &s, 4) < 0) return -1; c = (unsigned char)s[0]; --- 3606,3610 ---- int rc; ! if (self->read_func(self, &s, 4) < 0) return -1; c = (unsigned char)s[0]; *************** *** 3636,3640 **** char *s; ! if ((l = (*self->readline_func)(self, &s)) < 0) return -1; if (l < 2) return bad_readline(); if (!( len=self->stack->length )) return stackUnderflow(); --- 3640,3644 ---- char *s; ! if ((l = self->readline_func(self, &s)) < 0) return -1; if (l < 2) return bad_readline(); if (!( len=self->stack->length )) return stackUnderflow(); *************** *** 3655,3659 **** int len; ! if ((*self->read_func)(self, &s, 1) < 0) return -1; if (!( (len=self->stack->length) > 0 )) return stackUnderflow(); --- 3659,3663 ---- int len; ! if (self->read_func(self, &s, 1) < 0) return -1; if (!( (len=self->stack->length) > 0 )) return stackUnderflow(); *************** *** 3677,3681 **** int len; ! if ((*self->read_func)(self, &s, 4) < 0) return -1; if (!( len=self->stack->length )) return stackUnderflow(); --- 3681,3685 ---- int len; ! if (self->read_func(self, &s, 4) < 0) return -1; if (!( len=self->stack->length )) return stackUnderflow(); *************** *** 3933,3937 **** while (1) { ! if ((*self->read_func)(self, &s, 1) < 0) break; --- 3937,3941 ---- while (1) { ! if (self->read_func(self, &s, 1) < 0) break; *************** *** 4215,4220 **** if ((i = marker(self)) < 0) return -1; Pdata_clear(self->stack, i); ! if ((*self->readline_func)(self, &s) < 0) return -1; ! if ((*self->readline_func)(self, &s) < 0) return -1; PDATA_APPEND(self->stack, Py_None,-1); return 0; --- 4219,4224 ---- if ((i = marker(self)) < 0) return -1; Pdata_clear(self->stack, i); ! if (self->readline_func(self, &s) < 0) return -1; ! if (self->readline_func(self, &s) < 0) return -1; PDATA_APPEND(self->stack, Py_None,-1); return 0; *************** *** 4226,4231 **** char *s; ! if ((*self->readline_func)(self, &s) < 0) return -1; ! if ((*self->readline_func)(self, &s) < 0) return -1; PDATA_APPEND(self->stack, Py_None,-1); return 0; --- 4230,4235 ---- char *s; ! if (self->readline_func(self, &s) < 0) return -1; ! if (self->readline_func(self, &s) < 0) return -1; PDATA_APPEND(self->stack, Py_None,-1); return 0; *************** *** 4261,4265 **** while (1) { ! if ((*self->read_func)(self, &s, 1) < 0) break; --- 4265,4269 ---- while (1) { ! if (self->read_func(self, &s, 1) < 0) break; From jvr@users.sourceforge.net Sun Feb 2 18:56:40 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sun, 02 Feb 2003 10:56:40 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv31923 Modified Files: bundlebuilder.py Log Message: jeez, now I know why I shouldn't even _want_ to learn sh. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** bundlebuilder.py 1 Feb 2003 08:34:46 -0000 1.5 --- bundlebuilder.py 2 Feb 2003 18:56:37 -0000 1.6 *************** *** 255,265 **** #!/bin/sh ! execdir=$(dirname ${0}) executable=${execdir}/%(executable)s ! resdir=$(dirname ${execdir})/Resources main=${resdir}/%(mainprogram)s PYTHONPATH=$resdir export PYTHONPATH ! exec ${executable} ${main} ${1} """ --- 255,265 ---- #!/bin/sh ! execdir=$(dirname "${0}") executable=${execdir}/%(executable)s ! resdir=$(dirname "${execdir}")/Resources main=${resdir}/%(mainprogram)s PYTHONPATH=$resdir export PYTHONPATH ! exec "${executable}" "${main}" "${1}" """ *************** *** 620,624 **** --nib=NAME main nib name -c, --creator=CCCC 4-char creator code (default: '????') ! --iconfile=FILE filename of the icon (an .icns file) to be used as the Finder icon -l, --link symlink files/folder instead of copying them --- 620,624 ---- --nib=NAME main nib name -c, --creator=CCCC 4-char creator code (default: '????') ! --iconfile=FILE filename of the icon (an .icns file) to be used as the Finder icon -l, --link symlink files/folder instead of copying them From nnorwitz@users.sourceforge.net Sun Feb 2 19:06:12 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:06:12 -0800 Subject: [Python-checkins] python/dist/src/Doc/api exceptions.tex,1.3.6.4,1.3.6.5 init.tex,1.2,1.2.10.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv7057/api Modified Files: Tag: release22-maint exceptions.tex init.tex Log Message: Backport: date: 2002/12/06 22:42:13; author: theller; Typo: propogate -> propagate Index: exceptions.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/exceptions.tex,v retrieving revision 1.3.6.4 retrieving revision 1.3.6.5 diff -C2 -d -r1.3.6.4 -r1.3.6.5 *** exceptions.tex 24 Oct 2002 20:55:07 -0000 1.3.6.4 --- exceptions.tex 2 Feb 2003 19:06:03 -0000 1.3.6.5 *************** *** 20,24 **** error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or ! carefully propogated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. --- 20,24 ---- error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or ! carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. Index: init.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/init.tex,v retrieving revision 1.2 retrieving revision 1.2.10.1 diff -C2 -d -r1.2 -r1.2.10.1 *** init.tex 16 Oct 2001 19:23:55 -0000 1.2 --- init.tex 2 Feb 2003 19:06:04 -0000 1.2.10.1 *************** *** 656,660 **** store state in the dictionary. If this function returns \NULL, an exception has been raised and the caller should allow it to ! propogate. \end{cfuncdesc} --- 656,660 ---- store state in the dictionary. If this function returns \NULL, an exception has been raised and the caller should allow it to ! propagate. \end{cfuncdesc} *************** *** 714,718 **** being executed. The effect of this is that as exception propogation causes the Python stack to unwind, the callback is called upon ! return to each frame as the exception propogates. Only trace functions receives these events; they are not needed by the profiler. --- 714,718 ---- being executed. The effect of this is that as exception propogation causes the Python stack to unwind, the callback is called upon ! return to each frame as the exception propagates. Only trace functions receives these events; they are not needed by the profiler. From nnorwitz@users.sourceforge.net Sun Feb 2 19:07:06 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:07:06 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext run-func.c,1.2.14.1,1.2.14.2 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv7883/ext Modified Files: Tag: release22-maint run-func.c Log Message: backport: revision 1.4 date: 2002/12/17 00:40:38; author: nnorwitz; state: Exp; lines: +8 -3 Fix SF # 626275, missing DECREF's in embedding example Tested w/valgrind, all paths except the return on PyInt_AsLong() failure I think I got all of these right. Index: run-func.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/run-func.c,v retrieving revision 1.2.14.1 retrieving revision 1.2.14.2 diff -C2 -d -r1.2.14.1 -r1.2.14.2 *** run-func.c 2 Dec 2002 04:44:33 -0000 1.2.14.1 --- run-func.c 2 Feb 2003 19:07:01 -0000 1.2.14.2 *************** *** 18,21 **** --- 18,23 ---- pModule = PyImport_Import(pName); + Py_DECREF(pName); + if (pModule != NULL) { pDict = PyModule_GetDict(pModule); *************** *** 30,33 **** --- 32,37 ---- pValue = PyInt_FromLong(atoi(argv[i + 3])); if (!pValue) { + Py_DECREF(pArgs); + Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; *************** *** 37,40 **** --- 41,45 ---- } pValue = PyObject_CallObject(pFunc, pArgs); + Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyInt_AsLong(pValue)); *************** *** 42,54 **** } else { PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } - Py_DECREF(pArgs); /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { ! PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } --- 47,60 ---- } else { + Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { ! if (PyErr_Occurred()) ! PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } *************** *** 60,64 **** return 1; } - Py_DECREF(pName); Py_Finalize(); return 0; --- 66,69 ---- From nnorwitz@users.sourceforge.net Sun Feb 2 19:09:07 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:09:07 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libfuncs.tex,1.100.4.14,1.100.4.15 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv9298/lib Modified Files: Tag: release22-maint libfuncs.tex Log Message: backports: revision 1.127 date: 2003/01/04 02:16:22; author: rhettinger; state: Exp; lines: +1 -1 SF bug #655271: Slightly modify locals() doc Clarify the operation of locals(). revision 1.125 date: 2002/12/17 01:08:06; author: nnorwitz; state: Exp; lines: +6 -1 Fix SF # 641111, Undocumented side effect of eval Try to clear up confusion about the current globals being copied into a globals dict passed to eval(). This wording (more or less) was suggested in bug report. It should probably be made clearer. revision 1.124 date: 2002/12/17 01:02:57; author: nnorwitz; state: Exp; lines: +78 -0 Fix SF #642742, property() builtin not documented Added doc for functions new to 2.2: classmethod property staticmethod super Taken from docstrings. Could use review. Hope there wasn't a reason why these shouldn't have been added. Index: libfuncs.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libfuncs.tex,v retrieving revision 1.100.4.14 retrieving revision 1.100.4.15 diff -C2 -d -r1.100.4.14 -r1.100.4.15 *** libfuncs.tex 2 Jan 2003 04:54:22 -0000 1.100.4.14 --- libfuncs.tex 2 Feb 2003 19:08:58 -0000 1.100.4.15 *************** *** 83,86 **** --- 83,97 ---- \end{funcdesc} + \begin{funcdesc}{bool}{x} + Convert a value to a Boolean, using the standard truth testing + procedure. If \code{x} is false, this returns \code{False}; + otherwise it returns \code{True}. \code{bool} is also a class, + which is a subclass of \code{int}. Class \code{bool} cannot be + subclassed further. Its only instances are \code{False} and + \code{True}. + \indexii{Boolean}{type} + \versionadded{2.2.1} + \end{funcdesc} + \begin{funcdesc}{buffer}{object\optional{, offset\optional{, size}}} The \var{object} argument must be an object that supports the buffer *************** *** 110,113 **** --- 121,147 ---- \end{funcdesc} + \begin{funcdesc}{classmethod}{function} + Return a class method for \var{function}. + + A class method receives the class as implicit first argument, + just like an instance method receives the instance. + To declare a class method, use this idiom: + + \begin{verbatim} + class C: + def f(cls, arg1, arg2, ...): ... + f = classmethod(f) + \end{verbatim} + + It can be called either on the class (e.g. C.f()) or on an instance + (e.g. C().f()). The instance is ignored except for its class. + If a class method is called for a derived class, the derived class + object is passed as the implied first argument. + + Class methods are different than C++ or Java static methods. + If you want those, see \ref{staticmethod}. + \versionadded{2.2} + \end{funcdesc} + \begin{funcdesc}{cmp}{x, y} Compare the two objects \var{x} and \var{y} and return an integer *************** *** 265,269 **** expression (technically speaking, a condition list) using the \var{globals} and \var{locals} dictionaries as global and local name ! space. If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \keyword{eval} is --- 299,308 ---- expression (technically speaking, a condition list) using the \var{globals} and \var{locals} dictionaries as global and local name ! space. If the \var{globals} dictionary is present and lacks ! '__builtins__', the current globals are copied into \var{globals} before ! \var{expression} is parsed. This means that \var{expression} ! normally has full access to the standard ! \refmodule[builtin]{__builtin__} module and restricted environments ! are propagated. If the \var{locals} dictionary is omitted it defaults to the \var{globals} dictionary. If both dictionaries are omitted, the expression is executed in the environment where \keyword{eval} is *************** *** 546,550 **** \begin{funcdesc}{locals}{} ! Return a dictionary representing the current local symbol table. \warning{The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the --- 585,589 ---- \begin{funcdesc}{locals}{} ! Update and return a dictionary representing the current local symbol table. \warning{The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the *************** *** 633,636 **** --- 672,694 ---- \end{funcdesc} + \begin{funcdesc}{property}{\optional{fget\optional{, fset\optional{, fdel\optional{, doc}}}}} + Return a property attribute for new-style classes (classes that + derive from \function{object}. + + \var{fget} is a function for getting an attribute value, likewise + \var{fset} is a function for setting, and \var{fdel} a function + for del'ing, an attribute. Typical use is to define a managed attribute x: + + \begin{verbatim} + class C(object): + def getx(self): return self.__x + def setx(self, value): self.__x = value + def delx(self): del self.__x + x = property(getx, setx, delx, "I'm the 'x' property.") + \end{verbatim} + + \versionadded{2.2} + \end{funcdesc} + \begin{funcdesc}{range}{\optional{start,} stop\optional{, step}} This is a versatile function to create lists containing arithmetic *************** *** 778,781 **** --- 836,874 ---- indexing syntax is used. For example: \samp{a[start:stop:step]} or \samp{a[start:stop, i]}. + \end{funcdesc} + + \begin{funcdesc}{staticmethod}{function} + Return a static method for \var{function}. + + A static method does not receive an implicit first argument. + To declare a static method, use this idiom: + + \begin{verbatim} + class C: + def f(arg1, arg2, ...): ... + f = staticmethod(f) + \end{verbatim} + + It can be called either on the class (e.g. C.f()) or on an instance + (e.g. C().f()). The instance is ignored except for its class. + + Static methods in Python are similar to those found in Java or C++. + For a more advanced concept, see \ref{classmethod}. + \versionadded{2.2} + \end{funcdesc} + + \begin{funcdesc}{super}{type\optional{object-or-type}} + Return the superclass of \var{type}. If the second argument is omitted + the super object returned is unbound. If the second argument is an + object, isinstance(obj, type) must be true. If the second argument is a + type, issubclass(type2, type) must be true. + + A typical use for calling a cooperative superclass method is: + \begin{verbatim} + class C(B): + def meth(self, arg): + super(C, self).meth(arg) + \end{verbatim} + \versionadded{2.2} \end{funcdesc} From nnorwitz@users.sourceforge.net Sun Feb 2 19:23:18 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:23:18 -0800 Subject: [Python-checkins] python/dist/src/Lib macpath.py,1.31.10.2,1.31.10.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv18473/Lib Modified Files: Tag: release22-maint macpath.py Log Message: Backport: revision 1.44 date: 2003/01/15 22:45:48; author: jackjansen; state: Exp; lines: +5 -0 Added ismount(). Fixes #661762, bugfix candidate. Index: macpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/macpath.py,v retrieving revision 1.31.10.2 retrieving revision 1.31.10.3 diff -C2 -d -r1.31.10.2 -r1.31.10.3 *** macpath.py 13 Jan 2003 19:29:35 -0000 1.31.10.2 --- macpath.py 2 Feb 2003 19:23:13 -0000 1.31.10.3 *************** *** 94,97 **** --- 94,102 ---- def basename(s): return split(s)[1] + def ismount(s): + if not isabs(s): + return False + components = split(s) + return len(components) == 2 and components[1] == '' def isdir(s): From nnorwitz@users.sourceforge.net Sun Feb 2 19:24:41 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:24:41 -0800 Subject: [Python-checkins] python/dist/src/Lib threading.py,1.19.12.2,1.19.12.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv19291/Lib Modified Files: Tag: release22-maint threading.py Log Message: backport: revision 1.29 date: 2002/11/21 21:08:39; author: gvanrossum; state: Exp; lines: +14 -8 The _Event class should be more careful with releasing its lock when interrupted. A try/finally will do nicely. Maybe other classes need this too, but since they manipulate more state it's less clear that that is always the right thing, and I'm in a hurry. Index: threading.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/threading.py,v retrieving revision 1.19.12.2 retrieving revision 1.19.12.3 diff -C2 -d -r1.19.12.2 -r1.19.12.3 *** threading.py 19 Feb 2002 03:02:33 -0000 1.19.12.2 --- threading.py 2 Feb 2003 19:24:38 -0000 1.19.12.3 *************** *** 317,334 **** def set(self): self.__cond.acquire() ! self.__flag = 1 ! self.__cond.notifyAll() ! self.__cond.release() def clear(self): self.__cond.acquire() ! self.__flag = 0 ! self.__cond.release() def wait(self, timeout=None): self.__cond.acquire() ! if not self.__flag: ! self.__cond.wait(timeout) ! self.__cond.release() # Helper to generate new thread names --- 317,340 ---- def set(self): self.__cond.acquire() ! try: ! self.__flag = 1 ! self.__cond.notifyAll() ! finally: ! self.__cond.release() def clear(self): self.__cond.acquire() ! try: ! self.__flag = 0 ! finally: ! self.__cond.release() def wait(self, timeout=None): self.__cond.acquire() ! try: ! if not self.__flag: ! self.__cond.wait(timeout) ! finally: ! self.__cond.release() # Helper to generate new thread names From nnorwitz@users.sourceforge.net Sun Feb 2 19:25:26 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:25:26 -0800 Subject: [Python-checkins] python/dist/src/Objects structseq.c,1.3.6.3,1.3.6.4 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv19851/Objects Modified Files: Tag: release22-maint structseq.c Log Message: backport: revision 1.11 date: 2002/12/18 23:20:39; author: nnorwitz; state: Exp; lines: +6 -2 SF # 654974, fix unchecked return values in structseq Check return values after memory allocation. Index: structseq.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/structseq.c,v retrieving revision 1.3.6.3 retrieving revision 1.3.6.4 diff -C2 -d -r1.3.6.3 -r1.3.6.4 *** structseq.c 7 Mar 2002 15:16:07 -0000 1.3.6.3 --- structseq.c 2 Feb 2003 19:25:22 -0000 1.3.6.4 *************** *** 141,144 **** --- 141,147 ---- res = (PyStructSequence*) PyStructSequence_New(type); + if (res == NULL) { + return NULL; + } for (i = 0; i < len; ++i) { PyObject *v = PySequence_Fast_GET_ITEM(arg, i); *************** *** 347,350 **** --- 350,355 ---- members = PyMem_NEW(PyMemberDef, n_members+1); + if (members == NULL) + return; for (i = 0; i < n_members; ++i) { From nnorwitz@users.sourceforge.net Sun Feb 2 19:26:28 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:26:28 -0800 Subject: [Python-checkins] python/dist/src/PC _winreg.c,1.8,1.8.26.1 Message-ID: Update of /cvsroot/python/python/dist/src/PC In directory sc8-pr-cvs1:/tmp/cvs-serv20494/PC Modified Files: Tag: release22-maint _winreg.c Log Message: backport: revision 1.14 date: 2003/01/15 23:38:15; author: mhammond; state: Exp; lines: +1 -1 Correct docstring for SetValueEx() revision 1.13 date: 2002/12/20 20:13:35; author: theller; state: Exp; lines: +1 -1 Fix an error message in the _winreg module. The error message referred to a constant in the 'win32con' module, but this constant is also defined in the _winreg module itself. Index: _winreg.c =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/_winreg.c,v retrieving revision 1.8 retrieving revision 1.8.26.1 diff -C2 -d -r1.8 -r1.8.26.1 *** _winreg.c 28 Jul 2000 03:44:41 -0000 1.8 --- _winreg.c 2 Feb 2003 19:26:25 -0000 1.8.26.1 *************** *** 260,264 **** "\n" "key is an already open key, or any one of the predefined HKEY_* constants.\n" ! "sub_key is a string that names the subkey with which the value is associated.\n" "type is an integer that specifies the type of the data. This should be one of:\n" " REG_BINARY -- Binary data in any form.\n" --- 260,264 ---- "\n" "key is an already open key, or any one of the predefined HKEY_* constants.\n" ! "value_name is a string containing the name of the value to set, or None\n" "type is an integer that specifies the type of the data. This should be one of:\n" " REG_BINARY -- Binary data in any form.\n" *************** *** 1317,1321 **** if (typ != REG_SZ) { PyErr_SetString(PyExc_TypeError, ! "Type must be win32con.REG_SZ"); return NULL; } --- 1317,1321 ---- if (typ != REG_SZ) { PyErr_SetString(PyExc_TypeError, ! "Type must be _winreg.REG_SZ"); return NULL; } From nnorwitz@users.sourceforge.net Sun Feb 2 19:34:21 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:34:21 -0800 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.68,2.68.6.1 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv27568/Modules Modified Files: Tag: release22-maint parsermodule.c Log Message: backport: revision 2.75 date: 2003/01/29 14:20:22; author: mwh; state: Exp; lines: +2 -0 Teach the parsermodule about floor division. Fixes [ 676521 ] parser module validation failure Index: parsermodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/parsermodule.c,v retrieving revision 2.68 retrieving revision 2.68.6.1 diff -C2 -d -r2.68 -r2.68.6.1 *** parsermodule.c 8 Dec 2001 18:02:57 -0000 2.68 --- parsermodule.c 2 Feb 2003 19:34:14 -0000 2.68.6.1 *************** *** 1439,1442 **** --- 1439,1443 ---- || strcmp(s, "*=") == 0 || strcmp(s, "/=") == 0 + || strcmp(s, "//=") == 0 || strcmp(s, "%=") == 0 || strcmp(s, "&=") == 0 *************** *** 2094,2097 **** --- 2095,2099 ---- res = (((TYPE(CHILD(tree, pos)) == STAR) || (TYPE(CHILD(tree, pos)) == SLASH) + || (TYPE(CHILD(tree, pos)) == DOUBLESLASH) || (TYPE(CHILD(tree, pos)) == PERCENT)) && validate_factor(CHILD(tree, pos + 1))); From nnorwitz@users.sourceforge.net Sun Feb 2 19:34:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:34:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_parser.py,1.10,1.10.12.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv27870/Lib/test Modified Files: Tag: release22-maint test_parser.py Log Message: backport: revision 1.14 date: 2003/01/29 14:20:23; author: mwh; state: Exp; lines: +5 -0 Teach the parsermodule about floor division. Fixes [ 676521 ] parser module validation failure Index: test_parser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_parser.py,v retrieving revision 1.10 retrieving revision 1.10.12.1 diff -C2 -d -r1.10 -r1.10.12.1 *** test_parser.py 20 Sep 2001 21:33:42 -0000 1.10 --- test_parser.py 2 Feb 2003 19:34:40 -0000 1.10.12.1 *************** *** 55,58 **** --- 55,62 ---- self.check_expr("foo(a, b, c, **kw)") self.check_expr("foo + bar") + self.check_expr("foo - bar") + self.check_expr("foo * bar") + self.check_expr("foo / bar") + self.check_expr("foo // bar") self.check_expr("lambda: 0") self.check_expr("lambda x: 0") *************** *** 89,92 **** --- 93,97 ---- self.check_suite("a *= b") self.check_suite("a /= b") + self.check_suite("a //= b") self.check_suite("a %= b") self.check_suite("a &= b") From nnorwitz@users.sourceforge.net Sun Feb 2 19:37:53 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:37:53 -0800 Subject: [Python-checkins] python/dist/src/Objects classobject.c,2.154.8.2,2.154.8.3 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv29591/Objects Modified Files: Tag: release22-maint classobject.c Log Message: backport: revision 2.164 date: 2002/10/29 18:36:40; author: gvanrossum; state: Exp; lines: +12 -13 Since properties are supported here, is possible that instance_getattr2() raises an exception. Fix all code that made this assumption. Index: classobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/classobject.c,v retrieving revision 2.154.8.2 retrieving revision 2.154.8.3 diff -C2 -d -r2.154.8.2 -r2.154.8.3 *** classobject.c 18 Oct 2002 14:06:02 -0000 2.154.8.2 --- classobject.c 2 Feb 2003 19:37:32 -0000 2.154.8.3 *************** *** 544,547 **** --- 544,551 ---- init = instance_getattr2(inst, initstr); if (init == NULL) { + if (PyErr_Occurred()) { + Py_DECREF(inst); + return NULL; + } if ((arg != NULL && (!PyTuple_Check(arg) || PyTuple_Size(arg) != 0)) *************** *** 675,679 **** } v = instance_getattr2(inst, name); ! if (v == NULL) { PyErr_Format(PyExc_AttributeError, "%.50s instance has no attribute '%.400s'", --- 679,683 ---- } v = instance_getattr2(inst, name); ! if (v == NULL && !PyErr_Occurred()) { PyErr_Format(PyExc_AttributeError, "%.50s instance has no attribute '%.400s'", *************** *** 1760,1782 **** instance_getattr2 directly because it will not set an exception on failure. */ ! if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) { ! method = instance_getattr2((PyInstanceObject *)v, name_op[op]); ! if (method == NULL) { ! assert(!PyErr_Occurred()); ! res = Py_NotImplemented; ! Py_INCREF(res); ! return res; ! } ! } else { method = PyObject_GetAttr(v, name_op[op]); ! if (method == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); - res = Py_NotImplemented; - Py_INCREF(res); - return res; } } --- 1764,1781 ---- instance_getattr2 directly because it will not set an exception on failure. */ ! if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) ! method = instance_getattr2((PyInstanceObject *)v, name_op[op]); ! else method = PyObject_GetAttr(v, name_op[op]); ! if (method == NULL) { ! if (PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } + res = Py_NotImplemented; + Py_INCREF(res); + return res; } From nnorwitz@users.sourceforge.net Sun Feb 2 19:38:22 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 11:38:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_class.py,1.7.6.1,1.7.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv29958/Lib/test Modified Files: Tag: release22-maint test_class.py Log Message: backport: revision 1.10 date: 2002/10/29 19:08:29; author: gvanrossum; state: Exp; lines: +27 -0 Added test for this fix to classobject.c: Since properties are supported here, is possible that instance_getattr2() raises an exception. Fix all code that made this assumption. Index: test_class.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_class.py,v retrieving revision 1.7.6.1 retrieving revision 1.7.6.2 diff -C2 -d -r1.7.6.1 -r1.7.6.2 *** test_class.py 13 Jun 2002 21:36:35 -0000 1.7.6.1 --- test_class.py 2 Feb 2003 19:38:19 -0000 1.7.6.2 *************** *** 289,290 **** --- 289,317 ---- else: raise TestFailed, "how could this not have overflowed the stack?" + + + # Tests for exceptions raised in instance_getattr2(). + + def booh(self): + raise AttributeError, "booh" + + class A: + a = property(booh) + try: + A().a # Raised AttributeError: A instance has no attribute 'a' + except AttributeError, x: + if str(x) is not "booh": + print "attribute error for A().a got masked:", str(x) + + class E: + __eq__ = property(booh) + E() == E() # In debug mode, caused a C-level assert() to fail + + class I: + __init__ = property(booh) + try: + I() # In debug mode, printed XXX undetected error and raises AttributeError + except AttributeError, x: + pass + else: + print "attribute error for I.__init__ got masked" From nnorwitz@users.sourceforge.net Sun Feb 2 20:00:03 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 02 Feb 2003 12:00:03 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.126.4.31,2.126.4.32 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv8324/Objects Modified Files: Tag: release22-maint typeobject.c Log Message: backport: revision 2.196 date: 2002/12/07 21:39:16; author: tim_one; state: Exp; lines: +27 -28 slot_nb_nonzero(): Another leak uncovered by the sandbox datetime tests. I found the logic too confusing to follow here, so rewrote more than was likely absolutely necessary. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.126.4.31 retrieving revision 2.126.4.32 diff -C2 -d -r2.126.4.31 -r2.126.4.32 *** typeobject.c 7 Jan 2003 21:47:44 -0000 2.126.4.31 --- typeobject.c 2 Feb 2003 19:59:59 -0000 2.126.4.32 *************** *** 3114,3119 **** slot_nb_nonzero(PyObject *self) { ! PyObject *func, *res; static PyObject *nonzero_str, *len_str; func = lookup_maybe(self, "__nonzero__", &nonzero_str); --- 3114,3120 ---- slot_nb_nonzero(PyObject *self) { ! PyObject *func, *args; static PyObject *nonzero_str, *len_str; + int result = -1; func = lookup_maybe(self, "__nonzero__", &nonzero_str); *************** *** 3122,3137 **** return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) { ! if (PyErr_Occurred()) ! return -1; ! else ! return 1; } } - res = PyObject_CallObject(func, NULL); Py_DECREF(func); ! if (res == NULL) ! return -1; ! return PyObject_IsTrue(res); } --- 3123,3140 ---- return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) ! return PyErr_Occurred() ? -1 : 1; ! } ! args = PyTuple_New(0); ! if (args != NULL) { ! PyObject *temp = PyObject_Call(func, args, NULL); ! Py_DECREF(args); ! if (temp != NULL) { ! result = PyObject_IsTrue(temp); ! Py_DECREF(temp); } } Py_DECREF(func); ! return result; } From tim_one@users.sourceforge.net Sun Feb 2 20:29:41 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 12:29:41 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.36,1.37 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28209/Lib/test Modified Files: pickletester.py Log Message: cPickle support for TUPLE[123]. Incidentally plugged several undetected overflow holes in Pdata_grow(). Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** pickletester.py 2 Feb 2003 17:59:11 -0000 1.36 --- pickletester.py 2 Feb 2003 20:29:38 -0000 1.37 *************** *** 485,488 **** --- 485,509 ---- def test_short_tuples(self): + # Map (proto, len(tuple)) to expected opcode. + expected_opcode = {(0, 0): pickle.TUPLE, + (0, 1): pickle.TUPLE, + (0, 2): pickle.TUPLE, + (0, 3): pickle.TUPLE, + (0, 4): pickle.TUPLE, + + (1, 0): pickle.EMPTY_TUPLE, + (1, 1): pickle.TUPLE, + (1, 2): pickle.TUPLE, + (1, 3): pickle.TUPLE, + (1, 4): pickle.TUPLE, + + (2, 0): pickle.EMPTY_TUPLE, + (2, 1): pickle.TUPLE1, + (2, 2): pickle.TUPLE2, + (2, 3): pickle.TUPLE3, + (2, 4): pickle.TUPLE, + } + all_tuple_opcodes = (pickle.TUPLE, pickle.EMPTY_TUPLE, + pickle.TUPLE1, pickle.TUPLE2, pickle.TUPLE3) a = () b = (1,) *************** *** 495,498 **** --- 516,529 ---- y = self.loads(s) self.assertEqual(x, y, (proto, x, s, y)) + + # Verify that the protocol-correct tuple-building opcode + # was generated. + expected = expected_opcode[proto, len(x)] + for opcode in s: + if opcode in all_tuple_opcodes: + self.assertEqual(expected, opcode) + break + else: + self.fail("didn't find a tuple-building opcode in pickle") def test_singletons(self): From tim_one@users.sourceforge.net Sun Feb 2 20:29:40 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 12:29:40 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.139,1.140 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv28209/Lib Modified Files: pickle.py Log Message: cPickle support for TUPLE[123]. Incidentally plugged several undetected overflow holes in Pdata_grow(). Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.139 retrieving revision 1.140 diff -C2 -d -r1.139 -r1.140 *** pickle.py 2 Feb 2003 07:51:32 -0000 1.139 --- pickle.py 2 Feb 2003 20:29:38 -0000 1.140 *************** *** 622,627 **** n = len(obj) ! if n == 0 and proto: ! write(EMPTY_TUPLE) return --- 622,630 ---- n = len(obj) ! if n == 0: ! if proto: ! write(EMPTY_TUPLE) ! else: ! write(MARK + TUPLE) return *************** *** 640,644 **** return ! # proto 0, or proto 1 and tuple isn't empty, or proto > 1 and tuple # has more than 3 elements. write(MARK) --- 643,647 ---- return ! # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple # has more than 3 elements. write(MARK) *************** *** 646,650 **** save(element) ! if n and id(obj) in memo: # Subtle. d was not in memo when we entered save_tuple(), so # the process of saving the tuple's elements must have saved --- 649,653 ---- save(element) ! if id(obj) in memo: # Subtle. d was not in memo when we entered save_tuple(), so # the process of saving the tuple's elements must have saved *************** *** 661,668 **** return ! # No recursion (including the empty-tuple case for protocol 0). self.write(TUPLE) ! if obj: # No need to memoize empty tuple ! self.memoize(obj) dispatch[TupleType] = save_tuple --- 664,670 ---- return ! # No recursion. self.write(TUPLE) ! self.memoize(obj) dispatch[TupleType] = save_tuple From tim_one@users.sourceforge.net Sun Feb 2 20:29:41 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 02 Feb 2003 12:29:41 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.115,2.116 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv28209/Modules Modified Files: cPickle.c Log Message: cPickle support for TUPLE[123]. Incidentally plugged several undetected overflow holes in Pdata_grow(). Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.115 retrieving revision 2.116 diff -C2 -d -r2.115 -r2.116 *** cPickle.c 2 Feb 2003 18:29:33 -0000 2.115 --- cPickle.c 2 Feb 2003 20:29:39 -0000 2.116 *************** *** 111,115 **** typedef struct { PyObject_HEAD ! int length, size; PyObject **data; } Pdata; --- 111,116 ---- typedef struct { PyObject_HEAD ! int length; /* number of initial slots in data currently used */ ! int size; /* number of slots in data allocated */ PyObject **data; } Pdata; *************** *** 121,128 **** PyObject **p; ! for (i=self->length, p=self->data; --i >= 0; p++) Py_DECREF(*p); ! ! if (self->data) free(self->data); ! PyObject_Del(self); } --- 122,130 ---- PyObject **p; ! for (i = self->length, p = self->data; --i >= 0; p++) { ! Py_DECREF(*p); ! } ! if (self->data) ! free(self->data); PyObject_Del(self); } *************** *** 141,149 **** Pdata *self; ! if (!( self = PyObject_New(Pdata, &PdataType))) return NULL; ! self->size=8; ! self->length=0; ! self->data=malloc(self->size * sizeof(PyObject*)); ! if (self->data) return (PyObject*)self; Py_DECREF(self); return PyErr_NoMemory(); --- 143,153 ---- Pdata *self; ! if (!(self = PyObject_New(Pdata, &PdataType))) ! return NULL; ! self->size = 8; ! self->length = 0; ! self->data = malloc(self->size * sizeof(PyObject*)); ! if (self->data) ! return (PyObject*)self; Py_DECREF(self); return PyErr_NoMemory(); *************** *** 157,160 **** --- 161,167 ---- } + /* Retain only the initial clearto items. If clearto >= the current + * number of items, this is a (non-erroneous) NOP. + */ static int Pdata_clear(Pdata *self, int clearto) *************** *** 166,202 **** if (clearto >= self->length) return 0; ! for (i=self->length, p=self->data+clearto; --i >= clearto; p++) Py_DECREF(*p); ! self->length=clearto; return 0; } - static int Pdata_grow(Pdata *self) { ! if (! self->size) { ! PyErr_NoMemory(); ! return -1; ! } ! self->size *= 2; ! self->data = realloc(self->data, self->size*sizeof(PyObject*)); ! if (! self->data) { ! self->size = 0; ! PyErr_NoMemory(); ! return -1; ! } return 0; - } ! #define PDATA_POP(D,V) { \ ! if ((D)->length) V=D->data[--((D)->length)]; \ ! else { \ ! PyErr_SetString(UnpicklingError, "bad pickle data"); \ ! V=NULL; \ ! } \ } static PyObject * --- 173,226 ---- if (clearto >= self->length) return 0; ! for (i = self->length, p = self->data + clearto; ! --i >= clearto; ! p++) { Py_DECREF(*p); ! } ! self->length = clearto; return 0; } static int Pdata_grow(Pdata *self) { ! int bigger; ! size_t nbytes; ! ! if (! self->size) ! goto nomemory; ! bigger = self->size << 1; ! if (bigger <= 0) ! goto nomemory; ! if ((int)(size_t)bigger != bigger) ! goto nomemory; ! nbytes = (size_t)bigger * sizeof(PyObject *); ! if (nbytes / sizeof(PyObject *) != (size_t)bigger) ! goto nomemory; ! self->data = realloc(self->data, nbytes); ! if (self->data == NULL) ! goto nomemory; ! self->size = bigger; return 0; ! nomemory: ! self->size = 0; ! PyErr_NoMemory(); ! return -1; } + /* D is a Pdata *. Pop the topmost element and store it into V, which + * must be an lvalue holding PyObject *. On stack underflow, UnpicklingError + * is raised and V is set to NULL. D and V may be evaluated several times. + */ + #define PDATA_POP(D, V) { \ + if ((D)->length) \ + (V) = (D)->data[--((D)->length)]; \ + else { \ + PyErr_SetString(UnpicklingError, "bad pickle data"); \ + (V) = NULL; \ + } \ + } static PyObject * *************** *** 206,215 **** int i, j, l; ! l=self->length-start; ! if (!( r=PyTuple_New(l))) return NULL; ! for (i=start, j=0 ; j < l; i++, j++) PyTuple_SET_ITEM(r, j, self->data[i]); ! self->length=start; return r; } --- 230,241 ---- int i, j, l; ! l = self->length-start; ! r = PyTuple_New(l); ! if (r == NULL) ! return NULL; ! for (i = start, j = 0 ; j < l; i++, j++) PyTuple_SET_ITEM(r, j, self->data[i]); ! self->length = start; return r; } *************** *** 1445,1524 **** #endif static int save_tuple(Picklerobject *self, PyObject *args) { ! PyObject *element = 0, *py_tuple_id = 0; ! int len, i, res = -1; static char tuple = TUPLE; ! ! if (self->write_func(self, &MARKv, 1) < 0) ! goto finally; if ((len = PyTuple_Size(args)) < 0) goto finally; ! for (i = 0; i < len; i++) { ! if (!( element = PyTuple_GET_ITEM((PyTupleObject *)args, i))) ! goto finally; ! if (save(self, element, 0) < 0) ! goto finally; } ! if (!( py_tuple_id = PyLong_FromVoidPtr(args))) goto finally; ! if (len) { if (PyDict_GetItem(self->memo, py_tuple_id)) { ! if (self->bin) { ! static char pop_mark = POP_MARK; ! ! if (self->write_func(self, &pop_mark, 1) < 0) goto finally; ! } ! else { ! static char pop = POP; ! ! for (i = 0; i <= len; i++) { ! if (self->write_func(self, &pop, 1) < 0) ! goto finally; ! } ! } ! if (get(self, py_tuple_id) < 0) goto finally; - res = 0; goto finally; } } ! if (self->write_func(self, &tuple, 1) < 0) { goto finally; } ! if (put(self, args) < 0) goto finally; ! res = 0; finally: Py_XDECREF(py_tuple_id); - return res; } static int - save_empty_tuple(Picklerobject *self, PyObject *args) - { - static char tuple = EMPTY_TUPLE; - - return self->write_func(self, &tuple, 1); - } - - - static int save_list(Picklerobject *self, PyObject *args) { --- 1471,1611 ---- #endif + /* A helper for save_tuple. Push the len elements in tuple t on the stack. */ + static int + store_tuple_elememts(Picklerobject *self, PyObject *t, int len) + { + int i; + int res = -1; /* guilty until proved innocent */ + + assert(PyTuple_Size(t) == len); + + for (i = 0; i < len; i++) { + PyObject *element = PyTuple_GET_ITEM(t, i); + if (element == NULL) + goto finally; + if (save(self, element, 0) < 0) + goto finally; + } + res = 0; + + finally: + return res; + } + + /* Tuples are ubiquitous in the pickle protocols, so many techniques are + * used across protocols to minimize the space needed to pickle them. + * Tuples are also the only builtin immuatable type that can be recursive + * (a tuple can be reached from itself), and that requires some subtle + * magic so that it works in all cases. IOW, this is a long routine. + */ static int save_tuple(Picklerobject *self, PyObject *args) { ! PyObject *py_tuple_id = NULL; ! int len, i; ! int res = -1; static char tuple = TUPLE; ! static char pop = POP; ! static char pop_mark = POP_MARK; ! static char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3}; if ((len = PyTuple_Size(args)) < 0) goto finally; ! if (len == 0) { ! char c_str[2]; ! if (self->proto) { ! c_str[0] = EMPTY_TUPLE; ! len = 1; ! } ! else { ! c_str[0] = MARK; ! c_str[1] = TUPLE; ! len = 2; ! } ! if (self->write_func(self, c_str, len) >= 0) ! res = 0; ! /* Don't memoize an empty tuple. */ ! goto finally; } ! /* A non-empty tuple. */ ! ! /* id(tuple) isn't in the memo now. If it shows up there after ! * saving the tuple elements, the tuple must be recursive, in ! * which case we'll pop everything we put on the stack, and fetch ! * its value from the memo. ! */ ! py_tuple_id = PyLong_FromVoidPtr(args); ! if (py_tuple_id == NULL) goto finally; ! if (len <= 3 && self->proto >= 2) { ! /* Use TUPLE{1,2,3} opcodes. */ ! if (store_tuple_elememts(self, args, len) < 0) ! goto finally; if (PyDict_GetItem(self->memo, py_tuple_id)) { ! /* pop the len elements */ ! for (i = 0; i < len; ++i) ! if (self->write_func(self, &pop, 1) < 0) goto finally; ! /* fetch from memo */ if (get(self, py_tuple_id) < 0) goto finally; res = 0; goto finally; } + /* Not recursive. */ + if (self->write_func(self, len2opcode + len, 1) < 0) + goto finally; + goto memoize; } ! /* proto < 2 and len > 0, or proto >= 2 and len > 3. ! * Generate MARK elt1 elt2 ... TUPLE ! */ ! if (self->write_func(self, &MARKv, 1) < 0) ! goto finally; ! ! if (store_tuple_elememts(self, args, len) < 0) ! goto finally; ! ! if (PyDict_GetItem(self->memo, py_tuple_id)) { ! /* pop the stack stuff we pushed */ ! if (self->bin) { ! if (self->write_func(self, &pop_mark, 1) < 0) ! goto finally; ! } ! else { ! /* Note that we pop one more than len, to remove ! * the MARK too. ! */ ! for (i = 0; i <= len; i++) ! if (self->write_func(self, &pop, 1) < 0) ! goto finally; ! } ! /* fetch from memo */ ! if (get(self, py_tuple_id) >= 0) ! res = 0; goto finally; } ! /* Not recursive. */ ! if (self->write_func(self, &tuple, 1) < 0) goto finally; ! memoize: ! if (put(self, args) >= 0) ! res = 0; finally: Py_XDECREF(py_tuple_id); return res; } static int save_list(Picklerobject *self, PyObject *args) { *************** *** 1973,1977 **** static int ! save(Picklerobject *self, PyObject *args, int pers_save) { PyTypeObject *type; --- 2060,2064 ---- static int ! save(Picklerobject *self, PyObject *args, int pers_save) { PyTypeObject *type; *************** *** 2029,2035 **** case 't': ! if (type == &PyTuple_Type && PyTuple_Size(args)==0) { ! if (self->bin) res = save_empty_tuple(self, args); ! else res = save_tuple(self, args); goto finally; } --- 2116,2121 ---- case 't': ! if (type == &PyTuple_Type && PyTuple_Size(args) == 0) { ! res = save_tuple(self, args); goto finally; } *************** *** 3194,3202 **** static int ! load_empty_tuple(Unpicklerobject *self) { ! PyObject *tup; ! if (!( tup=PyTuple_New(0))) return -1; PDATA_PUSH(self->stack, tup, -1); return 0; --- 3280,3298 ---- static int ! load_counted_tuple(Unpicklerobject *self, int len) { ! PyObject *tup = PyTuple_New(len); ! if (tup == NULL) ! return -1; ! ! while (--len >= 0) { ! PyObject *element; ! ! PDATA_POP(self->stack, element); ! if (element == NULL) ! return -1; ! PyTuple_SET_ITEM(tup, len, element); ! } PDATA_PUSH(self->stack, tup, -1); return 0; *************** *** 4019,4023 **** case EMPTY_TUPLE: ! if (load_empty_tuple(self) < 0) break; continue; --- 4115,4134 ---- case EMPTY_TUPLE: ! if (load_counted_tuple(self, 0) < 0) ! break; ! continue; ! ! case TUPLE1: ! if (load_counted_tuple(self, 1) < 0) ! break; ! continue; ! ! case TUPLE2: ! if (load_counted_tuple(self, 2) < 0) ! break; ! continue; ! ! case TUPLE3: ! if (load_counted_tuple(self, 3) < 0) break; continue; *************** *** 4347,4351 **** case EMPTY_TUPLE: ! if (load_empty_tuple(self) < 0) break; continue; --- 4458,4477 ---- case EMPTY_TUPLE: ! if (load_counted_tuple(self, 0) < 0) ! break; ! continue; ! ! case TUPLE1: ! if (load_counted_tuple(self, 1) < 0) ! break; ! continue; ! ! case TUPLE2: ! if (load_counted_tuple(self, 2) < 0) ! break; ! continue; ! ! case TUPLE3: ! if (load_counted_tuple(self, 3) < 0) break; continue; From jackjansen@users.sourceforge.net Sun Feb 2 23:00:26 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 02 Feb 2003 15:00:26 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/file _Filemodule.c,1.16,1.17 filescan.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/file In directory sc8-pr-cvs1:/tmp/cvs-serv3819 Modified Files: _Filemodule.c filescan.py Log Message: The FSAliasFile routines also have an in/out parameter. Index: _Filemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/file/_Filemodule.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** _Filemodule.c 28 Jan 2003 23:29:46 -0000 1.16 --- _Filemodule.c 2 Feb 2003 23:00:19 -0000 1.17 *************** *** 2955,2959 **** Boolean wasAliased; unsigned long mountFlags; ! if (!PyArg_ParseTuple(_args, "bl", &resolveAliasChains, &mountFlags)) --- 2955,2960 ---- Boolean wasAliased; unsigned long mountFlags; ! if (!PyArg_ParseTuple(_args, "O&bl", ! FSRef_Convert, &theRef, &resolveAliasChains, &mountFlags)) *************** *** 2980,2984 **** Boolean targetIsFolder; Boolean wasAliased; ! if (!PyArg_ParseTuple(_args, "b", &resolveAliasChains)) return NULL; --- 2981,2986 ---- Boolean targetIsFolder; Boolean wasAliased; ! if (!PyArg_ParseTuple(_args, "O&b", ! FSRef_Convert, &theRef, &resolveAliasChains)) return NULL; *************** *** 3134,3140 **** PyDoc_STR("(FSRef fromFile, FSRef target) -> (AliasHandle inAlias)")}, {"FSResolveAliasFileWithMountFlags", (PyCFunction)File_FSResolveAliasFileWithMountFlags, 1, ! PyDoc_STR("(Boolean resolveAliasChains, unsigned long mountFlags) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")}, {"FSResolveAliasFile", (PyCFunction)File_FSResolveAliasFile, 1, ! PyDoc_STR("(Boolean resolveAliasChains) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")}, {"FSUpdateAlias", (PyCFunction)File_FSUpdateAlias, 1, PyDoc_STR("(FSRef fromFile, FSRef target, AliasHandle alias) -> (Boolean wasChanged)")}, --- 3136,3142 ---- PyDoc_STR("(FSRef fromFile, FSRef target) -> (AliasHandle inAlias)")}, {"FSResolveAliasFileWithMountFlags", (PyCFunction)File_FSResolveAliasFileWithMountFlags, 1, ! PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")}, {"FSResolveAliasFile", (PyCFunction)File_FSResolveAliasFile, 1, ! PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")}, {"FSUpdateAlias", (PyCFunction)File_FSUpdateAlias, 1, PyDoc_STR("(FSRef fromFile, FSRef target, AliasHandle alias) -> (Boolean wasChanged)")}, Index: filescan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/file/filescan.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** filescan.py 12 Jan 2003 23:01:46 -0000 1.7 --- filescan.py 2 Feb 2003 23:00:21 -0000 1.8 *************** *** 173,176 **** --- 173,179 ---- [('FSSpec_ptr', 'theSpec', 'InOutMode')]), + ([('FSRef', 'theRef', 'OutMode')], + [('FSRef_ptr', 'theRef', 'InOutMode')]), + # The optional FSSpec to all ResolveAlias and NewAlias methods ([('FSSpec_ptr', 'fromFile', 'InMode')], From jackjansen@users.sourceforge.net Sun Feb 2 23:03:52 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 02 Feb 2003 15:03:52 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac buildtools.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv5154 Modified Files: buildtools.py Log Message: Getting rid of macfs usage and almost all FSSpecs. Untested on MacOS9. Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** buildtools.py 9 Jan 2003 10:47:20 -0000 1.2 --- buildtools.py 2 Feb 2003 23:03:50 -0000 1.3 *************** *** 6,12 **** import imp import marshal - import macfs from Carbon import Res ! import MACFS import MacOS import macostools --- 6,12 ---- import imp import marshal from Carbon import Res ! import Carbon.Files ! import Carbon.File import MacOS import macostools *************** *** 39,42 **** --- 39,44 ---- WRITE = 2 + # Parameter for FSOpenResourceFile + RESOURCE_FORK_NAME=Carbon.File.FSGetResourceForkName() def findtemplate(template=None): *************** *** 51,57 **** file = os.path.join(p, template) try: ! file, d1, d2 = macfs.ResolveAliasFile(file) break ! except (macfs.error, ValueError): continue else: --- 53,59 ---- file = os.path.join(p, template) try: ! file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1) break ! except (Carbon.File.error, ValueError): continue else: *************** *** 146,152 **** raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files ! template_fss = macfs.FSSpec(template) ! template_fss, d1, d2 = macfs.ResolveAliasFile(template_fss) ! dest_fss = macfs.FSSpec(destname) # Copy data (not resources, yet) from the template --- 148,153 ---- raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files ! template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) ! template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template *************** *** 172,184 **** progress.set(20) try: ! output = Res.FSpOpenResFile(dest_fss, WRITE) except MacOS.Error: ! Res.FSpCreateResFile(destname, '????', 'APPL', MACFS.smAllScripts) ! output = Res.FSpOpenResFile(dest_fss, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: ! input = Res.FSpOpenResFile(rsrcname, READ) except (MacOS.Error, ValueError): pass --- 173,186 ---- progress.set(20) try: ! output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: ! destdir, destfile = os.path.split(destname) ! Res.FSCreateResourceFile(destdir, destfile, RESOURCE_FORK_NAME) ! output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: ! input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass *************** *** 205,209 **** # Copy the resources from the template ! input = Res.FSpOpenResFile(template_fss, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) --- 207,211 ---- # Copy the resources from the template ! input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) *************** *** 258,270 **** Res.CloseResFile(output) ! # Now set the creator, type and bundle bit of the destination ! dest_finfo = dest_fss.GetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' ! dest_finfo.Flags = dest_finfo.Flags | MACFS.kHasBundle | MACFS.kIsShared ! dest_finfo.Flags = dest_finfo.Flags & ~MACFS.kHasBeenInited ! dest_fss.SetFInfo(dest_finfo) ! macostools.touched(dest_fss) if progress: progress.label("Done.") --- 260,274 ---- Res.CloseResFile(output) ! # Now set the creator, type and bundle bit of the destination. ! # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) ! dset_fss = Carbon.File.FSSpec(destname) ! dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' ! dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared ! dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited ! dest_fss.FSpSetFInfo(dest_finfo) ! macostools.touched(destname) if progress: progress.label("Done.") From doerwalter@users.sourceforge.net Sun Feb 2 23:08:30 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Sun, 02 Feb 2003 15:08:30 -0800 Subject: [Python-checkins] python/dist/src/Lib codecs.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv6591/Lib Modified Files: codecs.py Log Message: Fix typos. Index: codecs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/codecs.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** codecs.py 30 Dec 2002 23:36:02 -0000 1.31 --- codecs.py 2 Feb 2003 23:08:27 -0000 1.32 *************** *** 281,285 **** .readline() method -- there is currently no support for line breaking using the codec decoder due to lack of line ! buffering. Sublcasses should however, if possible, try to implement this method using their own knowledge of line breaking. --- 281,285 ---- .readline() method -- there is currently no support for line breaking using the codec decoder due to lack of line ! buffering. Subclasses should however, if possible, try to implement this method using their own knowledge of line breaking. *************** *** 540,549 **** Files are always opened in binary mode, even if no binary mode ! was specified. Thisis done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode. encoding specifies the encoding which is to be used for the ! the file. errors may be given to define the error handling. It defaults --- 540,549 ---- Files are always opened in binary mode, even if no binary mode ! was specified. This is done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode. encoding specifies the encoding which is to be used for the ! file. errors may be given to define the error handling. It defaults *************** *** 671,675 **** """ Creates an encoding map from a decoding map. ! If a target mapping in the decoding map occurrs multiple times, then that target is mapped to None (undefined mapping), causing an exception when encountered by the charmap codec --- 671,675 ---- """ Creates an encoding map from a decoding map. ! If a target mapping in the decoding map occurs multiple times, then that target is mapped to None (undefined mapping), causing an exception when encountered by the charmap codec From doerwalter@users.sourceforge.net Sun Feb 2 23:37:08 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Sun, 02 Feb 2003 15:37:08 -0800 Subject: [Python-checkins] python/dist/src README,1.167,1.168 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv15940 Modified Files: README Log Message: Fix typos. Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/README,v retrieving revision 1.167 retrieving revision 1.168 diff -C2 -d -r1.167 -r1.168 *** README 15 Jan 2003 16:04:43 -0000 1.167 --- README 2 Feb 2003 23:37:05 -0000 1.168 *************** *** 135,139 **** If you have a proposal to change Python, it's best to submit a Python Enhancement Proposal (PEP) first. All current PEPs, as well as ! guidelines for submitting a new PEP, are list at http://python.sourceforge.net/peps/. --- 135,139 ---- If you have a proposal to change Python, it's best to submit a Python Enhancement Proposal (PEP) first. All current PEPs, as well as ! guidelines for submitting a new PEP, are listed at http://python.sourceforge.net/peps/. *************** *** 286,290 **** you need to first make sure that the library is available on your system. Then, you need to instruct the dynamic loader how ! to find it. You can chose any of the following strategies: 1. When compiling Python, set LD_RUN_PATH to the directories --- 286,290 ---- you need to first make sure that the library is available on your system. Then, you need to instruct the dynamic loader how ! to find it. You can choose any of the following strategies: 1. When compiling Python, set LD_RUN_PATH to the directories *************** *** 546,550 **** To do this, run "./configure --with-threads=no" including any other options you need (--prefix, etc.). Then in Modules/Setup ! uncomment the lines: #SSL=/usr/local/ssl --- 546,550 ---- To do this, run "./configure --with-threads=no" including any other options you need (--prefix, etc.). Then in Modules/Setup ! uncomment the lines: #SSL=/usr/local/ssl *************** *** 690,694 **** the configure.in file and are confident that the patch works, please send in the patch. (Don't bother patching the configure script itself ! -- it is regenerated each the configure.in file changes.) Compiler switches for threads --- 690,694 ---- the configure.in file and are confident that the patch works, please send in the patch. (Don't bother patching the configure script itself ! -- it is regenerated each time the configure.in file changes.) Compiler switches for threads *************** *** 821,825 **** Note that on Linux, gprof apparently does not work for shared libraries. The Makefile/Setup mechanism can be used to compile and ! link most extension module statically. --- 821,825 ---- Note that on Linux, gprof apparently does not work for shared libraries. The Makefile/Setup mechanism can be used to compile and ! link most extension modules statically. From doerwalter@users.sourceforge.net Sun Feb 2 23:39:48 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Sun, 02 Feb 2003 15:39:48 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts gencodec.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv16925/Tools/scripts Modified Files: gencodec.py Log Message: Fix comment typo. Index: gencodec.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/gencodec.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** gencodec.py 11 Sep 2002 20:36:01 -0000 1.7 --- gencodec.py 2 Feb 2003 23:39:45 -0000 1.8 *************** *** 96,100 **** enc2uni[enc] = (uni,comment) # If there are more identity-mapped entries than unmapped entries, ! # it pays to generate an identity dictionary first, add add explicit # mappings to None for the rest if len(identity)>=len(unmapped): --- 96,100 ---- enc2uni[enc] = (uni,comment) # If there are more identity-mapped entries than unmapped entries, ! # it pays to generate an identity dictionary first, and add explicit # mappings to None for the rest if len(identity)>=len(unmapped): From montanaro@users.sourceforge.net Mon Feb 3 01:25:04 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 17:25:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv25499 Modified Files: test_csv.py Log Message: Add a few tests for writing array objects. Writing ints or chars works, writing floats doesn't. It appears what is written is neither the str() or the repr() of the float. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_csv.py 2 Feb 2003 11:57:28 -0000 1.4 --- test_csv.py 3 Feb 2003 01:25:02 -0000 1.5 *************** *** 125,128 **** --- 125,158 ---- self.assertRaises(csv.CSVError, writer.write, {"f1": 10, "f3": "abc"}) + class TestArrayWrites(unittest.TestCase): + def test_int_write(self): + import array + contents = [(20-i) for i in range(20)] + a = array.array('i', contents) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.write(a) + expected = ",".join([str(i) for i in contents])+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + + def test_float_write(self): + import array + contents = [(20-i)*0.1 for i in range(20)] + a = array.array('f', contents) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.write(a) + expected = ",".join([str(i) for i in contents])+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + + def test_char_write(self): + import array, string + a = array.array('c', string.letters) + fileobj = StringIO() + writer = csv.writer(fileobj, dialect="excel") + writer.write(a) + expected = ",".join(string.letters)+"\r\n" + self.assertEqual(fileobj.getvalue(), expected) + def _testclasses(): mod = sys.modules[__name__] From gvanrossum@users.sourceforge.net Mon Feb 3 01:32:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 02 Feb 2003 17:32:35 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28280 Modified Files: test_datetime.py Log Message: cPickle now implements enough of protocol 2 to enable all cross-pickling tests. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** test_datetime.py 1 Feb 2003 02:54:14 -0000 1.33 --- test_datetime.py 3 Feb 2003 01:32:33 -0000 1.34 *************** *** 24,34 **** (cPickle, cPickle, 0), (cPickle, cPickle, 1), ! ## (cPickle, cPickle, 2), (pickle, cPickle, 0), (pickle, cPickle, 1), ! ## (pickle, cPickle, 2), (cPickle, pickle, 0), (cPickle, pickle, 1), ! ## (cPickle, pickle, 2), ] --- 24,34 ---- (cPickle, cPickle, 0), (cPickle, cPickle, 1), ! (cPickle, cPickle, 2), (pickle, cPickle, 0), (pickle, cPickle, 1), ! (pickle, cPickle, 2), (cPickle, pickle, 0), (cPickle, pickle, 1), ! (cPickle, pickle, 2), ] From montanaro@users.sourceforge.net Mon Feb 3 01:33:02 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 17:33:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv28480 Modified Files: test_csv.py Log Message: whoops - test was wrong. Should have tested writing doubles, not floats. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_csv.py 3 Feb 2003 01:25:02 -0000 1.5 --- test_csv.py 3 Feb 2003 01:33:00 -0000 1.6 *************** *** 136,143 **** self.assertEqual(fileobj.getvalue(), expected) ! def test_float_write(self): import array contents = [(20-i)*0.1 for i in range(20)] ! a = array.array('f', contents) fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") --- 136,143 ---- self.assertEqual(fileobj.getvalue(), expected) ! def test_double_write(self): import array contents = [(20-i)*0.1 for i in range(20)] ! a = array.array('d', contents) fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") From montanaro@users.sourceforge.net Mon Feb 3 01:42:24 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 17:42:24 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv31029 Modified Files: test_csv.py Log Message: Should be generating array expected values from the array, not the data fed into the array. Added a test of writing single-precision floats (which won't work if you generate the expected values from the inputs to the array constructor). Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_csv.py 3 Feb 2003 01:33:00 -0000 1.6 --- test_csv.py 3 Feb 2003 01:42:22 -0000 1.7 *************** *** 133,137 **** writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join([str(i) for i in contents])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 133,137 ---- writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 143,147 **** writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join([str(i) for i in contents])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 143,157 ---- writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join([str(i) for i in a])+"\r\n" ! self.assertEqual(fileobj.getvalue(), expected) ! ! def test_float_write(self): ! import array ! contents = [(20-i)*0.1 for i in range(20)] ! a = array.array('f', contents) ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect="excel") ! writer.write(a) ! expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 152,156 **** writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join(string.letters)+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 162,166 ---- writer = csv.writer(fileobj, dialect="excel") writer.write(a) ! expected = ",".join(a)+"\r\n" self.assertEqual(fileobj.getvalue(), expected) From montanaro@users.sourceforge.net Mon Feb 3 02:07:39 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:07:39 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv15396 Modified Files: pep-0305.txt Log Message: default dialect is now "excel", not "excel2000". Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** pep-0305.txt 2 Feb 2003 12:25:23 -0000 1.10 --- pep-0305.txt 3 Feb 2003 02:07:37 -0000 1.11 *************** *** 90,94 **** writing. The basic reading interface is:: ! obj = reader(iterable [, dialect='excel2000'] [optional keyword args]) --- 90,94 ---- writing. The basic reading interface is:: ! obj = reader(iterable [, dialect='excel'] [optional keyword args]) *************** *** 106,110 **** The writing interface is similar:: ! obj = writer(fileobj [, dialect='excel2000'], [, fieldnames=seq] [optional keyword args]) --- 106,110 ---- The writing interface is similar:: ! obj = writer(fileobj [, dialect='excel'], [, fieldnames=seq] [optional keyword args]) *************** *** 165,169 **** follows:: ! class exceltsv(csv.excel2000): delimiter = '\t' --- 165,169 ---- follows:: ! class exceltsv(csv.excel): delimiter = '\t' From montanaro@users.sourceforge.net Mon Feb 3 02:25:28 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:25:28 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv22612 Modified Files: pep-0305.txt Log Message: set_dialect is the wrong name. It conveys the notion of a single dialect. register_dialect is better. Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** pep-0305.txt 3 Feb 2003 02:07:37 -0000 1.11 --- pep-0305.txt 3 Feb 2003 02:25:26 -0000 1.12 *************** *** 170,174 **** Three functions are defined in the API to set, get and list dialects:: ! set_dialect(name, dialect) dialect = get_dialect(name) known_dialects = list_dialects() --- 170,174 ---- Three functions are defined in the API to set, get and list dialects:: ! register_dialect(name, dialect) dialect = get_dialect(name) known_dialects = list_dialects() *************** *** 177,181 **** formatting parameters defined in the next section. The list_dialects() function returns all the registered dialect names as ! given in previous set_dialect() calls (both predefined and user-defined). --- 177,181 ---- formatting parameters defined in the next section. The list_dialects() function returns all the registered dialect names as ! given in previous register_dialect() calls (both predefined and user-defined). *************** *** 187,191 **** formatting parameters, specified as keyword parameters. The parameters are also the keys for the input and output mapping objects ! for the set_dialect() and get_dialect() module functions. - ``quotechar`` specifies a one-character string to use as the quoting --- 187,191 ---- formatting parameters, specified as keyword parameters. The parameters are also the keys for the input and output mapping objects ! for the register_dialect() and get_dialect() module functions. - ``quotechar`` specifies a one-character string to use as the quoting From montanaro@users.sourceforge.net Mon Feb 3 02:34:44 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:34:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv25115 Modified Files: csv.py Log Message: set_dialect is a bad name. register_dialect is better. Check that dialect being registered is subclass of Dialect. save an instance of the class, not the class itself. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** csv.py 2 Feb 2003 12:05:07 -0000 1.12 --- csv.py 3 Feb 2003 02:34:42 -0000 1.13 *************** *** 89,94 **** pass ! def set_dialect(name, dialect): ! dialects[name] = dialect def get_dialect(name): --- 89,96 ---- pass ! def register_dialect(name, dialect): ! if not issubclass(dialect, Dialect): ! raise TypeError, "dialect not a subclass of Dialect" ! dialects[name] = dialect() def get_dialect(name): From montanaro@users.sourceforge.net Mon Feb 3 02:35:41 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:35:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv25351 Modified Files: test_csv.py Log Message: add a few tests of the dialect registration stuff. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** test_csv.py 3 Feb 2003 01:42:22 -0000 1.7 --- test_csv.py 3 Feb 2003 02:35:38 -0000 1.8 *************** *** 165,168 **** --- 165,187 ---- self.assertEqual(fileobj.getvalue(), expected) + class TestDialects(unittest.TestCase): + def test_register(self): + class myexceltsv(csv.excel): + delimiter = "\t" + csv.register_dialect("myexceltsv", myexceltsv) + self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), + myexceltsv), 1==1) + del csv.dialects["myexceltsv"] + + def test_get(self): + self.assertEqual(isinstance(csv.get_dialect("excel"), + csv.excel), 1==1) + + def test_bad_register(self): + class myexceltsv: + delimiter = "\t" + self.assertRaises(TypeError, csv.register_dialect, + "myexceltsv", myexceltsv) + def _testclasses(): mod = sys.modules[__name__] From montanaro@users.sourceforge.net Mon Feb 3 02:43:10 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:43:10 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv27527 Modified Files: _csv.c Log Message: make it work with Python 2.2 Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _csv.c 2 Feb 2003 12:58:40 -0000 1.11 --- _csv.c 3 Feb 2003 02:43:08 -0000 1.12 *************** *** 17,20 **** --- 17,41 ---- #include "structmember.h" + /* begin 2.2 compatibility macros */ + #ifndef PyDoc_STRVAR + /* Define macros for inline documentation. */ + #define PyDoc_VAR(name) static char name[] + #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) + #ifdef WITH_DOC_STRINGS + #define PyDoc_STR(str) str + #else + #define PyDoc_STR(str) "" + #endif + #endif /* ifndef PyDoc_STRVAR */ + + #ifndef PyMODINIT_FUNC + # if defined(__cplusplus) + # define PyMODINIT_FUNC extern "C" void + # else /* __cplusplus */ + # define PyMODINIT_FUNC void + # endif /* __cplusplus */ + #endif + /* end 2.2 compatibility macros */ + static PyObject *error_obj; /* CSV exception */ From montanaro@users.sourceforge.net Mon Feb 3 02:52:06 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:52:06 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30005 Modified Files: csv.py Log Message: The dialects dict shouldn't be part of the public API. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** csv.py 3 Feb 2003 02:34:42 -0000 1.13 --- csv.py 3 Feb 2003 02:52:04 -0000 1.14 *************** *** 19,23 **** delimiter = '\t' ! dialects = { 'excel': excel(), 'excel-tab': excel_tab(), --- 19,23 ---- delimiter = '\t' ! _dialects = { 'excel': excel(), 'excel-tab': excel_tab(), *************** *** 30,34 **** else: try: ! dialect_obj = dialects[dialect] except KeyError: raise CSVError('Unknown dialect') --- 30,34 ---- else: try: ! dialect_obj = _dialects[dialect] except KeyError: raise CSVError('Unknown dialect') *************** *** 92,106 **** if not issubclass(dialect, Dialect): raise TypeError, "dialect not a subclass of Dialect" ! dialects[name] = dialect() def get_dialect(name): ! return dialects[name] def list_dialects(): ! return dialects.keys() # An alternate way of populating the dialects dictionary... #def _init_dialects(): ! # global dialects # mod = sys.modules[__name__] # for name in dir(mod): --- 92,106 ---- if not issubclass(dialect, Dialect): raise TypeError, "dialect not a subclass of Dialect" ! _dialects[name] = dialect() def get_dialect(name): ! return _dialects[name] def list_dialects(): ! return _dialects.keys() # An alternate way of populating the dialects dictionary... #def _init_dialects(): ! # global _dialects # mod = sys.modules[__name__] # for name in dir(mod): *************** *** 109,113 **** # if issubclass(attr, Dialect) and attr is not Dialect: # dialect = attr() ! # dialects[dialect.name] = dialect # except TypeError: # pass --- 109,113 ---- # if issubclass(attr, Dialect) and attr is not Dialect: # dialect = attr() ! # _dialects[dialect.name] = dialect # except TypeError: # pass From montanaro@users.sourceforge.net Mon Feb 3 02:54:32 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:54:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30709 Modified Files: csv.py Log Message: define the public API with __all__ remove the OCcsv class from the public API Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** csv.py 3 Feb 2003 02:52:04 -0000 1.14 --- csv.py 3 Feb 2003 02:54:30 -0000 1.15 *************** *** 2,5 **** --- 2,9 ---- from _csv import Error as CSVError + __all__ [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", + "CSVError", "Dialect", "excel", "excel_tab", "reader", "writer", + "register_dialect", "get_dialect", "list_dialects"] + QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) *************** *** 24,28 **** } ! class OCcsv: def __init__(self, dialect, **options): if isinstance(dialect, Dialect): --- 28,32 ---- } ! class _OCcsv: def __init__(self, dialect, **options): if isinstance(dialect, Dialect): *************** *** 41,48 **** self.parser = _csv.parser(**parser_options) ! class reader(OCcsv): def __init__(self, iterobj, dialect = 'excel', **options): self.iterobj = iter(iterobj) ! OCcsv.__init__(self, dialect, **options) def __iter__(self): --- 45,52 ---- self.parser = _csv.parser(**parser_options) ! class reader(_OCcsv): def __init__(self, iterobj, dialect = 'excel', **options): self.iterobj = iter(iterobj) ! _OCcsv.__init__(self, dialect, **options) def __iter__(self): *************** *** 55,63 **** return fields ! class writer(OCcsv): def __init__(self, fileobj, dialect='excel', fieldnames=None, **options): self.fileobj = fileobj self.fieldnames = fieldnames ! OCcsv.__init__(self, dialect, **options) def write(self, fields): --- 59,67 ---- return fields ! class writer(_OCcsv): def __init__(self, fileobj, dialect='excel', fieldnames=None, **options): self.fileobj = fileobj self.fieldnames = fieldnames ! _OCcsv.__init__(self, dialect, **options) def write(self, fields): From montanaro@users.sourceforge.net Mon Feb 3 02:55:21 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:55:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv31143 Modified Files: csv.py Log Message: doh! a little quick with the trigger there, Skip! Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** csv.py 3 Feb 2003 02:54:30 -0000 1.15 --- csv.py 3 Feb 2003 02:55:19 -0000 1.16 *************** *** 2,8 **** from _csv import Error as CSVError ! __all__ [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", ! "CSVError", "Dialect", "excel", "excel_tab", "reader", "writer", ! "register_dialect", "get_dialect", "list_dialects"] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) --- 2,8 ---- from _csv import Error as CSVError ! __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", ! "CSVError", "Dialect", "excel", "excel_tab", "reader", "writer", ! "register_dialect", "get_dialect", "list_dialects"] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) From montanaro@users.sourceforge.net Mon Feb 3 02:56:22 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 18:56:22 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv31414 Modified Files: test_csv.py Log Message: the dialects dict is no longer part of the public API Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** test_csv.py 3 Feb 2003 02:35:38 -0000 1.8 --- test_csv.py 3 Feb 2003 02:56:20 -0000 1.9 *************** *** 172,176 **** self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), myexceltsv), 1==1) ! del csv.dialects["myexceltsv"] def test_get(self): --- 172,176 ---- self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), myexceltsv), 1==1) ! del csv._dialects["myexceltsv"] def test_get(self): From montanaro@users.sourceforge.net Mon Feb 3 03:01:50 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 19:01:50 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv32647 Modified Files: pep-0305.txt Log Message: zap incorrect statement about formatting parameters and the dialect registry. Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** pep-0305.txt 3 Feb 2003 02:25:26 -0000 1.12 --- pep-0305.txt 3 Feb 2003 03:01:48 -0000 1.13 *************** *** 185,191 **** Both the reader and writer constructors take several specific ! formatting parameters, specified as keyword parameters. The ! parameters are also the keys for the input and output mapping objects ! for the register_dialect() and get_dialect() module functions. - ``quotechar`` specifies a one-character string to use as the quoting --- 185,189 ---- Both the reader and writer constructors take several specific ! formatting parameters, specified as keyword parameters. - ``quotechar`` specifies a one-character string to use as the quoting From montanaro@users.sourceforge.net Mon Feb 3 03:09:30 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 19:09:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv2201 Added Files: libcsv.tex Log Message: First cut at a libref section. I'm certain there are mistakes, but this gets some ink on the paper. --- NEW FILE: libcsv.tex --- \section{\module{csv} --- CSV File Reading and Writing} \declaremodule{standard}{csv} \modulesynopsis{Write and read tabular data to and from delimited files.} \index{csv} \indexii{data}{tabular} The \module{csv} module implements classes to read and write tabular data. The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. While the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can manipulate such data. There is no ``CSV standard'', so the format is operationally defined by the many applications which read and write it. The lack of a standard means there can be subtle differences in the data produced and consumed by different applications. These differences can be maddeningly subtle. The \module{csv} allows programmers to say, ``write this data in the format preferred by Excel (tm),'' without knowing all the fiddly little details of the CSV format used by Excel. Programmers can also easily define their own CSV formats. \subsection{Relationship to other Python modules} The csv module reads and writes sequences. It can also read data and return the rows as dicts. Sequence types other than lists and tuples (e.g. \code{array} objects) can be written. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a {}\code{cursor.fetch*()} call. The \module{csv} module defines the following classes. \begin{classdesc}{reader}{iterable\optional{, dialect="excel"} \optional{, fmtparam}} Create a reader object which will iterate over lines in the given {}\var{csvfile}. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. The other optional \var{fmtparam} keyword arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. \end{classdesc} \begin{classdesc}{writer}{fileobj\optional{, dialect="excel"} \optional{, fieldnames} \optional{, fmtparam}} Create a writer object responsible for converting the user's data into delimited strings on the given file-like object. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. If a sequence of strings is given as the optional \var{fieldnames} parameter, the writer will use them to properly order mapping objects passed to the object's \method{write} methods. The other optional \var{fmtparam} keyword arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. \end{classdesc} The \module{csv} module defines the following functions. \begin{funcdesc}{register_dialect}{name, dialect} Associate \var{dialect} with \var{name}. \var{dialect} must be a subclass of \class{csv.Dialect}. \var{name} must be a string or Unicode object. \end{funcdesc} \begin{funcdesc}{get_dialect}{name} Return the dialect associated with \var{name}. A \exception{KeyError} is raised if \var{name} is not a registered dialect name. \end{funcdesc} \begin{funcdesc}{list_dialects}{} Return the names of all registered dialects. \end{funcdesc} The \module{csv} module defines the following constants. \begin{datadesc}{QUOTE_ALWAYS} Instructs \class{writer} objects to quote all fields. \end{datadesc} \begin{datadesc}{QUOTE_MINIMAL} Instructs \class{writer} objects to only quote those fields which contain the current \var{delimiter} or begin with the current \var{quotechar}. \end{datadesc} \begin{datadesc}{QUOTE_NONNUMERIC} Instructs \class{writer} objects to quote all non-numeric fields. \end{datadesc} \begin{datadesc}{QUOTE_NONE} Instructs \class{writer} objects to never quote fields. When the current {}\var{delimiter} occurs in output data it is preceded by the current {}\var{escapechar} character. When QUOTE_NONE is in effect, it is an error not to have a single-character \var{escapechar} defined, even if no data to be written contains the \var{delimiter} character. \end{datadesc} \subsection{Dialects and Formatting Parameters\label{fmt-params}} To make it easier to specify the format of input and output records, specific formatting parameters are grouped together into dialects. A dialect is a subclass of the \class{Dialect} class having a set of specific methods and a single \method{validate} method. When creating \class{reader} or \class{writer} objects, the programmer can specify a string or a subclass of the \class{Dialect} class as the dialect parameter. In addition to, or instead of, the \var{dialect} parameter, the programmer can also specify individual formatting parameters, described in the following section. \subsubsection{Formatting Parameters} Both the \class{reader} and \class{writer} classes take several specific formatting parameters, specified as keyword parameters. \begin{description} \item{quotechar}{specifies a one-character string to use as the quoting character. It defaults to \code{"}.} \item{delimiter}{specifies a one-character string to use as the field separator. It defaults to \code{,}.} \item{escapechar}{specifies a one-character string used to escape the delimiter when quotechar is set to \var{None}.} \item{skipinitialspace}{specifies how to interpret whitespace which immediately follows a delimiter. It defaults to False, which means that whitespace immediately following a delimiter is part of the following field.} \item{lineterminator}{specifies the character sequence which should terminate rows.} \item{quoting}{controls when quotes should be generated by the writer. It can take on any of the following module constants:} \begin{description} \item{QUOTE_MINIMAL}{means only when required, for example, when a field contains either the quotechar or the delimiter.} \item{QUOTE_ALL}{means that quotes are always placed around all fields.} \item{QUOTE_NONNUMERIC}{means that quotes are always placed around fields which contain characters other than [+-0-9.].} \item{QUOTE_NONE}{means that quotes are never placed around fields. Instead, the \var{escapechar} is used to escape any instances of the \var{delimiter} which occurs in the data.} \end{description} \item{doublequote}{controls the handling of quotes inside fields. When \var{True}, two consecutive quotes are interpreted as one during read, and when writing, each quote is written as two quotes.} \end{description} \subsection{Reader Objects} \class{Reader} objects have the following public methods. \begin{methoddesc}{next}{} Return the next row of the reader's iterable object as a list, parsed according to the current dialect. \end{methoddesc} \subsection{Writer Objects} \class{Writer} objects have the following public methods. \begin{methoddesc}{write}{row} Write the \var{row} parameter to the writer's file object, formatted according to the current dialect. \end{methoddesc} \begin{methoddesc}{writelines}{rows} Write all the \var{rows} parameters to the writer's file object, formatted according to the current dialect. \end{methoddesc} \begin{methoddesc}{close}{} Close the underlying file object. \end{methoddesc} \subsection{Examples} The ``hello world'' of csv reading is \begin{verbatim} reader = csv.reader(file("some.csv")) for row in reader: print row \end{verbatim} The corresponding simplest possible writing example is \begin{verbatim} writer = csv.writer(file("some.csv", "w")) for row in someiterable: writer.write(row) \end{verbatim} Both the \class{reader} and \class{writer} classes accept a number of optional arguments which are used to tailor them to the dialect of the input or output file. From montanaro@users.sourceforge.net Mon Feb 3 03:56:38 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 19:56:38 -0800 Subject: [Python-checkins] python/dist/src/Doc/api concrete.tex,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv13331 Modified Files: concrete.tex Log Message: Add PyFloat_FromString. Left the char **pend argument out of the description since while there, it is useless and ignored, according to Tim's commen. (PyInt_FromString is also not described, but PyLong_FromString is. Is the former deprecated?) Index: concrete.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/concrete.tex,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** concrete.tex 22 Oct 2002 20:20:20 -0000 1.18 --- concrete.tex 3 Feb 2003 03:56:36 -0000 1.19 *************** *** 318,321 **** --- 318,326 ---- \end{cfuncdesc} + \begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str} + Creates a \ctype{PyFloatObject} object based on the string value in + \var{str}, or \NULL{} on failure. + \end{cfuncdesc} + \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v} Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on From tim.one@comcast.net Mon Feb 3 04:17:24 2003 From: tim.one@comcast.net (Tim Peters) Date: Sun, 02 Feb 2003 23:17:24 -0500 Subject: [Python-checkins] python/dist/src/Doc/api concrete.tex,1.18,1.19 In-Reply-To: Message-ID: [montanaro@users.sourceforge.net] > Modified Files: > concrete.tex > Log Message: > Add PyFloat_FromString. Left the char **pend argument out of the > description since while there, it is useless and ignored, > according to Tim's comment. You still have to pass it, though! We can't get rid of it without breaking backward compatibility, but it does no good to pass anything other than NULL. The docs should tell the plain truth here -- sometimes reality isn't pretty . > (PyInt_FromString is also not described, but PyLong_FromString is. > Is the former deprecated?) Sounds like the lack of docs is just a bug. From greg@users.sourceforge.net Mon Feb 3 04:19:43 2003 From: greg@users.sourceforge.net (greg@users.sourceforge.net) Date: Sun, 02 Feb 2003 20:19:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb/test test_misc.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb/test In directory sc8-pr-cvs1:/tmp/cvs-serv19167/bsddb/test Modified Files: test_misc.py Log Message: fix for use on python 2.1 Index: test_misc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/test/test_misc.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_misc.py 28 Jan 2003 17:20:44 -0000 1.3 --- test_misc.py 3 Feb 2003 04:19:40 -0000 1.4 *************** *** 13,18 **** from bsddb3 import db, dbshelve - from test.test_support import verbose - #---------------------------------------------------------------------- --- 13,16 ---- From greg@users.sourceforge.net Mon Feb 3 04:28:28 2003 From: greg@users.sourceforge.net (greg@users.sourceforge.net) Date: Sun, 02 Feb 2003 20:28:28 -0800 Subject: [Python-checkins] python/dist/src/Modules _bsddb.c,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv21215/extsrc Modified Files: _bsddb.c Log Message: version 4.1.4 (4.1.3 just released) Index: _bsddb.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_bsddb.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** _bsddb.c 28 Jan 2003 17:30:46 -0000 1.7 --- _bsddb.c 3 Feb 2003 04:28:26 -0000 1.8 *************** *** 86,90 **** #define DBVER (DB_VERSION_MAJOR * 10 + DB_VERSION_MINOR) ! #define PY_BSDDB_VERSION "4.1.3" static char *rcs_id = "$Id$"; --- 86,90 ---- #define DBVER (DB_VERSION_MAJOR * 10 + DB_VERSION_MINOR) ! #define PY_BSDDB_VERSION "4.1.4" static char *rcs_id = "$Id$"; From montanaro@users.sourceforge.net Mon Feb 3 05:13:26 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 21:13:26 -0800 Subject: [Python-checkins] python/dist/src/Doc/api concrete.tex,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv32146 Modified Files: concrete.tex Log Message: * Add description of PyInt_FromString. * Correct description of PyFloat_FromString. While ignored, the pend argument still has to be given. * Typo in PyLong_FromString. Index: concrete.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/concrete.tex,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** concrete.tex 3 Feb 2003 03:56:36 -0000 1.19 --- concrete.tex 3 Feb 2003 05:13:24 -0000 1.20 *************** *** 130,133 **** --- 130,152 ---- \end{cfuncdesc} + \begin{cfuncdesc}{PyObject*}{PyInt_FromString}{char *str, char **pend, + int base} + Return a new \ctype{PyIntObject} or \ctype{PyLongObject} based on the + string value in \var{str}, which is interpreted according to the radix in + \var{base}. If \var{pend} is non-\NULL, \code{*\var{pend}} will point to + the first character in \var{str} which follows the representation of the + number. If \var{base} is \code{0}, the radix will be determined based on + the leading characters of \var{str}: if \var{str} starts with \code{'0x'} + or \code{'0X'}, radix 16 will be used; if \var{str} starts with + \code{'0'}, radix 8 will be used; otherwise radix 10 will be used. If + \var{base} is not \code{0}, it must be between \code{2} and \code{36}, + inclusive. Leading spaces are ignored. If there are no digits, + \exception{ValueError} will be raised. If the string represents a number + too large to be contained within the machine's \ctype{long int} type and + overflow warnings are being suppressed, a \ctype{PyLongObject} will be + returned. If overflow warnings are not being suppressed, \NULL{} will be + returned in this case. + \end{cfuncdesc} + \begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival} Creates a new integer object with a value of \var{ival}. *************** *** 215,219 **** point to the first character in \var{str} which follows the representation of the number. If \var{base} is \code{0}, the radix ! will be determined base on the leading characters of \var{str}: if \var{str} starts with \code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts with \code{'0'}, radix 8 will be used; --- 234,238 ---- point to the first character in \var{str} which follows the representation of the number. If \var{base} is \code{0}, the radix ! will be determined based on the leading characters of \var{str}: if \var{str} starts with \code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts with \code{'0'}, radix 8 will be used; *************** *** 318,324 **** \end{cfuncdesc} ! \begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str} Creates a \ctype{PyFloatObject} object based on the string value in ! \var{str}, or \NULL{} on failure. \end{cfuncdesc} --- 337,344 ---- \end{cfuncdesc} ! \begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str, char **pend} Creates a \ctype{PyFloatObject} object based on the string value in ! \var{str}, or \NULL{} on failure. The \var{pend} argument is ignored. It ! remains only for backward compatibility. \end{cfuncdesc} From andrewmcnamara@users.sourceforge.net Mon Feb 3 05:32:21 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Sun, 02 Feb 2003 21:32:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv4371 Modified Files: csv.py Log Message: Renamed CSVError back to Error, renamed writer methods as writerow and writerows. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** csv.py 3 Feb 2003 02:55:19 -0000 1.16 --- csv.py 3 Feb 2003 05:32:19 -0000 1.17 *************** *** 1,7 **** import _csv ! from _csv import Error as CSVError __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", ! "CSVError", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects"] --- 1,7 ---- import _csv ! from _csv import Error __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", ! "Error", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects"] *************** *** 36,40 **** dialect_obj = _dialects[dialect] except KeyError: ! raise CSVError('Unknown dialect') parser_options = {} for attr in dir(dialect_obj): --- 36,40 ---- dialect_obj = _dialects[dialect] except KeyError: ! raise Error('Unknown dialect') parser_options = {} for attr in dir(dialect_obj): *************** *** 65,69 **** _OCcsv.__init__(self, dialect, **options) ! def write(self, fields): # if fields is a dict, we need a valid fieldnames list # if self.fieldnames is None we'll get a TypeError in the for stmt --- 65,69 ---- _OCcsv.__init__(self, dialect, **options) ! def writerow(self, fields): # if fields is a dict, we need a valid fieldnames list # if self.fieldnames is None we'll get a TypeError in the for stmt *************** *** 78,95 **** self.fileobj.write(self.parser.join(fields)) ! def writelines(self, lines): for fields in lines: self.write(fields) - - def close(self): - self.fileobj.close() - del self.fileobj - - def __del__(self): - if hasattr(self, 'fileobj'): - try: - self.close() - except: - pass def register_dialect(name, dialect): --- 78,84 ---- self.fileobj.write(self.parser.join(fields)) ! def writerows(self, lines): for fields in lines: self.write(fields) def register_dialect(name, dialect): From montanaro@users.sourceforge.net Mon Feb 3 06:21:09 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 22:21:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv16625 Modified Files: libcsv.tex Log Message: tracking write()/writelines()/CSVError to writerow()/writerows()/Error. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** libcsv.tex 3 Feb 2003 03:09:28 -0000 1.1 --- libcsv.tex 3 Feb 2003 06:21:07 -0000 1.2 *************** *** 23,26 **** --- 23,27 ---- CSV formats. + \subsection{Relationship to other Python modules} *************** *** 80,83 **** --- 81,90 ---- \end{funcdesc} + The \module{csv} module defines the following exception. + + \begin{excdesc}{Error} + Raised by any of the functions when an error is detected. + \end{excdesc} + The \module{csv} module defines the following constants. *************** *** 103,106 **** --- 110,114 ---- \end{datadesc} + \subsection{Dialects and Formatting Parameters\label{fmt-params}} *************** *** 114,117 **** --- 122,126 ---- individual formatting parameters, described in the following section. + \subsubsection{Formatting Parameters} *************** *** 159,162 **** --- 168,172 ---- \end{description} + \subsection{Reader Objects} *************** *** 168,188 **** \end{methoddesc} \subsection{Writer Objects} \class{Writer} objects have the following public methods. ! \begin{methoddesc}{write}{row} Write the \var{row} parameter to the writer's file object, formatted according to the current dialect. \end{methoddesc} ! \begin{methoddesc}{writelines}{rows} Write all the \var{rows} parameters to the writer's file object, formatted according to the current dialect. \end{methoddesc} - \begin{methoddesc}{close}{} - Close the underlying file object. - \end{methoddesc} \subsection{Examples} --- 178,196 ---- \end{methoddesc} + \subsection{Writer Objects} \class{Writer} objects have the following public methods. ! \begin{methoddesc}{writerow}{row} Write the \var{row} parameter to the writer's file object, formatted according to the current dialect. \end{methoddesc} ! \begin{methoddesc}{writerows}{rows} Write all the \var{rows} parameters to the writer's file object, formatted according to the current dialect. \end{methoddesc} \subsection{Examples} *************** *** 201,205 **** writer = csv.writer(file("some.csv", "w")) for row in someiterable: ! writer.write(row) \end{verbatim} --- 209,213 ---- writer = csv.writer(file("some.csv", "w")) for row in someiterable: ! writer.writerow(row) \end{verbatim} From montanaro@users.sourceforge.net Mon Feb 3 06:25:32 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 22:25:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv17557 Modified Files: libcsv.tex Log Message: add a couple cross-references Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** libcsv.tex 3 Feb 2003 06:21:07 -0000 1.2 --- libcsv.tex 3 Feb 2003 06:25:30 -0000 1.3 *************** *** 216,217 **** --- 216,221 ---- or output file. + \begin{seealso} + \seemodule{array}{Arrays of uniformly types numeric values.} + \seepep{305}{CSV File API} + \end{seealso} From montanaro@users.sourceforge.net Mon Feb 3 06:34:25 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 22:34:25 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts trace.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv19536 Modified Files: trace.py Log Message: add missing "summary" from long options list Index: trace.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/trace.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** trace.py 11 Dec 2002 21:43:13 -0000 1.12 --- trace.py 3 Feb 2003 06:34:22 -0000 1.13 *************** *** 598,602 **** opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", ["help", "version", "trace", "count", ! "report", "no-report", "file=", "missing", "ignore-module=", "ignore-dir=", --- 598,602 ---- opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", ["help", "version", "trace", "count", ! "report", "no-report", "summary", "file=", "missing", "ignore-module=", "ignore-dir=", From montanaro@users.sourceforge.net Mon Feb 3 06:44:15 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 22:44:15 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv21699 Modified Files: csv.py Log Message: in writer.writerows, self.write() -> self.writerow() Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** csv.py 3 Feb 2003 05:32:19 -0000 1.17 --- csv.py 3 Feb 2003 06:44:13 -0000 1.18 *************** *** 80,84 **** def writerows(self, lines): for fields in lines: ! self.write(fields) def register_dialect(name, dialect): --- 80,84 ---- def writerows(self, lines): for fields in lines: ! self.writerow(fields) def register_dialect(name, dialect): From montanaro@users.sourceforge.net Mon Feb 3 06:46:02 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 02 Feb 2003 22:46:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv22046 Modified Files: test_csv.py Log Message: write()/writelines()/CSVError -> writerow()/writerows()/Error added simple test passing Dialect instance instead of string Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** test_csv.py 3 Feb 2003 02:56:20 -0000 1.9 --- test_csv.py 3 Feb 2003 06:45:59 -0000 1.10 *************** *** 16,20 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect = self.dialect) ! writer.writelines(input) self.assertEqual(fileobj.getvalue(), expected_result) --- 16,20 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect = self.dialect) ! writer.writerows(input) self.assertEqual(fileobj.getvalue(), expected_result) *************** *** 117,121 **** writer = csv.writer(fileobj, dialect="excel", fieldnames = ["f1", "f2", "f3"]) ! writer.write({"f1": 10, "f3": "abc"}) self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") --- 117,121 ---- writer = csv.writer(fileobj, dialect="excel", fieldnames = ["f1", "f2", "f3"]) ! writer.writerow({"f1": 10, "f3": "abc"}) self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") *************** *** 123,127 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! self.assertRaises(csv.CSVError, writer.write, {"f1": 10, "f3": "abc"}) class TestArrayWrites(unittest.TestCase): --- 123,127 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! self.assertRaises(csv.Error, writer.writerow, {"f1": 10, "f3": "abc"}) class TestArrayWrites(unittest.TestCase): *************** *** 132,136 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.write(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 132,136 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.writerow(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 142,146 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.write(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 142,146 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.writerow(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 152,156 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.write(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 152,156 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.writerow(a) expected = ",".join([str(i) for i in a])+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 161,165 **** fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.write(a) expected = ",".join(a)+"\r\n" self.assertEqual(fileobj.getvalue(), expected) --- 161,165 ---- fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") ! writer.writerow(a) expected = ",".join(a)+"\r\n" self.assertEqual(fileobj.getvalue(), expected) *************** *** 184,187 **** --- 184,196 ---- "myexceltsv", myexceltsv) + def test_dialect_class(self): + class myexceltsv(csv.Dialect): + delimiter = "\t" + fileobj = StringIO() + writer = csv.writer(fileobj, dialect=myexceltsv()) + writer.writerow([1,2,3]) + self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") + + def _testclasses(): mod = sys.modules[__name__] From mwh@users.sourceforge.net Mon Feb 3 11:04:29 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 03 Feb 2003 03:04:29 -0800 Subject: [Python-checkins] python/dist/src/Lib cmd.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv4243/Lib Modified Files: cmd.py Log Message: Fix bug [ 676342 ] after using pdb readline does not work correctly using Michael Stone's patch so the completer functionality of cmd is only setup between preloop and postloop. Index: cmd.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/cmd.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** cmd.py 13 Jan 2003 21:18:54 -0000 1.33 --- cmd.py 3 Feb 2003 11:04:27 -0000 1.34 *************** *** 87,97 **** """ self.cmdqueue = [] ! if completekey: ! try: ! import readline ! readline.set_completer(self.complete) ! readline.parse_and_bind(completekey+": complete") ! except ImportError: ! pass def cmdloop(self, intro=None): --- 87,91 ---- """ self.cmdqueue = [] ! self.completekey = completekey def cmdloop(self, intro=None): *************** *** 143,147 **** def preloop(self): """Hook method executed once when the cmdloop() method is called.""" ! pass def postloop(self): --- 137,148 ---- def preloop(self): """Hook method executed once when the cmdloop() method is called.""" ! if self.completekey: ! try: ! import readline ! self.old_completer = readline.get_completer() ! readline.set_completer(self.complete) ! readline.parse_and_bind(self.completekey+": complete") ! except ImportError: ! pass def postloop(self): *************** *** 150,154 **** """ ! pass def parseline(self, line): --- 151,160 ---- """ ! if self.completekey: ! try: ! import readline ! readline.set_completer(self.old_completer) ! except ImportError: ! pass def parseline(self, line): From jvr@users.sourceforge.net Mon Feb 3 11:43:56 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 03 Feb 2003 03:43:56 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command config.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv28776 Modified Files: config.py Log Message: patch #664131, fix config command on OSX and Linux Index: config.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/config.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** config.py 19 Nov 2002 13:12:28 -0000 1.15 --- config.py 3 Feb 2003 11:43:54 -0000 1.16 *************** *** 152,156 **** target_lang=lang) ! prog = prog + self.compiler.exe_extension self.temp_files.append(prog) --- 152,157 ---- target_lang=lang) ! if self.compiler.exe_extension is not None: ! prog = prog + self.compiler.exe_extension self.temp_files.append(prog) From doerwalter@users.sourceforge.net Mon Feb 3 11:54:42 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 03:54:42 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.120,1.121 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv425/Lib/test Modified Files: regrtest.py Log Message: Remove test_b1 and test_b2 from the list of tests that are no real tests, because test_b1 and test_b2 no longer exist. (Spotted by Raymond Hettinger) Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.120 retrieving revision 1.121 diff -C2 -d -r1.120 -r1.121 *** regrtest.py 29 Jan 2003 16:24:16 -0000 1.120 --- regrtest.py 3 Feb 2003 11:54:39 -0000 1.121 *************** *** 339,344 **** NOTTESTS = [ 'test_support', - 'test_b1', - 'test_b2', 'test_future1', 'test_future2', --- 339,342 ---- From gward@users.sourceforge.net Mon Feb 3 14:47:01 2003 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Mon, 03 Feb 2003 06:47:01 -0800 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv1030/Lib Modified Files: textwrap.py Log Message: Add __all__ (suggested by Raymond Hettinger). Rename 'whitespace' global to '_whitespace' -- it's not part of the public interface. Index: textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** textwrap.py 12 Dec 2002 17:24:35 -0000 1.22 --- textwrap.py 3 Feb 2003 14:46:57 -0000 1.23 *************** *** 13,16 **** --- 13,18 ---- import string, re + __all__ = ['TextWrapper', 'wrap', 'fill'] + # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in *************** *** 21,25 **** # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). ! whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: --- 23,27 ---- # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). ! _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: *************** *** 59,67 **** """ ! whitespace_trans = string.maketrans(whitespace, ' ' * len(whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') ! for x in map(ord, whitespace): unicode_whitespace_trans[x] = uspace --- 61,69 ---- """ ! whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') ! for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace From montanaro@users.sourceforge.net Mon Feb 3 15:08:44 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:08:44 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts pickle2db.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv12298 Added Files: pickle2db.py Log Message: convert pickles generated by db2pickle.py back to database files --- NEW FILE: pickle2db.py --- #!/usr/bin/env python """ Synopsis: %(prog)s [-h|-b|-r|-a|-d] dbfile [ picklefile ] Read the given picklefile as a series of key/value pairs and write to a new bsddb database. If the database already exists, any contents are deleted. The optional flags indicate the type of the database (bsddb hash, bsddb btree, bsddb recno, anydbm, dbm). The default is hash. If a pickle file is named it is opened for read access. If no pickle file is named, the pickle input is read from standard input. Note that recno databases can only contain numeric keys, so you can't dump a hash or btree database using bsddb2pickle.py and reconstitute it to a recno database with %(prog)s. """ import getopt try: import bsddb except ImportError: bsddb = None try: import dbm except ImportError: dbm = None try: import anydbm except ImportError: anydbm = None import sys try: import cPickle as pickle except ImportError: import pickle prog = sys.argv[0] def usage(): print >> sys.stderr, __doc__ % globals() def main(args): try: opts, args = getopt.getopt(args, "hbrda", ["hash", "btree", "recno", "dbm", "anydbm"]) except getopt.error: usage() return 1 if len(args) == 0 or len(args) > 2: usage() return 1 elif len(args) == 1: dbfile = args[0] pfile = sys.stdin else: dbfile = args[0] try: pfile = file(args[1], 'rb') except IOError: print >> sys.stderr, "Unable to open", args[1] return 1 dbopen = None for opt, arg in opts: if opt in ("-h", "--hash"): try: dbopen = bsddb.hashopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-b", "--btree"): try: dbopen = bsddb.btopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-r", "--recno"): try: dbopen = bsddb.rnopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-a", "--anydbm"): try: dbopen = anydbm.open except AttributeError: print >> sys.stderr, "anydbm module unavailable." return 1 elif opt in ("-d", "--dbm"): try: dbopen = dbm.open except AttributeError: print >> sys.stderr, "dbm module unavailable." return 1 if dbopen is None: if bsddb is None: print >> sys.stderr, "bsddb module unavailable -" print >> sys.stderr, "must specify dbtype." return 1 else: dbopen = bsddb.hashopen try: db = dbopen(dbfile, 'c') except bsddb.error: print >> sys.stderr, "Unable to open", dbfile, print >> sys.stderr, "Check for format or version mismatch." return 1 else: for k in db.keys(): del db[k] while 1: try: (key, val) = pickle.load(pfile) except EOFError: break db[key] = val db.close() pfile.close() return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:])) From montanaro@users.sourceforge.net Mon Feb 3 15:09:06 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:09:06 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts db2pickle.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv12456 Added Files: db2pickle.py Log Message: dump database files to pickle format --- NEW FILE: db2pickle.py --- #!/usr/bin/env python """ Synopsis: %(prog)s [-h|-b|-r] dbfile [ picklefile ] Convert the bsddb database file given on the command like to a pickle representation. The optional flags indicate the type of the database (hash, btree, recno). The default is hash. If a pickle file is named it is opened for write access (deleting any existing data). If no pickle file is named, the pickle output is written to standard output. """ import getopt try: import bsddb except ImportError: bsddb = None try: import dbm except ImportError: dbm = None try: import anydbm except ImportError: anydbm = None import sys try: import cPickle as pickle except ImportError: import pickle prog = sys.argv[0] def usage(): print >> sys.stderr, __doc__ % globals() def main(args): try: opts, args = getopt.getopt(args, "hbrda", ["hash", "btree", "recno", "dbm", "anydbm"]) except getopt.error: usage() return 1 if len(args) == 0 or len(args) > 2: usage() return 1 elif len(args) == 1: dbfile = args[0] pfile = sys.stdout else: dbfile = args[0] try: pfile = file(args[1], 'wb') except IOError: print >> sys.stderr, "Unable to open", args[1] return 1 dbopen = None for opt, arg in opts: if opt in ("-h", "--hash"): try: dbopen = bsddb.hashopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-b", "--btree"): try: dbopen = bsddb.btopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-r", "--recno"): try: dbopen = bsddb.rnopen except AttributeError: print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-a", "--anydbm"): try: dbopen = anydbm.open except AttributeError: print >> sys.stderr, "anydbm module unavailable." return 1 elif opt in ("-d", "--dbm"): try: dbopen = dbm.open except AttributeError: print >> sys.stderr, "dbm module unavailable." return 1 if dbopen is None: if bsddb is None: print >> sys.stderr, "bsddb module unavailable -" print >> sys.stderr, "must specify dbtype." return 1 else: dbopen = bsddb.hashopen try: db = dbopen(dbfile, 'r') except bsddb.error: print >> sys.stderr, "Unable to open", dbfile, print >> sys.stderr, "Check for format or version mismatch." return 1 for k in db.keys(): pickle.dump((k, db[k]), pfile, 1==1) db.close() pfile.close() return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:])) From montanaro@users.sourceforge.net Mon Feb 3 15:09:35 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:09:35 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts README,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv12663 Modified Files: README Log Message: note db2pickle.py and pickle2db.py Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/README,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** README 2 Jan 2003 02:24:22 -0000 1.9 --- README 3 Feb 2003 15:09:32 -0000 1.10 *************** *** 12,15 **** --- 12,16 ---- crlf.py Change CRLF line endings to LF (Windows to Unix) cvsfiles.py Print a list of files that are under CVS + db2pickle.py Dump a database file to a pickle dutree.py Format du(1) output as a tree sorted by size eptags.py Create Emacs TAGS file for Python modules *************** *** 35,38 **** --- 36,40 ---- pathfix.py Change #!/usr/local/bin/python into something else pdeps.py Print dependencies between Python modules + pickle2db.py Load a pickle generated by db2pickle.py to a database pindent.py Indent Python code, giving block-closing comments ptags.py Create vi tags file for Python modules From akuchling@users.sourceforge.net Mon Feb 3 15:16:20 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:16:20 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.111,1.112 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv15634 Modified Files: whatsnew23.tex Log Message: [Bug #679251] Use correct constant name Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.111 retrieving revision 1.112 diff -C2 -d -r1.111 -r1.112 *** whatsnew23.tex 27 Jan 2003 16:36:34 -0000 1.111 --- whatsnew23.tex 3 Feb 2003 15:16:15 -0000 1.112 *************** *** 328,332 **** cause a \exception{UnicodeError} to be raised. Applications can test whether arbitrary Unicode strings are supported as file names by ! checking \member{os.path.unicode_file_names}, a Boolean value. \begin{seealso} --- 328,332 ---- cause a \exception{UnicodeError} to be raised. Applications can test whether arbitrary Unicode strings are supported as file names by ! checking \member{os.path.supports_unicode_filenames}, a Boolean value. \begin{seealso} *************** *** 2107,2115 **** The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this ! article: Simon Brunning, Michael Chermside, Scott David Daniels, ! Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael Hudson, ! Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins, ! Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Vinay Sajip, ! Neil Schemenauer, Jason Tishler, Just van~Rossum. \end{document} --- 2107,2115 ---- The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this ! article: Simon Brunning, Michael Chermside, Andrew Dalke, Scott David ! Daniels, Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael ! Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo ! Martins, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, ! Vinay Sajip, Neil Schemenauer, Jason Tishler, Just van~Rossum. \end{document} From fdrake@users.sourceforge.net Mon Feb 3 15:19:36 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:19:36 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.121,1.122 test_support.py,1.47,1.48 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv17119 Modified Files: regrtest.py test_support.py Log Message: test_support.requires(): Instead of raising TestSkipped, raise a new exception, ResourceDenied. This is used to distinguish between tests that are skipped for other reasons (platform support, missing data, etc.) from those that are skipped because a "resource" has not been enabled. This prevents those tests from being reported as unexpected skips for the platform; those should only be considered unexpected skips if the resource were enabled. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.121 retrieving revision 1.122 diff -C2 -d -r1.121 -r1.122 *** regrtest.py 3 Feb 2003 11:54:39 -0000 1.121 --- regrtest.py 3 Feb 2003 15:19:27 -0000 1.122 *************** *** 197,200 **** --- 197,201 ---- bad = [] skipped = [] + resource_denieds = [] if findleaks: *************** *** 264,267 **** --- 265,270 ---- else: skipped.append(test) + if ok == -2: + resource_denieds.append(test) if findleaks: gc.collect() *************** *** 300,304 **** plat = sys.platform if e.isvalid(): ! surprise = Set(skipped) - e.getexpected() if surprise: print count(len(surprise), "skip"), \ --- 303,307 ---- plat = sys.platform if e.isvalid(): ! surprise = Set(skipped) - e.getexpected() - Set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ *************** *** 396,399 **** --- 399,407 ---- finally: sys.stdout = save_stdout + except test_support.ResourceDenied, msg: + if not quiet: + print test, "skipped --", msg + sys.stdout.flush() + return -2 except (ImportError, test_support.TestSkipped), msg: if not quiet: Index: test_support.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_support.py,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** test_support.py 4 Dec 2002 03:26:57 -0000 1.47 --- test_support.py 3 Feb 2003 15:19:30 -0000 1.48 *************** *** 22,25 **** --- 22,33 ---- """ + class ResourceDenied(TestSkipped): + """Test skipped because it requested a disallowed resource. + + This is raised when a test calls requires() for a resource that + has not be enabled. It is used to distinguish between expected + and unexpected skips. + """ + verbose = 1 # Flag set to 0 by regrtest.py use_resources = None # Flag set to [] by regrtest.py *************** *** 58,62 **** if msg is None: msg = "Use of the `%s' resource not enabled" % resource ! raise TestSkipped(msg) FUZZ = 1e-6 --- 66,70 ---- if msg is None: msg = "Use of the `%s' resource not enabled" % resource ! raise ResourceDenied(msg) FUZZ = 1e-6 From akuchling@users.sourceforge.net Mon Feb 3 15:21:19 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:21:19 -0800 Subject: [Python-checkins] python/dist/src/Lib BaseHTTPServer.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv18099 Modified Files: BaseHTTPServer.py Log Message: Bug #676273: Rewrite paragraph in module docstring Index: BaseHTTPServer.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/BaseHTTPServer.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** BaseHTTPServer.py 31 May 2002 23:03:33 -0000 1.22 --- BaseHTTPServer.py 3 Feb 2003 15:21:15 -0000 1.23 *************** *** 133,141 **** the ASCII character with hex code xx). ! The protocol is vague about whether lines are separated by LF ! characters or by CRLF pairs -- for compatibility with the widest ! range of clients, both should be accepted. Similarly, whitespace ! in the request line should be treated sensibly (allowing multiple ! spaces between components and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs --- 133,141 ---- the ASCII character with hex code xx). ! The specification specifies that lines are separated by CRLF but ! for compatibility with the widest range of clients recommends ! servers also handle LF. Similarly, whitespace in the request line ! is treated sensibly (allowing multiple spaces between components ! and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs From gvanrossum@users.sourceforge.net Mon Feb 3 15:25:08 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:25:08 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_long.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19986 Modified Files: test_long.py Log Message: test_float_overflow(): make shuge (added last week) a little less huge. On older Linux systems, the C library's strtod() apparently gives up before seeing the end of the string when it sees so many digits that it thinks the result must be Infinity. (It is wrong, BTW -- there could be an "e-10000" hiding behind 10,000 digits.) The shorter shuge still tests what it's testing, without relying on strtod() doing a super job. Index: test_long.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_long.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** test_long.py 28 Jan 2003 19:21:19 -0000 1.22 --- test_long.py 3 Feb 2003 15:25:01 -0000 1.23 *************** *** 372,376 **** verify(float(long(x)) == x) ! shuge = '12345' * 1000 huge = 1L << 30000 mhuge = -huge --- 372,376 ---- verify(float(long(x)) == x) ! shuge = '12345' * 120 huge = 1L << 30000 mhuge = -huge From montanaro@users.sourceforge.net Mon Feb 3 15:28:26 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:28:26 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts pickle2db.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv21767 Modified Files: pickle2db.py Log Message: try to avoid gross incompatibilities with earlier versions of Python Index: pickle2db.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/pickle2db.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pickle2db.py 3 Feb 2003 15:08:42 -0000 1.1 --- pickle2db.py 3 Feb 2003 15:28:23 -0000 1.2 *************** *** 38,42 **** def usage(): ! print >> sys.stderr, __doc__ % globals() def main(args): --- 38,42 ---- def usage(): ! sys.stderr.write(__doc__ % globals()) def main(args): *************** *** 57,63 **** dbfile = args[0] try: ! pfile = file(args[1], 'rb') except IOError: ! print >> sys.stderr, "Unable to open", args[1] return 1 --- 57,63 ---- dbfile = args[0] try: ! pfile = open(args[1], 'rb') except IOError: ! sys.stderr.write("Unable to open %s\n" % args[1]) return 1 *************** *** 68,72 **** dbopen = bsddb.hashopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-b", "--btree"): --- 68,72 ---- dbopen = bsddb.hashopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-b", "--btree"): *************** *** 74,78 **** dbopen = bsddb.btopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-r", "--recno"): --- 74,78 ---- dbopen = bsddb.btopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-r", "--recno"): *************** *** 80,84 **** dbopen = bsddb.rnopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-a", "--anydbm"): --- 80,84 ---- dbopen = bsddb.rnopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-a", "--anydbm"): *************** *** 86,90 **** dbopen = anydbm.open except AttributeError: ! print >> sys.stderr, "anydbm module unavailable." return 1 elif opt in ("-d", "--dbm"): --- 86,90 ---- dbopen = anydbm.open except AttributeError: ! sys.stderr.write("anydbm module unavailable.\n") return 1 elif opt in ("-d", "--dbm"): *************** *** 92,101 **** dbopen = dbm.open except AttributeError: ! print >> sys.stderr, "dbm module unavailable." return 1 if dbopen is None: if bsddb is None: ! print >> sys.stderr, "bsddb module unavailable -" ! print >> sys.stderr, "must specify dbtype." return 1 else: --- 92,101 ---- dbopen = dbm.open except AttributeError: ! sys.stderr.write("dbm module unavailable.\n") return 1 if dbopen is None: if bsddb is None: ! sys.stderr.write("bsddb module unavailable - ") ! sys.stderr.write("must specify dbtype.\n") return 1 else: *************** *** 105,110 **** db = dbopen(dbfile, 'c') except bsddb.error: ! print >> sys.stderr, "Unable to open", dbfile, ! print >> sys.stderr, "Check for format or version mismatch." return 1 else: --- 105,110 ---- db = dbopen(dbfile, 'c') except bsddb.error: ! sys.stderr.write("Unable to open %s. " % dbfile) ! sys.stderr.write("Check for format or version mismatch.\n") return 1 else: From montanaro@users.sourceforge.net Mon Feb 3 15:29:37 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:29:37 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts db2pickle.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv22246 Modified Files: db2pickle.py Log Message: try to avoid gross incompatibilities with older versions of Python Index: db2pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/db2pickle.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** db2pickle.py 3 Feb 2003 15:09:03 -0000 1.1 --- db2pickle.py 3 Feb 2003 15:29:34 -0000 1.2 *************** *** 34,38 **** def usage(): ! print >> sys.stderr, __doc__ % globals() def main(args): --- 34,38 ---- def usage(): ! sys.stderr.write(__doc__ % globals()) def main(args): *************** *** 53,59 **** dbfile = args[0] try: ! pfile = file(args[1], 'wb') except IOError: ! print >> sys.stderr, "Unable to open", args[1] return 1 --- 53,59 ---- dbfile = args[0] try: ! pfile = open(args[1], 'wb') except IOError: ! sys.stderr.write("Unable to open %s\n" % args[1]) return 1 *************** *** 64,68 **** dbopen = bsddb.hashopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-b", "--btree"): --- 64,68 ---- dbopen = bsddb.hashopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-b", "--btree"): *************** *** 70,74 **** dbopen = bsddb.btopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-r", "--recno"): --- 70,74 ---- dbopen = bsddb.btopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-r", "--recno"): *************** *** 76,80 **** dbopen = bsddb.rnopen except AttributeError: ! print >> sys.stderr, "bsddb module unavailable." return 1 elif opt in ("-a", "--anydbm"): --- 76,80 ---- dbopen = bsddb.rnopen except AttributeError: ! sys.stderr.write("bsddb module unavailable.\n") return 1 elif opt in ("-a", "--anydbm"): *************** *** 82,86 **** dbopen = anydbm.open except AttributeError: ! print >> sys.stderr, "anydbm module unavailable." return 1 elif opt in ("-d", "--dbm"): --- 82,86 ---- dbopen = anydbm.open except AttributeError: ! sys.stderr.write("anydbm module unavailable.\n") return 1 elif opt in ("-d", "--dbm"): *************** *** 88,97 **** dbopen = dbm.open except AttributeError: ! print >> sys.stderr, "dbm module unavailable." return 1 if dbopen is None: if bsddb is None: ! print >> sys.stderr, "bsddb module unavailable -" ! print >> sys.stderr, "must specify dbtype." return 1 else: --- 88,97 ---- dbopen = dbm.open except AttributeError: ! sys.stderr.write("dbm module unavailable.\n") return 1 if dbopen is None: if bsddb is None: ! sys.stderr.write("bsddb module unavailable - ") ! sys.stderr.write("must specify dbtype.\n") return 1 else: *************** *** 101,106 **** db = dbopen(dbfile, 'r') except bsddb.error: ! print >> sys.stderr, "Unable to open", dbfile, ! print >> sys.stderr, "Check for format or version mismatch." return 1 --- 101,106 ---- db = dbopen(dbfile, 'r') except bsddb.error: ! sys.stderr.write("Unable to open %s. " % dbfile) ! sys.stderr.write("Check for format or version mismatch.\n") return 1 From gvanrossum@users.sourceforge.net Mon Feb 3 15:28:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:28:24 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.154,1.155 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv21734 Modified Files: longobject.c Log Message: _PyLong_Sign(): remove an assert that needed a variable ndigits that wasn't used outside the assert (and hence caused a compiler warning about an unused variable in NDEBUG mode). The assert wasn't very useful any more. _PyLong_NumBits(): moved the calculation of ndigits after asserting that v != NULL. Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.154 retrieving revision 1.155 diff -C2 -d -r1.154 -r1.155 *** longobject.c 2 Feb 2003 17:33:53 -0000 1.154 --- longobject.c 3 Feb 2003 15:28:19 -0000 1.155 *************** *** 265,273 **** { PyLongObject *v = (PyLongObject *)vv; - const int ndigits = ABS(v->ob_size); assert(v != NULL); assert(PyLong_Check(v)); - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); return v->ob_size == 0 ? 0 : (v->ob_size < 0 ? -1 : 1); --- 265,271 ---- *************** *** 279,286 **** PyLongObject *v = (PyLongObject *)vv; size_t result = 0; ! int ndigits = ABS(v->ob_size); assert(v != NULL); assert(PyLong_Check(v)); assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); if (ndigits > 0) { --- 277,285 ---- PyLongObject *v = (PyLongObject *)vv; size_t result = 0; ! int ndigits; assert(v != NULL); assert(PyLong_Check(v)); + ndigits = ABS(v->ob_size); assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); if (ndigits > 0) { From akuchling@users.sourceforge.net Mon Feb 3 15:36:30 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:36:30 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.109,1.110 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv25340 Modified Files: libos.tex Log Message: Bug #678077: Suggest alternative to os.getlogin() Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.109 retrieving revision 1.110 diff -C2 -d -r1.109 -r1.110 *** libos.tex 7 Jan 2003 22:43:25 -0000 1.109 --- libos.tex 3 Feb 2003 15:36:26 -0000 1.110 *************** *** 142,146 **** Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the ! environment variable \envvar{LOGNAME} to find out who the user is. Availability: \UNIX. \end{funcdesc} --- 142,148 ---- Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use the ! environment variable \envvar{LOGNAME} to find out who the user is, ! or \code{pwd.getpwuid(os.getuid())[0]} to get the login name ! of the currently effective user ID. Availability: \UNIX. \end{funcdesc} From tim_one@users.sourceforge.net Mon Feb 3 15:45:59 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:45:59 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.116,2.117 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29027/Modules Modified Files: cPickle.c Log Message: PDATA_PUSH and PDATA_APPEND. documented, and reformatted for better readability. load_bool(): Now that I know the intended difference between _PUSH and _APPEND, used the right one. Pdata_grow(): Squashed out a redundant overflow test. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.116 retrieving revision 2.117 diff -C2 -d -r2.116 -r2.117 *** cPickle.c 2 Feb 2003 20:29:39 -0000 2.116 --- cPickle.c 3 Feb 2003 15:45:56 -0000 2.117 *************** *** 189,196 **** size_t nbytes; - if (! self->size) - goto nomemory; bigger = self->size << 1; ! if (bigger <= 0) goto nomemory; if ((int)(size_t)bigger != bigger) --- 189,194 ---- size_t nbytes; bigger = self->size << 1; ! if (bigger <= 0) /* was 0, or new value overflows */ goto nomemory; if ((int)(size_t)bigger != bigger) *************** *** 211,227 **** } ! /* D is a Pdata *. Pop the topmost element and store it into V, which ! * must be an lvalue holding PyObject *. On stack underflow, UnpicklingError * is raised and V is set to NULL. D and V may be evaluated several times. */ #define PDATA_POP(D, V) { \ ! if ((D)->length) \ ! (V) = (D)->data[--((D)->length)]; \ ! else { \ ! PyErr_SetString(UnpicklingError, "bad pickle data"); \ ! (V) = NULL; \ ! } \ } static PyObject * Pdata_popTuple(Pdata *self, int start) --- 209,253 ---- } ! /* D is a Pdata*. Pop the topmost element and store it into V, which ! * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError * is raised and V is set to NULL. D and V may be evaluated several times. */ #define PDATA_POP(D, V) { \ ! if ((D)->length) \ ! (V) = (D)->data[--((D)->length)]; \ ! else { \ ! PyErr_SetString(UnpicklingError, "bad pickle data"); \ ! (V) = NULL; \ ! } \ ! } ! ! /* PDATA_PUSH and PDATA_APPEND both push rvalue PyObject* O on to Pdata* ! * D. If the Pdata stack can't be grown to hold the new value, both ! * raise MemoryError and execute "return ER". The difference is in ownership ! * of O after: _PUSH transfers ownership of O from the caller to the stack ! * (no incref of O is done, and in case of error O is decrefed), while ! * _APPEND pushes a new reference. ! */ ! ! /* Push O on stack D, giving ownership of O to the stack. */ ! #define PDATA_PUSH(D, O, ER) { \ ! if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \ ! Pdata_grow((Pdata*)(D)) < 0) { \ ! Py_DECREF(O); \ ! return ER; \ ! } \ ! ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \ } + /* Push O on stack D, pushing a new reference. */ + #define PDATA_APPEND(D, O, ER) { \ + if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \ + Pdata_grow((Pdata*)(D)) < 0) \ + return ER; \ + Py_INCREF(O); \ + ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \ + } + + static PyObject * Pdata_popTuple(Pdata *self, int start) *************** *** 256,276 **** } - #define PDATA_APPEND(D,O,ER) { \ - if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \ - Pdata_grow((Pdata*)(D)) < 0) \ - return ER; \ - Py_INCREF(O); \ - ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O; \ - } - - #define PDATA_PUSH(D,O,ER) { \ - if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \ - Pdata_grow((Pdata*)(D)) < 0) { \ - Py_DECREF(O); \ - return ER; \ - } \ - ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O; \ - } - /*************************************************************************/ --- 282,285 ---- *************** *** 2887,2892 **** { assert(boolean == Py_True || boolean == Py_False); ! Py_INCREF(boolean); ! PDATA_PUSH(self->stack, boolean, -1); return 0; } --- 2896,2900 ---- { assert(boolean == Py_True || boolean == Py_False); ! PDATA_APPEND(self->stack, boolean, -1); return 0; } From montanaro@users.sourceforge.net Mon Feb 3 15:48:17 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:48:17 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.637,1.638 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv31587 Modified Files: NEWS Log Message: braino Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.637 retrieving revision 1.638 diff -C2 -d -r1.637 -r1.638 *** NEWS 3 Feb 2003 15:17:25 -0000 1.637 --- NEWS 3 Feb 2003 15:48:10 -0000 1.638 *************** *** 189,194 **** example: ! % python2.2 -h some.db > some.pickle ! % python2.3 -h some.db.new < some.pickle Run the scripts without any args to get a usage message. --- 189,194 ---- example: ! % python2.2 db2pickle.py -h some.db > some.pickle ! % python2.3 pickle2db.py -h some.db.new < some.pickle Run the scripts without any args to get a usage message. From tim_one@users.sourceforge.net Mon Feb 3 16:20:21 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 08:20:21 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv14251/python/Lib/test Modified Files: pickletester.py Log Message: Proper testing of proto 2 in part requires checking that the new opcodes are actually getting generated. Add helpered method ensure_opcode_in_pickle to do a correct job checking for that. Changed test_long1(), test_long4(), and test_short_tuples() to use it. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** pickletester.py 2 Feb 2003 20:29:38 -0000 1.37 --- pickletester.py 3 Feb 2003 16:20:13 -0000 1.38 *************** *** 1,4 **** --- 1,5 ---- import unittest import pickle + import pickletools from test.test_support import TestFailed, have_unicode, TESTFN *************** *** 254,257 **** --- 255,264 ---- pass + def ensure_opcode_in_pickle(self, code, pickle): + for op, dummy, dummy in pickletools.genops(pickle): + if op.code == code: + return + self.fail("didn't find opcode %r in pickle %r" % (code, pickle)) + def test_misc(self): # test various datatypes not tested by testdata *************** *** 477,480 **** --- 484,488 ---- y = self.loads(s) self.assertEqual(x, y) + self.ensure_opcode_in_pickle(pickle.LONG1, s) def test_long4(self): *************** *** 483,486 **** --- 491,495 ---- y = self.loads(s) self.assertEqual(x, y) + self.ensure_opcode_in_pickle(pickle.LONG4, s) def test_short_tuples(self): *************** *** 504,509 **** (2, 4): pickle.TUPLE, } - all_tuple_opcodes = (pickle.TUPLE, pickle.EMPTY_TUPLE, - pickle.TUPLE1, pickle.TUPLE2, pickle.TUPLE3) a = () b = (1,) --- 513,516 ---- *************** *** 516,529 **** y = self.loads(s) self.assertEqual(x, y, (proto, x, s, y)) - - # Verify that the protocol-correct tuple-building opcode - # was generated. expected = expected_opcode[proto, len(x)] ! for opcode in s: ! if opcode in all_tuple_opcodes: ! self.assertEqual(expected, opcode) ! break ! else: ! self.fail("didn't find a tuple-building opcode in pickle") def test_singletons(self): --- 523,528 ---- y = self.loads(s) self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] ! self.ensure_opcode_in_pickle(expected, s) def test_singletons(self): From montanaro@users.sourceforge.net Mon Feb 3 15:17:31 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 07:17:31 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.636,1.637 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv16232 Modified Files: NEWS Log Message: add note about new db2pickle.py and pickle2db.py scripts Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.636 retrieving revision 1.637 diff -C2 -d -r1.636 -r1.637 *** NEWS 2 Feb 2003 07:51:32 -0000 1.636 --- NEWS 3 Feb 2003 15:17:25 -0000 1.637 *************** *** 179,183 **** ----------- ! TBD Build --- 179,197 ---- ----------- ! - Two new scripts (db2pickle.py and pickle2db.py) were added to the ! Tools/scripts directory to facilitate conversion from the old bsddb module ! to the new one. While the user-visible API of the new module is ! compatible with the old one, it's likely that the version of the ! underlying database library has changed. To convert from the old library, ! run the db2pickle.py script using the old version of Python to convert it ! to a pickle file. After upgrading Python, run the pickle2db.py script ! using the new version of Python to reconstitute your database. For ! example: ! ! % python2.2 -h some.db > some.pickle ! % python2.3 -h some.db.new < some.pickle ! ! Run the scripts without any args to get a usage message. ! Build *************** *** 627,631 **** still available in source code, but not built automatically anymore, and is now named bsddb185. This supports Berkeley DB versions from ! 3.0 to 4.1. - unicodedata was updated to Unicode 3.2. It supports normalization --- 641,648 ---- still available in source code, but not built automatically anymore, and is now named bsddb185. This supports Berkeley DB versions from ! 3.0 to 4.1. For help converting your databases from the old module (which ! probably used an obsolete version of Berkeley DB) to the new module, see ! the db2pickle.py and pickle2db.py scripts described in the Tools/Demos ! section above. - unicodedata was updated to Unicode 3.2. It supports normalization From gvanrossum@users.sourceforge.net Mon Feb 3 16:59:54 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 08:59:54 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.140,1.141 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv19418 Modified Files: pickle.py Log Message: Support keyword argument 'bin', with a pending deprecation warning. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.140 retrieving revision 1.141 diff -C2 -d -r1.140 -r1.141 *** pickle.py 2 Feb 2003 20:29:38 -0000 1.140 --- pickle.py 3 Feb 2003 16:59:48 -0000 1.141 *************** *** 168,172 **** class Pickler: ! def __init__(self, file, proto=0): """This takes a file-like object for writing a pickle data stream. --- 168,172 ---- class Pickler: ! def __init__(self, file, proto=None, bin=None): """This takes a file-like object for writing a pickle data stream. *************** *** 192,195 **** --- 192,203 ---- """ + if proto is not None and bin is not None: + raise ValueError, "can't specify both 'proto' and 'bin' arguments" + if bin is not None: + warnings.warn("The 'bin' argument to Pickler() is deprecated", + PendingDeprecationWarning) + proto = bin + if proto is None: + proto = 0 if proto < 0: proto = 2 *************** *** 1465,1474 **** from StringIO import StringIO ! def dump(obj, file, proto=0): ! Pickler(file, proto).dump(obj) ! def dumps(obj, proto=0): file = StringIO() ! Pickler(file, proto).dump(obj) return file.getvalue() --- 1473,1482 ---- from StringIO import StringIO ! def dump(obj, file, proto=None, bin=None): ! Pickler(file, proto, bin).dump(obj) ! def dumps(obj, proto=None, bin=None): file = StringIO() ! Pickler(file, proto, bin).dump(obj) return file.getvalue() From montanaro@users.sourceforge.net Mon Feb 3 17:24:21 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 09:24:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv31512 Modified Files: test_csv.py Log Message: replicate Excel tests with a dialect using TABs as the delimiter and colons as the quotechar. All this duplication probably isn't needed. Hopefully it helps cover a few more lines in _csv.c though. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** test_csv.py 3 Feb 2003 06:45:59 -0000 1.10 --- test_csv.py 3 Feb 2003 17:24:18 -0000 1.11 *************** *** 112,115 **** --- 112,212 ---- self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') + class MyWeirdDialect(csv.excel): + quotechar = ':' + delimiter = '\t' + + class TestExcelTabsColons(TestCsvBase): + dialect = MyWeirdDialect() + + def test_single(self): + self.readerAssertEqual('abc', [['abc']]) + + def test_simple(self): + self.readerAssertEqual('1\t2\t3\t4\t5', [['1','2','3','4','5']]) + + def test_blankline(self): + self.readerAssertEqual('', []) + + def test_empty_fields(self): + self.readerAssertEqual('\t', [['', '']]) + + def test_singlequoted(self): + self.readerAssertEqual('::', [['']]) + + def test_singlequoted_left_empty(self): + self.readerAssertEqual('::\t', [['','']]) + + def test_singlequoted_right_empty(self): + self.readerAssertEqual('\t::', [['','']]) + + def test_single_quoted_quote(self): + self.readerAssertEqual('::::', [[':']]) + + def test_quoted_quotes(self): + self.readerAssertEqual('::::::', [['::']]) + + def test_inline_quote(self): + self.readerAssertEqual('a::b', [['a::b']]) + + def test_inline_quotes(self): + self.readerAssertEqual('a:b:c', [['a:b:c']]) + + def test_quotes_and_more(self): + self.readerAssertEqual(':a:b', [['ab']]) + + def test_lone_quote(self): + self.readerAssertEqual('a:b', [['a:b']]) + + def test_quote_and_quote(self): + self.readerAssertEqual(':a: :b:', [['a :b:']]) + + def test_space_and_quote(self): + self.readerAssertEqual(' :a:', [[' :a:']]) + + def test_quoted(self): + self.readerAssertEqual('1\t2\t3\t:I think,\ttherefore I am:\t5\t6', + [['1', '2', '3', + 'I think,\ttherefore I am', + '5', '6']]) + + def test_quoted_quote(self): + self.readerAssertEqual('1\t2\t3\t:"I see,"\tsaid the blind man:\t:as he picked up his hammer and saw:', + [['1', '2', '3', + '"I see,"\tsaid the blind man', + 'as he picked up his hammer and saw']]) + + def test_quoted_nl(self): + input = '''\ + 1\t2\t3\t:"I see," + \tsaid the blind man:\t:as he picked up his + hammer and saw: + 9\t8\t7\t6''' + self.readerAssertEqual(input, + [['1', '2', '3', + '"I see,"\n\tsaid the blind man', + 'as he picked up his\nhammer and saw'], + ['9','8','7','6']]) + + def test_dubious_quote(self): + self.readerAssertEqual('12\t12\t1:\t', [['12', '12', '1:', '']]) + + def test_null(self): + self.writerAssertEqual([], '') + + def test_single(self): + self.writerAssertEqual([['abc']], 'abc\r\n') + + def test_simple(self): + self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1\t2\tabc\t3\t4\r\n') + + def test_quotes(self): + self.writerAssertEqual([[1, 2, 'a:bc:', 3, 4]], '1\t2\t:a::bc:::\t3\t4\r\n') + + def test_quote_fieldsep(self): + self.writerAssertEqual([['abc\tdef']], ':abc\tdef:\r\n') + + def test_newlines(self): + self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1\t2\t:a\nbc:\t3\t4\r\n') + class TestDictFields(unittest.TestCase): def test_simple_dict(self): From montanaro@users.sourceforge.net Mon Feb 3 17:28:59 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 09:28:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv896 Modified Files: test_csv.py Log Message: that was a dumb waste of time. I should have known there was no code in _csv.c that depended on specific delimiters and quotechars... Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_csv.py 3 Feb 2003 17:24:18 -0000 1.11 --- test_csv.py 3 Feb 2003 17:28:55 -0000 1.12 *************** *** 112,212 **** self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') - class MyWeirdDialect(csv.excel): - quotechar = ':' - delimiter = '\t' - - class TestExcelTabsColons(TestCsvBase): - dialect = MyWeirdDialect() - - def test_single(self): - self.readerAssertEqual('abc', [['abc']]) - - def test_simple(self): - self.readerAssertEqual('1\t2\t3\t4\t5', [['1','2','3','4','5']]) - - def test_blankline(self): - self.readerAssertEqual('', []) - - def test_empty_fields(self): - self.readerAssertEqual('\t', [['', '']]) - - def test_singlequoted(self): - self.readerAssertEqual('::', [['']]) - - def test_singlequoted_left_empty(self): - self.readerAssertEqual('::\t', [['','']]) - - def test_singlequoted_right_empty(self): - self.readerAssertEqual('\t::', [['','']]) - - def test_single_quoted_quote(self): - self.readerAssertEqual('::::', [[':']]) - - def test_quoted_quotes(self): - self.readerAssertEqual('::::::', [['::']]) - - def test_inline_quote(self): - self.readerAssertEqual('a::b', [['a::b']]) - - def test_inline_quotes(self): - self.readerAssertEqual('a:b:c', [['a:b:c']]) - - def test_quotes_and_more(self): - self.readerAssertEqual(':a:b', [['ab']]) - - def test_lone_quote(self): - self.readerAssertEqual('a:b', [['a:b']]) - - def test_quote_and_quote(self): - self.readerAssertEqual(':a: :b:', [['a :b:']]) - - def test_space_and_quote(self): - self.readerAssertEqual(' :a:', [[' :a:']]) - - def test_quoted(self): - self.readerAssertEqual('1\t2\t3\t:I think,\ttherefore I am:\t5\t6', - [['1', '2', '3', - 'I think,\ttherefore I am', - '5', '6']]) - - def test_quoted_quote(self): - self.readerAssertEqual('1\t2\t3\t:"I see,"\tsaid the blind man:\t:as he picked up his hammer and saw:', - [['1', '2', '3', - '"I see,"\tsaid the blind man', - 'as he picked up his hammer and saw']]) - - def test_quoted_nl(self): - input = '''\ - 1\t2\t3\t:"I see," - \tsaid the blind man:\t:as he picked up his - hammer and saw: - 9\t8\t7\t6''' - self.readerAssertEqual(input, - [['1', '2', '3', - '"I see,"\n\tsaid the blind man', - 'as he picked up his\nhammer and saw'], - ['9','8','7','6']]) - - def test_dubious_quote(self): - self.readerAssertEqual('12\t12\t1:\t', [['12', '12', '1:', '']]) - - def test_null(self): - self.writerAssertEqual([], '') - - def test_single(self): - self.writerAssertEqual([['abc']], 'abc\r\n') - - def test_simple(self): - self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1\t2\tabc\t3\t4\r\n') - - def test_quotes(self): - self.writerAssertEqual([[1, 2, 'a:bc:', 3, 4]], '1\t2\t:a::bc:::\t3\t4\r\n') - - def test_quote_fieldsep(self): - self.writerAssertEqual([['abc\tdef']], ':abc\tdef:\r\n') - - def test_newlines(self): - self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1\t2\t:a\nbc:\t3\t4\r\n') - class TestDictFields(unittest.TestCase): def test_simple_dict(self): --- 112,115 ---- From montanaro@users.sourceforge.net Mon Feb 3 17:37:34 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 09:37:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv5816 Modified Files: test_csv.py Log Message: a few more productive tests dealing with quoting and escaping. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_csv.py 3 Feb 2003 17:28:55 -0000 1.12 --- test_csv.py 3 Feb 2003 17:37:29 -0000 1.13 *************** *** 112,115 **** --- 112,141 ---- self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') + class EscapedExcel(csv.excel): + quoting = csv.QUOTE_NONE + escapechar = '\\' + + class TestEscapedExcel(TestCsvBase): + dialect = EscapedExcel() + + def test_escape_fieldsep(self): + self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n') + + def test_read_escape_fieldsep(self): + self.readerAssertEqual('abc\\,def\r\n', [['abc,def']]) + + class QuotedEscapedExcel(csv.excel): + quoting = csv.QUOTE_NONNUMERIC + escapechar = '\\' + + class TestQuotedEscapedExcel(TestCsvBase): + dialect = QuotedEscapedExcel() + + def test_write_escape_fieldsep(self): + self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') + + def test_read_escape_fieldsep(self): + self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']]) + class TestDictFields(unittest.TestCase): def test_simple_dict(self): From gvanrossum@users.sourceforge.net Mon Feb 3 17:50:21 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 09:50:21 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv12555 Modified Files: pep-0307.txt Log Message: Misc tweaks and updates. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** pep-0307.txt 1 Feb 2003 20:10:35 -0000 1.5 --- pep-0307.txt 3 Feb 2003 17:50:16 -0000 1.6 *************** *** 27,30 **** --- 27,36 ---- CVS for Python 2.3). + This PEP attempts to fully document the interface between pickled + objects and the pickling process, highlighting additions by + specifying "new in this PEP". (The interface to invoke pickling + or unpickling is not covered fully, except for the changes to the + API for specifying the pickling protocol to picklers.) + Motivation *************** *** 79,82 **** --- 85,97 ---- This works in previous Python versions, too. + The pickle.py module has supported passing the 'bin' value as a + keyword argument rather than a positional argument. (This is not + recommended, since cPickle only accepts positional arguments, but + it works...) Passing 'bin' as a keyword argument is deprecated, + and a PendingDeprecationWarning is issued in this case. You have + to invoke the Python interpreter with -Wa or a variation on that + to see PendingDeprecationWarning messages. In Python 2.4, the + warning class may be upgraded to DeprecationWarning. + Security issues *************** *** 106,109 **** --- 121,127 ---- unauthenticated source *** + The same warning applies to previous Python versions, despite the + presence of safety checks there. + Extended __reduce__ API *************** *** 185,188 **** --- 203,215 ---- state with value None. + A __reduce__ implementation that needs to work both under Python + 2.2 and under Python 2.3 could check the variable + pickle.format_version to determine whether to use the listitems + and dictitems features. If this value is >= "2.0" then they are + supported. If not, any list or dict items should be incorporated + somehow in the 'state' return value; the __setstate__ method + should be prepared to accept list or dict items as part of the + state (how this is done is up to the application). + The __newobj__ unpickling function *************** *** 205,208 **** --- 232,239 ---- function named __newobj__ that returns something different, you deserve what you get. + + It is safe to use this feature under Python 2.2; there's nothing + in the recommended implementation of __newobj__ that depends on + Python 2.3. From gvanrossum@users.sourceforge.net Mon Feb 3 18:10:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 10:10:15 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.141,1.142 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv23466 Modified Files: pickle.py Log Message: _slotnames(): exclude __dict__ and __weakref__; these aren't real slots even though they can be listed in __slots__. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.141 retrieving revision 1.142 diff -C2 -d -r1.141 -r1.142 *** pickle.py 3 Feb 2003 16:59:48 -0000 1.141 --- pickle.py 3 Feb 2003 18:10:09 -0000 1.142 *************** *** 882,886 **** for c in cls.__mro__: if "__slots__" in c.__dict__: ! names += list(c.__dict__["__slots__"]) return names --- 882,887 ---- for c in cls.__mro__: if "__slots__" in c.__dict__: ! names += [name for name in c.__dict__["__slots__"] ! if name not in ("__dict__", "__weakref__")] return names From akuchling@users.sourceforge.net Mon Feb 3 19:11:22 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 03 Feb 2003 11:11:22 -0800 Subject: [Python-checkins] python/dist/src/Lib BaseHTTPServer.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv17964 Modified Files: BaseHTTPServer.py Log Message: [Bug #676292] BaseHTTPServer incorrectly parses protocol; fix by Andrew Dalke * Treat major, minor numbers of HTTP version as separate integers * Fix errors if version string is "HTTP/1.2.3" or even simply "BLAH". * send_error() checks if 'self.command' is a HEAD. However, if there's an error parsing the first line of the HTTP request the self.command wasn't set yet; force self.command to be initialized to None. Index: BaseHTTPServer.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/BaseHTTPServer.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** BaseHTTPServer.py 3 Feb 2003 15:21:15 -0000 1.23 --- BaseHTTPServer.py 3 Feb 2003 19:11:18 -0000 1.24 *************** *** 227,230 **** --- 227,231 ---- """ + self.command = None # set in case of error on the first line self.request_version = version = "HTTP/0.9" # Default self.close_connection = 1 *************** *** 242,254 **** return False try: ! version_number = float(version.split('/', 1)[1]) ! except ValueError: self.send_error(400, "Bad request version (%s)" % `version`) return False ! if version_number >= 1.1 and self.protocol_version >= "HTTP/1.1": self.close_connection = 0 ! if version_number >= 2.0: self.send_error(505, ! "Invalid HTTP Version (%f)" % version_number) return False elif len(words) == 2: --- 243,265 ---- return False try: ! base_version_number = version.split('/', 1)[1] ! version_number = base_version_number.split(".") ! # RFC 2145 section 3.1 says there can be only one "." and ! # - major and minor numbers MUST be treated as ! # separate integers; ! # - HTTP/2.4 is a lower version than HTTP/2.13, which in ! # turn is lower than HTTP/12.3; ! # - Leading zeros MUST be ignored by recipients. ! if len(version_number) != 2: ! raise ValueError ! version_number = int(version_number[0]), int(version_number[1]) ! except (ValueError, IndexError): self.send_error(400, "Bad request version (%s)" % `version`) return False ! if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": self.close_connection = 0 ! if version_number >= (2, 0): self.send_error(505, ! "Invalid HTTP Version (%s)" % base_version_number) return False elif len(words) == 2: From gvanrossum@users.sourceforge.net Mon Feb 3 19:46:58 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 11:46:58 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.142,1.143 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv2565 Modified Files: pickle.py Log Message: _slotnames(): this is a fairly expensive calculation. Cache the outcome as __slotnames__ on the class. (Like __slots__, it's not safe to ask for this as an attribute -- you must look for it in the specific class's __dict__. But it must be set using attribute notation, because __dict__ is a read-only proxy.) Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.142 retrieving revision 1.143 diff -C2 -d -r1.142 -r1.143 *** pickle.py 3 Feb 2003 18:10:09 -0000 1.142 --- pickle.py 3 Feb 2003 19:46:54 -0000 1.143 *************** *** 877,887 **** defined.) """ ! if not hasattr(cls, "__slots__"): ! return [] names = [] ! for c in cls.__mro__: ! if "__slots__" in c.__dict__: ! names += [name for name in c.__dict__["__slots__"] ! if name not in ("__dict__", "__weakref__")] return names --- 877,904 ---- defined.) """ ! ! # Get the value from a cache in the class if possible ! names = cls.__dict__.get("__slotnames__") ! if names is not None: ! return names ! ! # Not cached -- calculate the value names = [] ! if not hasattr(cls, "__slots__"): ! # This class has no slots ! pass ! else: ! # Slots found -- gather slot names from all base classes ! for c in cls.__mro__: ! if "__slots__" in c.__dict__: ! names += [name for name in c.__dict__["__slots__"] ! if name not in ("__dict__", "__weakref__")] ! ! # Cache the outcome in the class if at all possible ! try: ! cls.__slotnames__ = names ! except: ! pass # But don't die if we can't ! return names From doerwalter@users.sourceforge.net Mon Feb 3 20:17:21 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:17:21 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_pow,1.2,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv15333/Lib/test/output Removed Files: test_pow Log Message: Port test_pow.py to PyUnit. From SF patch #662807 --- test_pow DELETED --- From doerwalter@users.sourceforge.net Mon Feb 3 20:17:21 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:17:21 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_pow.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15333/Lib/test Modified Files: test_pow.py Log Message: Port test_pow.py to PyUnit. From SF patch #662807 Index: test_pow.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pow.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_pow.py 7 Dec 2002 10:05:27 -0000 1.16 --- test_pow.py 3 Feb 2003 20:17:19 -0000 1.17 *************** *** 1,125 **** ! import sys ! from test import test_support ! def powtest(type): ! if type != float: ! print " Testing 2-argument pow() function..." ! for i in range(-1000, 1000): ! if pow(type(i), 0) != 1: ! raise ValueError, 'pow('+str(i)+',0) != 1' ! if pow(type(i), 1) != type(i): ! raise ValueError, 'pow('+str(i)+',1) != '+str(i) ! if pow(type(0), 1) != type(0): ! raise ValueError, 'pow(0,'+str(i)+') != 0' ! if pow(type(1), 1) != type(1): ! raise ValueError, 'pow(1,'+str(i)+') != 1' ! for i in range(-100, 100): ! if pow(type(i), 3) != i*i*i: ! raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) ! pow2 = 1 ! for i in range(0,31): ! if pow(2, i) != pow2: ! raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) ! if i != 30 : pow2 = pow2*2 ! for othertype in int, long: ! for i in range(-10, 0) + range(1, 10): ! ii = type(i) ! for j in range(1, 11): ! jj = -othertype(j) ! try: pow(ii, jj) - except ValueError: - raise ValueError, "pow(%s, %s) failed" % (ii, jj) ! for othertype in int, long, float: ! for i in range(1, 100): ! zero = type(0) ! exp = -othertype(i/10.0) ! if exp == 0: ! continue ! try: ! pow(zero, exp) ! except ZeroDivisionError: ! pass # taking zero to any negative exponent should fail ! else: ! raise ValueError, "pow(%s, %s) did not fail" % (zero, exp) ! print " Testing 3-argument pow() function..." ! il, ih = -20, 20 ! jl, jh = -5, 5 ! kl, kh = -10, 10 ! compare = cmp ! if type == float: ! il = 1 ! compare = test_support.fcmp ! elif type == int: ! jl = 0 ! elif type == long: ! jl, jh = 0, 15 ! for i in range(il, ih+1): ! for j in range(jl, jh+1): ! for k in range(kl, kh+1): ! if k != 0: ! if type == float or j < 0: ! try: ! pow(type(i),j,k) ! except TypeError: ! pass ! else: ! raise ValueError, "expected TypeError from " + \ ! "pow%r" % ((type(i), j, k),) ! continue ! if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): ! raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ ! "," +str(k)+ ") != pow(" +str(i)+ "," + \ ! str(j)+ ") % " +str(k) ! print 'Testing integer mode...' ! powtest(int) ! print 'Testing long integer mode...' ! powtest(long) ! print 'Testing floating point mode...' ! powtest(float) ! # Other tests-- not very systematic ! print 'The number in both columns should match.' ! print `pow(3,3) % 8`, `pow(3,3,8)` ! print `pow(3,3) % -8`, `pow(3,3,-8)` ! print `pow(3,2) % -2`, `pow(3,2,-2)` ! print `pow(-3,3) % 8`, `pow(-3,3,8)` ! print `pow(-3,3) % -8`, `pow(-3,3,-8)` ! print `pow(5,2) % -8`, `pow(5,2,-8)` ! print ! print `pow(3L,3L) % 8`, `pow(3L,3L,8)` ! print `pow(3L,3L) % -8`, `pow(3L,3L,-8)` ! print `pow(3L,2) % -2`, `pow(3L,2,-2)` ! print `pow(-3L,3L) % 8`, `pow(-3L,3L,8)` ! print `pow(-3L,3L) % -8`, `pow(-3L,3L,-8)` ! print `pow(5L,2) % -8`, `pow(5L,2,-8)` ! print ! print ! for i in range(-10, 11): ! for j in range(0, 6): ! for k in range(-7, 11): ! if j >= 0 and k != 0: ! o = pow(i,j) % k ! n = pow(i,j,k) ! if o != n: print 'Integer mismatch:', i,j,k ! if j >= 0 and k != 0: ! o = pow(long(i),j) % k ! n = pow(long(i),j,k) ! if o != n: print 'Integer mismatch:', i,j,k ! class TestRpow: ! def __rpow__(self, other): ! return None ! None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. --- 1,111 ---- ! import test.test_support, unittest + class PowTest(unittest.TestCase): ! def powtest(self, type): ! if type != float: ! for i in range(-1000, 1000): ! self.assertEquals(pow(type(i), 0), 1) ! self.assertEquals(pow(type(i), 1), type(i)) ! self.assertEquals(pow(type(0), 1), type(0)) ! self.assertEquals(pow(type(1), 1), type(1)) ! for i in range(-100, 100): ! self.assertEquals(pow(type(i), 3), i*i*i) ! pow2 = 1 ! for i in range(0,31): ! self.assertEquals(pow(2, i), pow2) ! if i != 30 : pow2 = pow2*2 ! for othertype in int, long: ! for i in range(-10, 0) + range(1, 10): ! ii = type(i) ! for j in range(1, 11): ! jj = -othertype(j) pow(ii, jj) ! for othertype in int, long, float: ! for i in range(1, 100): ! zero = type(0) ! exp = -othertype(i/10.0) ! if exp == 0: ! continue ! self.assertRaises(ZeroDivisionError, pow, zero, exp) ! il, ih = -20, 20 ! jl, jh = -5, 5 ! kl, kh = -10, 10 ! asseq = self.assertEqual ! if type == float: ! il = 1 ! asseq = self.assertAlmostEqual ! elif type == int: ! jl = 0 ! elif type == long: ! jl, jh = 0, 15 ! for i in range(il, ih+1): ! for j in range(jl, jh+1): ! for k in range(kl, kh+1): ! if k != 0: ! if type == float or j < 0: ! self.assertRaises(TypeError, pow, type(i), j, k) ! continue ! asseq( ! pow(type(i),j,k), ! pow(type(i),j)% type(k) ! ) + def test_powint(self): + self.powtest(int) ! def test_powlong(self): ! self.powtest(long) ! def test_powfloat(self): ! self.powtest(float) ! def test_other(self): ! # Other tests-- not very systematic ! self.assertEquals(pow(3,3) % 8, pow(3,3,8)) ! self.assertEquals(pow(3,3) % -8, pow(3,3,-8)) ! self.assertEquals(pow(3,2) % -2, pow(3,2,-2)) ! self.assertEquals(pow(-3,3) % 8, pow(-3,3,8)) ! self.assertEquals(pow(-3,3) % -8, pow(-3,3,-8)) ! self.assertEquals(pow(5,2) % -8, pow(5,2,-8)) ! self.assertEquals(pow(3L,3L) % 8, pow(3L,3L,8)) ! self.assertEquals(pow(3L,3L) % -8, pow(3L,3L,-8)) ! self.assertEquals(pow(3L,2) % -2, pow(3L,2,-2)) ! self.assertEquals(pow(-3L,3L) % 8, pow(-3L,3L,8)) ! self.assertEquals(pow(-3L,3L) % -8, pow(-3L,3L,-8)) ! self.assertEquals(pow(5L,2) % -8, pow(5L,2,-8)) ! for i in range(-10, 11): ! for j in range(0, 6): ! for k in range(-7, 11): ! if j >= 0 and k != 0: ! self.assertEquals( ! pow(i,j) % k, ! pow(i,j,k) ! ) ! if j >= 0 and k != 0: ! self.assertEquals( ! pow(long(i),j) % k, ! pow(long(i),j,k) ! ) ! def test_bug643260(self): ! class TestRpow: ! def __rpow__(self, other): ! return None ! None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(PowTest)) ! test.test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() From gvanrossum@users.sourceforge.net Mon Feb 3 20:22:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:22:26 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv17587 Modified Files: pep-0307.txt Log Message: Added docs for __getstate__ and __setstate__, __getinitargs__ and __getnewargs__. Unfortunately these need to be refactored again according to a different organizing principle. ;-( Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** pep-0307.txt 3 Feb 2003 17:50:16 -0000 1.6 --- pep-0307.txt 3 Feb 2003 20:22:23 -0000 1.7 *************** *** 138,141 **** --- 138,145 ---- though, and we'll refer to these collectively as __reduce__. + IMPORTANT: a classic class cannot provide __reduce__ + functionality. It must use __getinitargs__ and/or __gestate__ to + customize pickling. These are described below. + __reduce__ must return either a string or a tuple. If it returns a string, this is an object whose state is not to be pickled, but *************** *** 213,216 **** --- 217,232 ---- + XXX Refactoring needed + + The following sections should really be reorganized according to + the following cases: + + 1. classic classes, all protocols + + 2. new-style classes, protocols 0 and 1 + + 3. new-style classes, protocol 2 + + The __newobj__ unpickling function *************** *** 236,239 **** --- 252,395 ---- in the recommended implementation of __newobj__ that depends on Python 2.3. + + + The __getstate__ and __setstate__ methods + + When there is no __reduce__ for an object, the primary ways to + customize pickling is by specifying __getstate__ and/or + __setstate__ methods. These are supported for classic classes as + well as for new-style classes for which no __reduce__ exists. + + When __reduce__ exists, __getstate__ is not called (unless your + __reduce__ implementation calls it), but __getstate__ will be + called with the third item from the tuple returned by __reduce__, + if not None. + + There's a subtle difference between classic and new-style classes + here: if a classic class's __getstate__ returns None, + self.__setstate__(None) will be called as part of unpickling. But + if a new-style class's __getstate__ returns None, its __setstate__ + won't be called at all as part of unpickling. + + The __getstate__ method is supposed to return a picklable version + of an object's state that does not reference the object itself. + If no __getstate__ method exists, a default state is assumed. + There are several cases: + + - For a classic class, the default state is self.__dict__. + + - For a new-style class that has an instance __dict__ and no + __slots__, the default state is self.__dict__. + + - For a new-style class that has no instance __dict__ and no + __slots__, the default __state__ is None. + + - For a new-style class that has an instance __dict__ and + __slots__, the default state is a tuple consisting of two + dictionaries: the first being self.__dict__, and the second + being a dictionary mapping slot names to slot values. Only + slots that have a value are included in the latter. + + - For a new-style class that has __slots__ and no instance + __dict__, the default state is a tuple whose first item is None + and whose second item is a dictionary mapping slot names to slot + values described in the previous bullet. + + The __setstate__ should take one argument; it will be called with + the value returned by __getstate__ or with the default state + described above if no __setstate__ method is defined. + + If no __setstate__ method exists, a default implementation is + provided that can handle the state returned by the default + __getstate__. + + It is fine if a class implements one of these but not the other, + as long as it is compatible with the default version. + + New-style classes that inherit a default __reduce__ implementation + from the ultimate base class 'object'. This implementation is not + used for protocol 2, and then last four bullets above apply. For + protocols 0 and 1, the default implementation looks for a + __getstate__ method, and if none exists, it uses a simpler default + strategy: + + - If there is an instance __dict__, the state is self.__dict__. + + - Otherwise, the state is None (and __setstate__ will not be + called). + + Note that this strategy ignores slots. New-style classes that + define slots and don't define __getstate__ in the same class that + defines the slots automatically have a __getstate__ method added + that raises TypeError. Protocol 2 ignores this __getstate__ + method (recognized by the specific text of the error message). + + + The __getinitargs__ and __getnewargs__ methods + + The __setstate__ method (or its default implementation) requires + that a new object already exists so that its __setstate__ method + can be called. The point is to create a new object that isn't + fully initialized; in particular, the class's __init__ method + should not be called if possible. + + The way this is done differs between classic and new-style + classes. + + For classic classes, these are the possibilities: + + - Normally, the following trick is used: create an instance of a + trivial classic class (one without any methods or instance + variables) and then use __class__ assignment to change its class + to the desired class. This creates an instance of the desired + class with an empty __dict__ whose __init__ has not been called. + + - However, if the class has a method named __getinitargs__, the + above trick is not used, and a class instance is created by + using the tuple returned by __getinitargs__ as an argument list + to the class constructor. This is done even if __getinitargs__ + returns an empty tuple -- a __getinitargs__ method that returns + () is not equivalent to not having __getinitargs__ at all. + __getinitargs__ *must* return a tuple. + + - In restricted execution mode, the trick from the first bullet + doesn't work; in this case, the class constructor is called with + an empty argument list if no __getinitargs__ method exists. + This means that in order for a classic class to be unpicklable + in restricted mode, it must either implement __getinitargs__ or + its constructor (i.e., its __init__ method) must be callable + without arguments. + + For new-style classes, these are the possibilities: + + - When using protocol 0 or 1, a default __reduce__ implementation + is normally inherited from the ultimate base class class + 'object'. This implementation finds the nearest base class that + is implemented in C (either as a built-in type or as a type + defined by an extension class). Calling this base class B and + the class of the object to be pickled C, the new object is + created at unpickling time using the following code: + + obj = B.__new__(C, state) + B.__init__(obj, state) + + where state is a value computed at pickling time as follows: + + state = B(obj) + + This only works when B is not C, and only for certain classes + B. It does work for the following built-in classes: int, long, + float, complex, str, unicode, tuple, list, dict; and this is its + main redeeming factor. + + - When using protocol 2, the default __reduce__ implementation + inherited from 'object' is ignored. Instead, a new pickling + opcode is generated that causes a new object to be created as + follows: + + obj = C.__new__(C, *args) + + where args is either the empty tuple, or the tuple returned by + the __getnewargs__ method, if defined. From doerwalter@users.sourceforge.net Mon Feb 3 20:22:30 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:22:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/test README,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv17586/Lib/test Modified Files: README Log Message: Fix typos. Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/README,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** README 27 Nov 2002 15:47:10 -0000 1.17 --- README 3 Feb 2003 20:22:27 -0000 1.18 *************** *** 14,18 **** testing facility provided with Python; any particular test should use only one of these options. Each option requires writing a test module using the ! conventions of the the selected option: - PyUnit_ based tests --- 14,18 ---- testing facility provided with Python; any particular test should use only one of these options. Each option requires writing a test module using the ! conventions of the selected option: - PyUnit_ based tests *************** *** 42,46 **** the interface and general guidelines on writing PyUnit based tests. ! The test_support helper module provides a two functions for use by PyUnit based tests in the Python regression testing framework: --- 42,46 ---- the interface and general guidelines on writing PyUnit based tests. ! The test_support helper module provides two functions for use by PyUnit based tests in the Python regression testing framework: From nnorwitz@users.sourceforge.net Mon Feb 3 20:23:37 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:23:37 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.271,2.272 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv18087a/Python Modified Files: bltinmodule.c Log Message: SF #661437, apply() should get PendingDeprecation Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.271 retrieving revision 2.272 diff -C2 -d -r2.271 -r2.272 *** bltinmodule.c 25 Jan 2003 22:46:11 -0000 2.271 --- bltinmodule.c 3 Feb 2003 20:23:33 -0000 2.272 *************** *** 74,77 **** --- 74,80 ---- PyObject *t = NULL, *retval = NULL; + PyErr_Warn(PyExc_PendingDeprecationWarning, + "use func(*args, **kwargs) instead of " + "apply(func, args, kwargs)"); if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict)) return NULL; From montanaro@users.sourceforge.net Mon Feb 3 20:25:22 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:25:22 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv18989 Modified Files: csv.py Log Message: Rearrange the dialect code a bit. Add a _name attribute to the Dialect class and set it in register_dialect. Add an unregister_dialect function. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** csv.py 3 Feb 2003 06:44:13 -0000 1.18 --- csv.py 3 Feb 2003 20:25:19 -0000 1.19 *************** *** 4,12 **** __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", "Error", "Dialect", "excel", "excel_tab", "reader", "writer", ! "register_dialect", "get_dialect", "list_dialects"] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) class Dialect: delimiter = ',' quotechar = '"' --- 4,31 ---- __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", "Error", "Dialect", "excel", "excel_tab", "reader", "writer", ! "register_dialect", "get_dialect", "list_dialects", ! "unregister_dialect" ] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) + _dialects = {} + + def register_dialect(name, dialect): + if not issubclass(dialect, Dialect): + raise TypeError, "dialect not a subclass of Dialect" + dialect._name = name + _dialects[name] = dialect() + + def get_dialect(name): + return _dialects[name] + + def list_dialects(): + return _dialects.keys() + + def unregister_dialect(name): + del _dialects[name] + class Dialect: + _name = "" delimiter = ',' quotechar = '"' *************** *** 19,30 **** class excel(Dialect): pass class excel_tab(excel): delimiter = '\t' ! ! _dialects = { ! 'excel': excel(), ! 'excel-tab': excel_tab(), ! } class _OCcsv: --- 38,46 ---- class excel(Dialect): pass + register_dialect("excel", excel) class excel_tab(excel): delimiter = '\t' ! register_dialect("excel-tab", excel_tab) class _OCcsv: *************** *** 81,95 **** for fields in lines: self.writerow(fields) - - def register_dialect(name, dialect): - if not issubclass(dialect, Dialect): - raise TypeError, "dialect not a subclass of Dialect" - _dialects[name] = dialect() - - def get_dialect(name): - return _dialects[name] - - def list_dialects(): - return _dialects.keys() # An alternate way of populating the dialects dictionary... --- 97,100 ---- From montanaro@users.sourceforge.net Mon Feb 3 20:26:28 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:26:28 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv19587 Modified Files: test_csv.py Log Message: Add test for list_dialects. Call unregister_dialect where appropriate instead of fiddling _dialects directly. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** test_csv.py 3 Feb 2003 17:37:29 -0000 1.13 --- test_csv.py 3 Feb 2003 20:26:26 -0000 1.14 *************** *** 198,206 **** self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), myexceltsv), 1==1) ! del csv._dialects["myexceltsv"] def test_get(self): self.assertEqual(isinstance(csv.get_dialect("excel"), csv.excel), 1==1) def test_bad_register(self): --- 198,211 ---- self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), myexceltsv), 1==1) ! csv.unregister_dialect("myexceltsv") def test_get(self): self.assertEqual(isinstance(csv.get_dialect("excel"), csv.excel), 1==1) + + def test_list(self): + for dname in csv.list_dialects(): + d = csv.get_dialect(dname) + self.assertEqual(d._name, dname) def test_bad_register(self): From gvanrossum@users.sourceforge.net Mon Feb 3 20:45:52 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:45:52 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_zlib,1.5,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv30447/Lib/test/output Removed Files: test_zlib Log Message: - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrite the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) Backport candidate I think. --- test_zlib DELETED --- From gvanrossum@users.sourceforge.net Mon Feb 3 20:45:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:45:56 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.638,1.639 ACKS,1.225,1.226 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv30447/Misc Modified Files: NEWS ACKS Log Message: - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrite the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) Backport candidate I think. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.638 retrieving revision 1.639 diff -C2 -d -r1.638 -r1.639 *** NEWS 3 Feb 2003 15:48:10 -0000 1.638 --- NEWS 3 Feb 2003 20:45:50 -0000 1.639 *************** *** 34,37 **** --- 34,42 ---- ----------------- + - Thanks to Scott David Daniels, a subtle bug in how the zlib + extension implemented flush() was fixed. Scott also rewrite the + zlib test suite using the unittest module. (SF bug #640230 and + patch #678531.) + - Added an itertools module containing high speed, memory efficient looping constructs inspired by tools from Haskell and SML. Index: ACKS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/ACKS,v retrieving revision 1.225 retrieving revision 1.226 diff -C2 -d -r1.225 -r1.226 *** ACKS 27 Jan 2003 22:19:55 -0000 1.225 --- ACKS 3 Feb 2003 20:45:52 -0000 1.226 *************** *** 124,127 **** --- 124,128 ---- Lars Damerow Eric Daniel + Scott David Daniels Ben Darnell Jonathan Dasteel From gvanrossum@users.sourceforge.net Mon Feb 3 20:46:21 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:46:21 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_zlib.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv30447/Lib/test Modified Files: test_zlib.py Log Message: - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrite the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) Backport candidate I think. Index: test_zlib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_zlib.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** test_zlib.py 12 Aug 2002 15:26:05 -0000 1.19 --- test_zlib.py 3 Feb 2003 20:45:48 -0000 1.20 *************** *** 1,168 **** import zlib ! import sys ! import imp ! from test.test_support import TestFailed ! try: ! t = imp.find_module('test_zlib') ! file = t[0] ! except ImportError: ! file = open(__file__) ! buf = file.read() * 8 ! file.close() ! # test the checksums (hex so the test doesn't break on 64-bit machines) ! def fix(x): ! return "0x%x" % (x & 0xffffffffL) ! print fix(zlib.crc32('penguin')), fix(zlib.crc32('penguin', 1)) ! print fix(zlib.adler32('penguin')), fix(zlib.adler32('penguin', 1)) - # make sure we generate some expected errors - try: - zlib.compress('ERROR', zlib.MAX_WBITS + 1) - except zlib.error, msg: - print "expecting", msg - try: - zlib.compressobj(1, 8, 0) - except ValueError, msg: - print "expecting", msg - try: - zlib.decompressobj(0) - except ValueError, msg: - print "expecting", msg - x = zlib.compress(buf) - y = zlib.decompress(x) - if buf != y: - print "normal compression/decompression failed" - else: - print "normal compression/decompression succeeded" ! buf = buf * 16 ! co = zlib.compressobj(8, 8, -15) ! x1 = co.compress(buf) ! x2 = co.flush() ! try: ! co.flush() ! print "Oops - second flush worked when it should not have!" ! except zlib.error: ! pass ! x = x1 + x2 ! dc = zlib.decompressobj(-15) ! y1 = dc.decompress(x) ! y2 = dc.flush() ! y = y1 + y2 ! if buf != y: ! print "compress/decompression obj failed" ! else: ! print "compress/decompression obj succeeded" ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(buf), 256): ! bufs.append(co.compress(buf[i:i+256])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! decomp1 = zlib.decompress(combuf, -12, -5) ! if decomp1 != buf: ! print "decompress with init options failed" ! else: ! print "decompress with init options succeeded" ! deco = zlib.decompressobj(-12) ! bufs = [] ! for i in range(0, len(combuf), 128): ! bufs.append(deco.decompress(combuf[i:i+128])) ! bufs.append(deco.flush()) ! decomp2 = ''.join(bufs) ! if decomp2 != buf: ! print "decompressobj with init options failed" ! else: ! print "decompressobj with init options succeeded" - print "should be '':", `deco.unconsumed_tail` - # Check a decompression object with max_length specified - deco = zlib.decompressobj(-12) - cb = combuf - bufs = [] - while cb: - max_length = 1 + len(cb)/10 - chunk = deco.decompress(cb, max_length) - if len(chunk) > max_length: - print 'chunk too big (%d>%d)' % (len(chunk),max_length) - bufs.append(chunk) - cb = deco.unconsumed_tail - bufs.append(deco.flush()) - decomp2 = ''.join(buf) - if decomp2 != buf: - print "max_length decompressobj failed" - else: - print "max_length decompressobj succeeded" ! # Misc tests of max_length ! deco = zlib.decompressobj(-12) ! try: ! deco.decompress("", -1) ! except ValueError: ! pass ! else: ! print "failed to raise value error on bad max_length" ! print "unconsumed_tail should be '':", `deco.unconsumed_tail` ! # Test flush() with the various options, using all the different levels ! # in order to provide more variations. ! sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH'] ! sync_opt = [getattr(zlib, opt) for opt in sync_opt if hasattr(zlib, opt)] ! for sync in sync_opt: ! for level in range(10): ! obj = zlib.compressobj( level ) ! d = obj.compress( buf[:3000] ) ! d = d + obj.flush( sync ) ! d = d + obj.compress( buf[3000:] ) ! d = d + obj.flush() ! if zlib.decompress(d) != buf: ! print "Decompress failed: flush mode=%i, level=%i" % (sync,level) ! del obj - # Test for the odd flushing bugs noted in 2.0, and hopefully fixed in 2.1 - import random - random.seed(1) ! print 'Testing on 17K of random data' ! if hasattr(zlib, 'Z_SYNC_FLUSH'): ! # Create compressor and decompressor objects ! c=zlib.compressobj(9) ! d=zlib.decompressobj() ! # Try 17K of data ! # generate random data stream ! a="" ! for i in range(17*1024): ! a=a+chr(random.randint(0,255)) ! # compress, sync-flush, and decompress ! t = d.decompress( c.compress(a)+c.flush(zlib.Z_SYNC_FLUSH) ) - # if decompressed data is different from the input data, choke. - if len(t) != len(a): - print len(a),len(t),len(d.unused_data) - raise TestFailed, "output of 17K doesn't match" - def ignore(): - """An empty function with a big string. ! Make the compression algorithm work a little harder. ! """ ! """ LAERTES --- 1,418 ---- + import unittest + from test import test_support import zlib ! import random ! # print test_support.TESTFN ! def getbuf(): ! # This was in the original. Avoid non-repeatable sources. ! # Left here (unused) in case something wants to be done with it. ! import imp ! try: ! t = imp.find_module('test_zlib') ! file = t[0] ! except ImportError: ! file = open(__file__) ! buf = file.read() * 8 ! file.close() ! return buf ! class ChecksumTestCase(unittest.TestCase): ! # checksum test cases ! def test_crc32start(self): ! self.assertEqual(zlib.crc32(""), zlib.crc32("", 0)) ! def test_crc32empty(self): ! self.assertEqual(zlib.crc32("", 0), 0) ! self.assertEqual(zlib.crc32("", 1), 1) ! self.assertEqual(zlib.crc32("", 432), 432) ! def test_adler32start(self): ! self.assertEqual(zlib.adler32(""), zlib.adler32("", 1)) ! def test_adler32empty(self): ! self.assertEqual(zlib.adler32("", 0), 0) ! self.assertEqual(zlib.adler32("", 1), 1) ! self.assertEqual(zlib.adler32("", 432), 432) ! def assertEqual32(self, seen, expected): ! # 32-bit values masked -- checksums on 32- vs 64- bit machines ! # This is important if bit 31 (0x08000000L) is set. ! self.assertEqual(seen & 0x0FFFFFFFFL, expected & 0x0FFFFFFFFL) ! def test_penguins(self): ! self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L) ! self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94) ! self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6) ! self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7) ! self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0)) ! self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1)) ! class ExceptionTestCase(unittest.TestCase): ! # make sure we generate some expected errors ! def test_bigbits(self): ! # specifying total bits too large causes an error ! self.assertRaises(zlib.error, ! zlib.compress, 'ERROR', zlib.MAX_WBITS + 1) ! def test_badcompressobj(self): ! # verify failure on building compress object with bad params ! self.assertRaises(ValueError, zlib.compressobj, 1, 8, 0) ! def test_baddecompressobj(self): ! # verify failure on building decompress object with bad params ! self.assertRaises(ValueError, zlib.decompressobj, 0) ! class CompressTestCase(unittest.TestCase): ! # Test compression in one go (whole message compression) ! def test_speech(self): ! # decompress(compress(data)) better be data ! x = zlib.compress(hamlet_scene) ! self.assertEqual(zlib.decompress(x), hamlet_scene) ! def test_speech8(self): ! # decompress(compress(data)) better be data -- more compression chances ! data = hamlet_scene * 8 ! x = zlib.compress(data) ! self.assertEqual(zlib.decompress(x), data) ! def test_speech16(self): ! # decompress(compress(data)) better be data -- more compression chances ! data = hamlet_scene * 16 ! x = zlib.compress(data) ! self.assertEqual(zlib.decompress(x), data) ! def test_speech128(self): ! # decompress(compress(data)) better be data -- more compression chances ! data = hamlet_scene * 8 * 16 ! x = zlib.compress(data) ! self.assertEqual(zlib.decompress(x), data) ! def test_monotonic(self): ! # higher compression levels should not expand compressed size ! data = hamlet_scene * 8 * 16 ! last = length = len(zlib.compress(data, 0)) ! self.failUnless(last > len(data), "compress level 0 always expands") ! for level in range(10): ! length = len(zlib.compress(data, level)) ! self.failUnless(length <= last, ! 'compress level %d more effective than %d!' % ( ! level-1, level)) ! last = length ! class CompressObjectTestCase(unittest.TestCase): ! # Test compression object ! def test_pairsmall(self): ! # use compress object in straightforward manner, decompress w/ object ! data = hamlet_scene ! co = zlib.compressobj(8, 8, -15) ! x1 = co.compress(data) ! x2 = co.flush() ! self.assertRaises(zlib.error, co.flush) # second flush should not work ! dco = zlib.decompressobj(-15) ! y1 = dco.decompress(x1 + x2) ! y2 = dco.flush() ! self.assertEqual(data, y1 + y2) ! def test_pair(self): ! # straightforward compress/decompress objects, more compression ! data = hamlet_scene * 8 * 16 ! co = zlib.compressobj(8, 8, -15) ! x1 = co.compress(data) ! x2 = co.flush() ! self.assertRaises(zlib.error, co.flush) # second flush should not work ! dco = zlib.decompressobj(-15) ! y1 = dco.decompress(x1 + x2) ! y2 = dco.flush() ! self.assertEqual(data, y1 + y2) ! ! def test_compressincremental(self): ! # compress object in steps, decompress object as one-shot ! data = hamlet_scene * 8 * 16 ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), 256): ! bufs.append(co.compress(data[i:i+256])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! ! dco = zlib.decompressobj(-15) ! y1 = dco.decompress(''.join(bufs)) ! y2 = dco.flush() ! self.assertEqual(data, y1 + y2) ! ! def test_decompressincremental(self): ! # compress object in steps, decompress object in steps ! data = hamlet_scene * 8 * 16 ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), 256): ! bufs.append(co.compress(data[i:i+256])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! ! self.assertEqual(data, zlib.decompress(combuf, -12, -5)) ! ! dco = zlib.decompressobj(-12) ! bufs = [] ! for i in range(0, len(combuf), 128): ! bufs.append(dco.decompress(combuf[i:i+128])) ! self.assertEqual('', dco.unconsumed_tail, ######## ! "(A) uct should be '': not %d long" % ! len(dco.unconsumed_tail)) ! bufs.append(dco.flush()) ! self.assertEqual('', dco.unconsumed_tail, ######## ! "(B) uct should be '': not %d long" % ! len(dco.unconsumed_tail)) ! self.assertEqual(data, ''.join(bufs)) ! # Failure means: "decompressobj with init options failed" ! ! def test_decompinc(self,sizes=[128],flush=True,source=None,cx=256,dcx=64): ! # compress object in steps, decompress object in steps, loop sizes ! source = source or hamlet_scene ! for reps in sizes: ! data = source * reps ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), cx): ! bufs.append(co.compress(data[i:i+cx])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! ! self.assertEqual(data, zlib.decompress(combuf, -12, -5)) ! ! dco = zlib.decompressobj(-12) ! bufs = [] ! for i in range(0, len(combuf), dcx): ! bufs.append(dco.decompress(combuf[i:i+dcx])) ! self.assertEqual('', dco.unconsumed_tail, ######## ! "(A) uct should be '': not %d long" % ! len(dco.unconsumed_tail)) ! if flush: ! bufs.append(dco.flush()) ! else: ! while True: ! chunk = dco.decompress('') ! if chunk: ! bufs.append(chunk) ! else: ! break ! self.assertEqual('', dco.unconsumed_tail, ######## ! "(B) uct should be '': not %d long" % ! len(dco.unconsumed_tail)) ! self.assertEqual(data, ''.join(bufs)) ! # Failure means: "decompressobj with init options failed" ! ! def test_decompimax(self,sizes=[128],flush=True,source=None,cx=256,dcx=64): ! # compress in steps, decompress in length-restricted steps, loop sizes ! source = source or hamlet_scene ! for reps in sizes: ! # Check a decompression object with max_length specified ! data = source * reps ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), cx): ! bufs.append(co.compress(data[i:i+cx])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! self.assertEqual(data, zlib.decompress(combuf, -12, -5), ! 'compressed data failure') ! ! dco = zlib.decompressobj(-12) ! bufs = [] ! cb = combuf ! while cb: ! #max_length = 1 + len(cb)/10 ! chunk = dco.decompress(cb, dcx) ! self.failIf(len(chunk) > dcx, ! 'chunk too big (%d>%d)' % (len(chunk), dcx)) ! bufs.append(chunk) ! cb = dco.unconsumed_tail ! if flush: ! bufs.append(dco.flush()) ! else: ! while True: ! chunk = dco.decompress('', dcx) ! self.failIf(len(chunk) > dcx, ! 'chunk too big in tail (%d>%d)' % (len(chunk), dcx)) ! if chunk: ! bufs.append(chunk) ! else: ! break ! self.assertEqual(len(data), len(''.join(bufs))) ! self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') ! ! def test_decompressmaxlen(self): ! # Check a decompression object with max_length specified ! data = hamlet_scene * 8 * 16 ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), 256): ! bufs.append(co.compress(data[i:i+256])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! self.assertEqual(data, zlib.decompress(combuf, -12, -5), ! 'compressed data failure') ! ! dco = zlib.decompressobj(-12) ! bufs = [] ! cb = combuf ! while cb: ! max_length = 1 + len(cb)/10 ! chunk = dco.decompress(cb, max_length) ! self.failIf(len(chunk) > max_length, ! 'chunk too big (%d>%d)' % (len(chunk),max_length)) ! bufs.append(chunk) ! cb = dco.unconsumed_tail ! bufs.append(dco.flush()) ! self.assertEqual(len(data), len(''.join(bufs))) ! self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') ! ! def test_decompressmaxlenflushless(self): ! # identical to test_decompressmaxlen except flush is replaced ! # with an equivalent. This works and other fails on (eg) 2.2.2 ! data = hamlet_scene * 8 * 16 ! co = zlib.compressobj(2, 8, -12, 9, 1) ! bufs = [] ! for i in range(0, len(data), 256): ! bufs.append(co.compress(data[i:i+256])) ! bufs.append(co.flush()) ! combuf = ''.join(bufs) ! self.assertEqual(data, zlib.decompress(combuf, -12, -5), ! 'compressed data mismatch') ! ! dco = zlib.decompressobj(-12) ! bufs = [] ! cb = combuf ! while cb: ! max_length = 1 + len(cb)/10 ! chunk = dco.decompress(cb, max_length) ! self.failIf(len(chunk) > max_length, ! 'chunk too big (%d>%d)' % (len(chunk),max_length)) ! bufs.append(chunk) ! cb = dco.unconsumed_tail ! ! #bufs.append(dco.flush()) ! while len(chunk): ! chunk = dco.decompress('', max_length) ! self.failIf(len(chunk) > max_length, ! 'chunk too big (%d>%d)' % (len(chunk),max_length)) ! bufs.append(chunk) ! ! self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved') ! ! def test_maxlenmisc(self): ! # Misc tests of max_length ! dco = zlib.decompressobj(-12) ! self.assertRaises(ValueError, dco.decompress, "", -1) ! self.assertEqual('', dco.unconsumed_tail) ! ! def test_flushes(self): ! # Test flush() with the various options, using all the ! # different levels in order to provide more variations. ! sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH'] ! sync_opt = [getattr(zlib, opt) for opt in sync_opt ! if hasattr(zlib, opt)] ! data = hamlet_scene * 8 ! ! for sync in sync_opt: ! for level in range(10): ! obj = zlib.compressobj( level ) ! a = obj.compress( data[:3000] ) ! b = obj.flush( sync ) ! c = obj.compress( data[3000:] ) ! d = obj.flush() ! self.assertEqual(zlib.decompress(''.join([a,b,c,d])), ! data, ("Decompress failed: flush " ! "mode=%i, level=%i") % (sync, level)) ! del obj ! ! def test_odd_flush(self): ! # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1 ! import random ! ! if hasattr(zlib, 'Z_SYNC_FLUSH'): ! # Testing on 17K of "random" data ! ! # Create compressor and decompressor objects ! co = zlib.compressobj(9) ! dco = zlib.decompressobj() ! ! # Try 17K of data ! # generate random data stream ! try: ! # In 2.3 and later, WichmannHill is the RNG of the bug report ! gen = random.WichmannHill() ! except AttributeError: ! try: ! # 2.2 called it Random ! gen = random.Random() ! except AttributeError: ! # others might simply have a single RNG ! gen = random ! gen.seed(1) ! data = genblock(1, 17 * 1024, generator=gen) ! ! # compress, sync-flush, and decompress ! first = co.compress(data) ! second = co.flush(zlib.Z_SYNC_FLUSH) ! expanded = dco.decompress(first + second) ! ! # if decompressed data is different from the input data, choke. ! self.assertEqual(expanded, data, "17K random source doesn't match") ! ! def test_manydecompinc(self): ! # Run incremental decompress test for a large range of sizes ! self.test_decompinc(sizes=[1< Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv30447/Modules Modified Files: zlibmodule.c Log Message: - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrite the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) Backport candidate I think. Index: zlibmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/zlibmodule.c,v retrieving revision 2.65 retrieving revision 2.66 diff -C2 -d -r2.65 -r2.66 *** zlibmodule.c 23 Jul 2002 06:31:14 -0000 2.65 --- zlibmodule.c 3 Feb 2003 20:45:47 -0000 2.66 *************** *** 657,680 **** static PyObject * PyZlib_unflush(compobject *self, PyObject *args) - /*decompressor flush is a no-op because all pending data would have been - flushed by the decompress method. However, this routine previously called - inflateEnd, causing any further decompress or flush calls to raise - exceptions. This behaviour has been preserved.*/ { ! int err; PyObject * retval = NULL; ! if (!PyArg_ParseTuple(args, "")) return NULL; ENTER_ZLIB ! err = inflateEnd(&(self->zst)); ! if (err != Z_OK) ! zlib_error(self->zst, err, "from inflateEnd()"); ! else { ! self->is_initialised = 0; ! retval = PyString_FromStringAndSize(NULL, 0); } LEAVE_ZLIB --- 657,711 ---- static PyObject * PyZlib_unflush(compobject *self, PyObject *args) { ! int err, length = DEFAULTALLOC; PyObject * retval = NULL; + unsigned long start_total_out; ! if (!PyArg_ParseTuple(args, "|i:flush", &length)) ! return NULL; ! if (!(retval = PyString_FromStringAndSize(NULL, length))) return NULL; + ENTER_ZLIB ! start_total_out = self->zst.total_out; ! self->zst.avail_out = length; ! self->zst.next_out = (Byte *)PyString_AS_STRING(retval); ! ! Py_BEGIN_ALLOW_THREADS ! err = inflate(&(self->zst), Z_FINISH); ! Py_END_ALLOW_THREADS ! ! /* while Z_OK and the output buffer is full, there might be more output, ! so extend the output buffer and try again */ ! while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { ! if (_PyString_Resize(&retval, length << 1) < 0) ! goto error; ! self->zst.next_out = (Byte *)PyString_AS_STRING(retval) + length; ! self->zst.avail_out = length; ! length = length << 1; ! ! Py_BEGIN_ALLOW_THREADS ! err = inflate(&(self->zst), Z_FINISH); ! Py_END_ALLOW_THREADS ! } ! ! /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free ! various data structures. Note we should only get Z_STREAM_END when ! flushmode is Z_FINISH */ ! if (err == Z_STREAM_END) { ! err = inflateEnd(&(self->zst)); ! self->is_initialised = 0; ! if (err != Z_OK) { ! zlib_error(self->zst, err, "from inflateEnd()"); ! Py_DECREF(retval); ! retval = NULL; ! goto error; ! } } + _PyString_Resize(&retval, self->zst.total_out - start_total_out); + + error: LEAVE_ZLIB *************** *** 868,871 **** --- 899,904 ---- if (ver != NULL) PyModule_AddObject(m, "ZLIB_VERSION", ver); + + PyModule_AddStringConstant(m, "__version__", "1.0"); #ifdef WITH_THREAD From doerwalter@users.sourceforge.net Mon Feb 3 20:53:20 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 12:53:20 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.639,1.640 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv2191/Misc Modified Files: NEWS Log Message: Fix typo. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.639 retrieving revision 1.640 diff -C2 -d -r1.639 -r1.640 *** NEWS 3 Feb 2003 20:45:50 -0000 1.639 --- NEWS 3 Feb 2003 20:53:14 -0000 1.640 *************** *** 35,39 **** - Thanks to Scott David Daniels, a subtle bug in how the zlib ! extension implemented flush() was fixed. Scott also rewrite the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) --- 35,39 ---- - Thanks to Scott David Daniels, a subtle bug in how the zlib ! extension implemented flush() was fixed. Scott also rewrote the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) From montanaro@users.sourceforge.net Mon Feb 3 21:22:40 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 03 Feb 2003 13:22:40 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv README,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv18228 Modified Files: README Log Message: updated Index: README =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/README,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** README 29 Jan 2003 14:18:20 -0000 1.2 --- README 3 Feb 2003 21:22:37 -0000 1.3 *************** *** 1,6 **** ! This little corner of the sandbox aims to create a module to read and write ! CSV files. Involved parties are currently Kevin Altis, Dave Cole, Skip ! Montanaro, Cliff Wells and Andrew McNamara. ! Stay tuned... --- 1,25 ---- ! This little corner of the sandbox contains a fairly complete csv module ! based on PEP 305 and drawing heavily on the code in Object Craft's original ! csv module. If you'd like to try it out simply execute ! python setup.py install + There is a moderately accurate library reference manual section in + libcsv.tex, though you will have to read the raw source for the time being. + You may also find PEP 305 helpful. + + Please send feedback, including bug reports, to csv@mail.mojam.com. You can + browse the list archives at + + http://manatee.mojam.com/pipermail/csv/ + + and subscribe to the list at + + http://manatee.mojam.com/mailman/listinfo/csv + + + Kevin Altis + Dave Cole + Andrew McNamara + Skip Montanaro + Cliff Wells From tim_one@users.sourceforge.net Mon Feb 3 21:31:26 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 13:31:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.38,1.39 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22080/Lib/test Modified Files: pickletester.py Log Message: Do a better job of testing that opcodes aren't generated under protocols earlier than the ones in which they were introduced. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** pickletester.py 3 Feb 2003 16:20:13 -0000 1.38 --- pickletester.py 3 Feb 2003 21:31:22 -0000 1.39 *************** *** 255,263 **** pass ! def ensure_opcode_in_pickle(self, code, pickle): for op, dummy, dummy in pickletools.genops(pickle): if op.code == code: ! return ! self.fail("didn't find opcode %r in pickle %r" % (code, pickle)) def test_misc(self): --- 255,264 ---- pass ! # Return True if opcode code appears in the pickle, else False. ! def opcode_in_pickle(self, code, pickle): for op, dummy, dummy in pickletools.genops(pickle): if op.code == code: ! return True ! return False def test_misc(self): *************** *** 481,495 **** def test_long1(self): x = 12345678910111213141516178920L ! s = self.dumps(x, 2) ! y = self.loads(s) ! self.assertEqual(x, y) ! self.ensure_opcode_in_pickle(pickle.LONG1, s) def test_long4(self): x = 12345678910111213141516178920L << (256*8) ! s = self.dumps(x, 2) ! y = self.loads(s) ! self.assertEqual(x, y) ! self.ensure_opcode_in_pickle(pickle.LONG4, s) def test_short_tuples(self): --- 482,500 ---- def test_long1(self): x = 12345678910111213141516178920L ! for proto in protocols: ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(x, y) ! self.assertEqual(self.opcode_in_pickle(pickle.LONG1, s), ! proto >= 2) def test_long4(self): x = 12345678910111213141516178920L << (256*8) ! for proto in protocols: ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(x, y) ! self.assertEqual(self.opcode_in_pickle(pickle.LONG4, s), ! proto >= 2) def test_short_tuples(self): *************** *** 524,530 **** self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] ! self.ensure_opcode_in_pickle(expected, s) def test_singletons(self): for proto in protocols: for x in None, False, True: --- 529,548 ---- self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] ! self.assertEqual(self.opcode_in_pickle(expected, s), True) def test_singletons(self): + # Map (proto, singleton) to expected opcode. + expected_opcode = {(0, None): pickle.NONE, + (1, None): pickle.NONE, + (2, None): pickle.NONE, + + (0, True): pickle.INT, + (1, True): pickle.INT, + (2, True): pickle.NEWTRUE, + + (0, False): pickle.INT, + (1, False): pickle.INT, + (2, False): pickle.NEWFALSE, + } for proto in protocols: for x in None, False, True: *************** *** 532,541 **** y = self.loads(s) self.assert_(x is y, (proto, x, s, y)) ! ! # Test that proto >= 2 really uses the bool opcodes. ! if proto >= 2 and x in (False, True): ! expected = x and pickle.NEWTRUE or pickle.NEWFALSE ! # Skip the PROTO opcode at the start. ! self.assertEqual(s[2], expected) def test_newobj_tuple(self): --- 550,555 ---- y = self.loads(s) self.assert_(x is y, (proto, x, s, y)) ! expected = expected_opcode[proto, x] ! self.assertEqual(self.opcode_in_pickle(expected, s), True) def test_newobj_tuple(self): From tim_one@users.sourceforge.net Mon Feb 3 22:07:30 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 14:07:30 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.117,2.118 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv8214/Modules Modified Files: cPickle.c Log Message: load_counted_long(): Changed a ValueError to an UnpicklingError, just because it seems more consistent with the rest of the code. cPickle_PyMapping_HasKey(): This extern function isn't used anywhere in Python or Zope, so got rid of it. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.117 retrieving revision 2.118 diff -C2 -d -r2.117 -r2.118 *** cPickle.c 3 Feb 2003 15:45:56 -0000 2.117 --- cPickle.c 3 Feb 2003 22:07:24 -0000 2.118 *************** *** 361,378 **** static int put2(Picklerobject *, PyObject *); - int - cPickle_PyMapping_HasKey(PyObject *o, PyObject *key) - { - PyObject *v; - - if ((v = PyObject_GetItem(o,key))) { - Py_DECREF(v); - return 1; - } - - PyErr_Clear(); - return 0; - } - static PyObject * --- 361,364 ---- *************** *** 3023,3027 **** * this. */ ! PyErr_SetString(PyExc_ValueError, "LONG pickle has negative " "byte count"); return -1; --- 3009,3013 ---- * this. */ ! PyErr_SetString(UnpicklingError, "LONG pickle has negative " "byte count"); return -1; From tim_one@users.sourceforge.net Mon Feb 3 22:27:40 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 14:27:40 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv18134/Lib/test Modified Files: pickletester.py Log Message: Added a bit to the EXT[124] tests, and refactored them to squash code duplication. Note that these still don't get run under cPickle. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** pickletester.py 3 Feb 2003 21:31:22 -0000 1.39 --- pickletester.py 3 Feb 2003 22:27:38 -0000 1.40 *************** *** 10,13 **** --- 10,21 ---- protocols = range(3) + + # Return True if opcode code appears in the pickle, else False. + def opcode_in_pickle(code, pickle): + for op, dummy, dummy in pickletools.genops(pickle): + if op.code == code: + return True + return False + class C: def __cmp__(self, other): *************** *** 255,265 **** pass - # Return True if opcode code appears in the pickle, else False. - def opcode_in_pickle(self, code, pickle): - for op, dummy, dummy in pickletools.genops(pickle): - if op.code == code: - return True - return False - def test_misc(self): # test various datatypes not tested by testdata --- 263,266 ---- *************** *** 486,491 **** y = self.loads(s) self.assertEqual(x, y) ! self.assertEqual(self.opcode_in_pickle(pickle.LONG1, s), ! proto >= 2) def test_long4(self): --- 487,491 ---- y = self.loads(s) self.assertEqual(x, y) ! self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2) def test_long4(self): *************** *** 495,500 **** y = self.loads(s) self.assertEqual(x, y) ! self.assertEqual(self.opcode_in_pickle(pickle.LONG4, s), ! proto >= 2) def test_short_tuples(self): --- 495,499 ---- y = self.loads(s) self.assertEqual(x, y) ! self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2) def test_short_tuples(self): *************** *** 529,533 **** self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] ! self.assertEqual(self.opcode_in_pickle(expected, s), True) def test_singletons(self): --- 528,532 ---- self.assertEqual(x, y, (proto, x, s, y)) expected = expected_opcode[proto, len(x)] ! self.assertEqual(opcode_in_pickle(expected, s), True) def test_singletons(self): *************** *** 551,555 **** self.assert_(x is y, (proto, x, s, y)) expected = expected_opcode[proto, x] ! self.assertEqual(self.opcode_in_pickle(expected, s), True) def test_newobj_tuple(self): --- 550,554 ---- self.assert_(x is y, (proto, x, s, y)) expected = expected_opcode[proto, x] ! self.assertEqual(opcode_in_pickle(expected, s), True) def test_newobj_tuple(self): *************** *** 599,609 **** self.assertEqual(x.foo, y.foo) self.assertEqual(x.bar, y.bar) - ## import pickletools - ## print - ## pickletools.dis(s) ! def test_global_ext1(self): import copy_reg ! copy_reg.add_extension(__name__, "MyList", 0xf0) try: x = MyList([1, 2, 3]) --- 598,608 ---- self.assertEqual(x.foo, y.foo) self.assertEqual(x.bar, y.bar) ! # Register a type with copy_reg, with extension code extcode. Pickle ! # an object of that type. Check that the resulting pickle uses opcode ! # (EXT[124]) under proto 2, and not in proto 1. ! def produce_global_ext(self, extcode, opcode): import copy_reg ! copy_reg.add_extension(__name__, "MyList", extcode) try: x = MyList([1, 2, 3]) *************** *** 611,615 **** x.bar = "hello" ! # Dump using protocol 1 for comparison s1 = self.dumps(x, 1) y = self.loads(s1) --- 610,614 ---- x.bar = "hello" ! # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) y = self.loads(s1) *************** *** 618,626 **** self.assert_(s1.find(__name__) >= 0) self.assert_(s1.find("MyList") >= 0) - ## import pickletools - ## print - ## pickletools.dis(s1) ! # Dump using protocol 2 for test s2 = self.dumps(x, 2) self.assertEqual(s2.find(__name__), -1) --- 617,622 ---- self.assert_(s1.find(__name__) >= 0) self.assert_(s1.find("MyList") >= 0) ! # Dump using protocol 2 for test. s2 = self.dumps(x, 2) self.assertEqual(s2.find(__name__), -1) *************** *** 629,666 **** self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) ! ## import pickletools ! ## print ! ## pickletools.dis(s2) finally: ! copy_reg.remove_extension(__name__, "MyList", 0xf0) def test_global_ext2(self): ! import copy_reg ! copy_reg.add_extension(__name__, "MyList", 0xfff0) ! try: ! x = MyList() ! s2 = self.dumps(x, 2) ! self.assertEqual(s2.find(__name__), -1) ! self.assertEqual(s2.find("MyList"), -1) ! y = self.loads(s2) ! self.assertEqual(list(x), list(y)) ! self.assertEqual(x.__dict__, y.__dict__) ! finally: ! copy_reg.remove_extension(__name__, "MyList", 0xfff0) def test_global_ext4(self): ! import copy_reg ! copy_reg.add_extension(__name__, "MyList", 0xfffff0) ! try: ! x = MyList() ! s2 = self.dumps(x, 2) ! self.assertEqual(s2.find(__name__), -1) ! self.assertEqual(s2.find("MyList"), -1) ! y = self.loads(s2) ! self.assertEqual(list(x), list(y)) ! self.assertEqual(x.__dict__, y.__dict__) ! finally: ! copy_reg.remove_extension(__name__, "MyList", 0xfffff0) class MyInt(int): --- 625,642 ---- self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) ! self.assertEqual(opcode_in_pickle(opcode, s2), True) finally: ! copy_reg.remove_extension(__name__, "MyList", extcode) ! ! def test_global_ext1(self): ! self.produce_global_ext(0xf0, pickle.EXT1) def test_global_ext2(self): ! self.produce_global_ext(0xfff0, pickle.EXT2) def test_global_ext4(self): ! self.produce_global_ext(0xffffff0, pickle.EXT4) ! class MyInt(int): From tim_one@users.sourceforge.net Mon Feb 3 22:28:43 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 14:28:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.40,1.41 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv18846/Lib/test Modified Files: pickletester.py Log Message: test_newobj_generic(): Use the global protocols vector instead of a hardcoded list. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** pickletester.py 3 Feb 2003 22:27:38 -0000 1.40 --- pickletester.py 3 Feb 2003 22:28:41 -0000 1.41 *************** *** 571,575 **** def test_newobj_generic(self): ! for proto in [0, 1, 2]: for C in myclasses: B = C.__base__ --- 571,575 ---- def test_newobj_generic(self): ! for proto in protocols: for C in myclasses: B = C.__base__ From tim_one@users.sourceforge.net Mon Feb 3 22:32:20 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 14:32:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.41,1.42 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv20221/Lib/test Modified Files: pickletester.py Log Message: test_newobj_tuple(), test_newobj_list(): These tests should work under all protocols, so tried them under all. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** pickletester.py 3 Feb 2003 22:28:41 -0000 1.41 --- pickletester.py 3 Feb 2003 22:32:18 -0000 1.42 *************** *** 556,563 **** x.foo = 42 x.bar = "hello" ! s = self.dumps(x, 2) ! y = self.loads(s) ! self.assertEqual(tuple(x), tuple(y)) ! self.assertEqual(x.__dict__, y.__dict__) def test_newobj_list(self): --- 556,564 ---- x.foo = 42 x.bar = "hello" ! for proto in protocols: ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(tuple(x), tuple(y)) ! self.assertEqual(x.__dict__, y.__dict__) def test_newobj_list(self): *************** *** 565,572 **** x.foo = 42 x.bar = "hello" ! s = self.dumps(x, 2) ! y = self.loads(s) ! self.assertEqual(list(x), list(y)) ! self.assertEqual(x.__dict__, y.__dict__) def test_newobj_generic(self): --- 566,574 ---- x.foo = 42 x.bar = "hello" ! for proto in protocols: ! s = self.dumps(x, proto) ! y = self.loads(s) ! self.assertEqual(list(x), list(y)) ! self.assertEqual(x.__dict__, y.__dict__) def test_newobj_generic(self): From doerwalter@users.sourceforge.net Mon Feb 3 23:03:52 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 15:03:52 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_sys.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3087/Lib/test Added Files: test_sys.py Log Message: Add a new test script that tests various features of the sys module. This increases code coverage of Python/sysmodule.c from 68% to 77% (on Linux). The script doesn't exercise the error branch that handles an evil or lost sys.excepthook in Python/pythonrun.c::PyErr_PrintEx(). Also this script might not work on Jython in its current form. >From SF patch #662807. --- NEW FILE: test_sys.py --- # -*- coding: iso-8859-1 -*- import unittest, test.test_support import sys, cStringIO class SysModuleTest(unittest.TestCase): def test_original_displayhook(self): import __builtin__ savestdout = sys.stdout out = cStringIO.StringIO() sys.stdout = out dh = sys.__displayhook__ self.assertRaises(TypeError, dh) if hasattr(__builtin__, "_"): del __builtin__._ dh(None) self.assertEqual(out.getvalue(), "") self.assert_(not hasattr(__builtin__, "_")) dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqual(__builtin__._, 42) del sys.stdout self.assertRaises(RuntimeError, dh, 42) sys.stdout = savestdout def test_lost_displayhook(self): olddisplayhook = sys.displayhook del sys.displayhook code = compile("42", "", "single") self.assertRaises(RuntimeError, eval, code) sys.displayhook = olddisplayhook def test_custom_displayhook(self): olddisplayhook = sys.displayhook def baddisplayhook(obj): raise ValueError sys.displayhook = baddisplayhook code = compile("42", "", "single") self.assertRaises(ValueError, eval, code) sys.displayhook = olddisplayhook def test_original_excepthook(self): savestderr = sys.stderr err = cStringIO.StringIO() sys.stderr = err eh = sys.__excepthook__ self.assertRaises(TypeError, eh) try: raise ValueError(42) except ValueError, exc: eh(*sys.exc_info()) sys.stderr = savestderr self.assert_(err.getvalue().endswith("ValueError: 42\n")) # FIXME: testing the code for a lost or replace excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. def test_exit(self): self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument try: sys.exit(0) except SystemExit, exc: self.assertEquals(exc.code, 0) except: self.fail("wrong exception") else: self.fail("no exception") # call with tuple argument with one entry # entry will be unpacked try: sys.exit(42) except SystemExit, exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") else: self.fail("no exception") # call with integer argument try: sys.exit((42,)) except SystemExit, exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") else: self.fail("no exception") # call with string argument try: sys.exit("exit") except SystemExit, exc: self.assertEquals(exc.code, "exit") except: self.fail("wrong exception") else: self.fail("no exception") # call with tuple argument with two entries try: sys.exit((17, 23)) except SystemExit, exc: self.assertEquals(exc.code, (17, 23)) except: self.fail("wrong exception") else: self.fail("no exception") def test_getdefaultencoding(self): if test.test_support.have_unicode: self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it self.assert_(isinstance(sys.getdefaultencoding(), str)) # testing sys.settrace() is done in test_trace.py # testing sys.setprofile() is done in test_profile.py def test_setcheckinterval(self): self.assertRaises(TypeError, sys.setcheckinterval) sys.setcheckinterval(120) sys.setcheckinterval(100) def test_recursionlimit(self): self.assertRaises(TypeError, sys.getrecursionlimit, 42) oldlimit = sys.getrecursionlimit() self.assertRaises(TypeError, sys.setrecursionlimit) self.assertRaises(ValueError, sys.setrecursionlimit, -42) sys.setrecursionlimit(10000) self.assertEqual(sys.getrecursionlimit(), 10000) sys.setrecursionlimit(oldlimit) def test_getwindowsversion(self): if hasattr(sys, "getwindowsversion"): v = sys.getwindowsversion() self.assert_(isinstance(v, tuple)) self.assertEqual(len(v), 5) self.assert_(isinstance(v[0], int)) self.assert_(isinstance(v[1], int)) self.assert_(isinstance(v[2], int)) self.assert_(isinstance(v[3], int)) self.assert_(isinstance(v[4], str)) def test_dlopenflags(self): if hasattr(sys, "setdlopenflags"): self.assert_(hasattr(sys, "getdlopenflags")) self.assertRaises(TypeError, sys.getdlopenflags, 42) oldflags = sys.getdlopenflags() self.assertRaises(TypeError, sys.setdlopenflags) sys.setdlopenflags(oldflags+1) self.assertEqual(sys.getdlopenflags(), oldflags+1) sys.setdlopenflags(oldflags) def test_refcount(self): self.assertRaises(TypeError, sys.getrefcount) c = sys.getrefcount(None) n = None self.assertEqual(sys.getrefcount(None), c+1) del n self.assertEqual(sys.getrefcount(None), c) if hasattr(sys, "gettotalrefcount"): self.assert_(isinstance(sys.gettotalrefcount(), int)) def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) self.assertRaises(ValueError, sys._getframe, sys.maxint) self.assert_( SysModuleTest.test_getframe.im_func.func_code \ is sys._getframe().f_code ) def test_attributes(self): self.assert_(isinstance(sys.api_version, int)) self.assert_(isinstance(sys.argv, list)) self.assert_(sys.byteorder in ("little", "big")) self.assert_(isinstance(sys.builtin_module_names, tuple)) self.assert_(isinstance(sys.copyright, basestring)) self.assert_(isinstance(sys.exec_prefix, basestring)) self.assert_(isinstance(sys.executable, basestring)) self.assert_(isinstance(sys.hexversion, int)) self.assert_(isinstance(sys.maxint, int)) self.assert_(isinstance(sys.maxunicode, int)) self.assert_(isinstance(sys.platform, basestring)) self.assert_(isinstance(sys.prefix, basestring)) self.assert_(isinstance(sys.version, basestring)) vi = sys.version_info self.assert_(isinstance(vi, tuple)) self.assertEqual(len(vi), 5) self.assert_(isinstance(vi[0], int)) self.assert_(isinstance(vi[1], int)) self.assert_(isinstance(vi[2], int)) self.assert_(vi[3] in ("alpha", "beta", "candidate", "final")) self.assert_(isinstance(vi[4], int)) def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SysModuleTest)) test.test_support.run_suite(suite) if __name__ == "__main__": test_main() From doerwalter@users.sourceforge.net Mon Feb 3 23:05:30 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 03 Feb 2003 15:05:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_sys.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv4103/Lib/test Modified Files: test_sys.py Log Message: Fix typo. Index: test_sys.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sys.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_sys.py 3 Feb 2003 23:03:49 -0000 1.1 --- test_sys.py 3 Feb 2003 23:05:27 -0000 1.2 *************** *** 61,65 **** self.assert_(err.getvalue().endswith("ValueError: 42\n")) ! # FIXME: testing the code for a lost or replace excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. --- 61,65 ---- self.assert_(err.getvalue().endswith("ValueError: 42\n")) ! # FIXME: testing the code for a lost or replaced excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. From tim_one@users.sourceforge.net Tue Feb 4 00:21:10 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 16:21:10 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.118,2.119 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2555/Modules Modified Files: cPickle.c Log Message: Brought some module variables into synch with pickle.py's current values. Imported the extension-registry dicts from copy_reg.py, in preparation for tackling EXT[124]. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.118 retrieving revision 2.119 diff -C2 -d -r2.118 -r2.119 *** cPickle.c 3 Feb 2003 22:07:24 -0000 2.118 --- cPickle.c 4 Feb 2003 00:21:07 -0000 2.119 *************** *** 96,102 **** static PyObject *BadPickleGet; static PyObject *dispatch_table; ! static PyObject *empty_tuple; static PyObject *__class___str, *__getinitargs___str, *__dict___str, --- 96,112 ---- static PyObject *BadPickleGet; + /* As the name says, an empty tuple. */ + static PyObject *empty_tuple; + /* copy_reg.dispatch_table, {type_object: pickling_function} */ static PyObject *dispatch_table; ! ! /* For EXT[124] opcodes. */ ! /* copy_reg.extension_registry, {(module_name, function_name): code} */ ! static PyObject *extension_registry; ! /* copy_reg.inverted_registry, {code: (module_name, function_name)} */ ! static PyObject *inverted_registry; ! /* copy_reg.extension_cache, {code: object} */ ! static PyObject *extension_cache; static PyObject *__class___str, *__getinitargs___str, *__dict___str, *************** *** 2593,2605 **** if (PyEval_GetRestricted()) { /* Restricted execution, get private tables */ ! PyObject *m; ! if (!( m=PyImport_Import(copy_reg_str))) goto err; ! self->dispatch_table=PyObject_GetAttr(m, dispatch_table_str); Py_DECREF(m); ! if (!( self->dispatch_table )) goto err; } else { ! self->dispatch_table=dispatch_table; Py_INCREF(dispatch_table); } --- 2603,2617 ---- if (PyEval_GetRestricted()) { /* Restricted execution, get private tables */ ! PyObject *m = PyImport_Import(copy_reg_str); ! if (m == NULL) ! goto err; ! self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str); Py_DECREF(m); ! if (self->dispatch_table == NULL) ! goto err; } else { ! self->dispatch_table = dispatch_table; Py_INCREF(dispatch_table); } *************** *** 5078,5083 **** one in restricted mode. */ dispatch_table = PyObject_GetAttr(copy_reg, dispatch_table_str); ! if (!dispatch_table) ! return -1; Py_DECREF(copy_reg); --- 5090,5106 ---- one in restricted mode. */ dispatch_table = PyObject_GetAttr(copy_reg, dispatch_table_str); ! if (!dispatch_table) return -1; ! ! extension_registry = PyObject_GetAttrString(copy_reg, ! "extension_registry"); ! if (!extension_registry) return -1; ! ! inverted_registry = PyObject_GetAttrString(copy_reg, ! "inverted_registry"); ! if (!inverted_registry) return -1; ! ! extension_cache = PyObject_GetAttrString(copy_reg, ! "extension_cache"); ! if (!extension_cache) return -1; Py_DECREF(copy_reg); *************** *** 5169,5173 **** PyObject *m, *d, *di, *v, *k; int i; ! char *rev="1.71"; PyObject *format_version; PyObject *compatible_formats; --- 5192,5196 ---- PyObject *m, *d, *di, *v, *k; int i; ! char *rev = "1.71"; /* XXX when does this change? */ PyObject *format_version; PyObject *compatible_formats; *************** *** 5178,5184 **** /* Initialize some pieces. We need to do this before module creation, ! so we're forced to use a temporary dictionary. :( ! */ ! di=PyDict_New(); if (!di) return; if (init_stuff(di) < 0) return; --- 5201,5207 ---- /* Initialize some pieces. We need to do this before module creation, ! * so we're forced to use a temporary dictionary. :( ! */ ! di = PyDict_New(); if (!di) return; if (init_stuff(di) < 0) return; *************** *** 5191,5195 **** /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ! PyDict_SetItemString(d,"__version__", v = PyString_FromString(rev)); Py_XDECREF(v); --- 5214,5219 ---- /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ! v = PyString_FromString(rev); ! PyDict_SetItemString(d, "__version__", v); Py_XDECREF(v); *************** *** 5203,5209 **** Py_DECREF(di); ! format_version = PyString_FromString("1.3"); ! compatible_formats = Py_BuildValue("[sss]", "1.0", "1.1", "1.2"); ! PyDict_SetItemString(d, "format_version", format_version); PyDict_SetItemString(d, "compatible_formats", compatible_formats); --- 5227,5240 ---- Py_DECREF(di); ! /* These are purely informational; no code uses them. */ ! /* File format version we write. */ ! format_version = PyString_FromString("2.0"); ! /* Format versions we can read. */ ! compatible_formats = Py_BuildValue("[sssss]", ! "1.0", /* Original protocol 0 */ ! "1.1", /* Protocol 0 + INST */ ! "1.2", /* Original protocol 1 */ ! "1.3", /* Protocol 1 + BINFLOAT */ ! "2.0"); /* Oritinal potocol 2 */ PyDict_SetItemString(d, "format_version", format_version); PyDict_SetItemString(d, "compatible_formats", compatible_formats); From tim_one@users.sourceforge.net Tue Feb 4 00:21:09 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 16:21:09 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv2555/Lib Modified Files: copy_reg.py Log Message: Brought some module variables into synch with pickle.py's current values. Imported the extension-registry dicts from copy_reg.py, in preparation for tackling EXT[124]. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** copy_reg.py 1 Feb 2003 02:16:36 -0000 1.13 --- copy_reg.py 4 Feb 2003 00:21:06 -0000 1.14 *************** *** 82,85 **** --- 82,87 ---- inverted_registry = {} # code -> key extension_cache = {} # code -> object + # Don't ever rebind those names: cPickle grabs a reference to them when + # it's initialized, and won't see a rebinding. def add_extension(module, name, code): From tim_one@users.sourceforge.net Tue Feb 4 00:30:49 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 16:30:49 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.119,2.120 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv6800/Modules Modified Files: cPickle.c Log Message: Typo repair. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.119 retrieving revision 2.120 diff -C2 -d -r2.119 -r2.120 *** cPickle.c 4 Feb 2003 00:21:07 -0000 2.119 --- cPickle.c 4 Feb 2003 00:30:46 -0000 2.120 *************** *** 5236,5240 **** "1.2", /* Original protocol 1 */ "1.3", /* Protocol 1 + BINFLOAT */ ! "2.0"); /* Oritinal potocol 2 */ PyDict_SetItemString(d, "format_version", format_version); PyDict_SetItemString(d, "compatible_formats", compatible_formats); --- 5236,5240 ---- "1.2", /* Original protocol 1 */ "1.3", /* Protocol 1 + BINFLOAT */ ! "2.0"); /* Original protocol 2 */ PyDict_SetItemString(d, "format_version", format_version); PyDict_SetItemString(d, "compatible_formats", compatible_formats); From tim_one@users.sourceforge.net Tue Feb 4 00:38:24 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 16:38:24 -0800 Subject: [Python-checkins] python/dist/src/Lib sets.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv9494/Lib Modified Files: sets.py Log Message: Whitespace normalization. Index: sets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sets.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** sets.py 2 Feb 2003 16:07:53 -0000 1.39 --- sets.py 4 Feb 2003 00:38:20 -0000 1.40 *************** *** 271,275 **** return False for elt in ifilter(self._data.has_key, other, True): ! return False return True --- 271,275 ---- return False for elt in ifilter(self._data.has_key, other, True): ! return False return True From gvanrossum@users.sourceforge.net Tue Feb 4 01:54:51 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 17:54:51 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.143,1.144 copy_reg.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv3141/Lib Modified Files: pickle.py copy_reg.py Log Message: Rename the extension registry variables to have leading underscores -- this clarifies that they are part of an internal API (albeit shared between pickle.py, copy_reg.py and cPickle.c). I'd like to do the same for copy_reg.dispatch_table, but worry that it might be used by existing code. This risk doesn't exist for the extension registry. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.143 retrieving revision 1.144 diff -C2 -d -r1.143 -r1.144 *** pickle.py 3 Feb 2003 19:46:54 -0000 1.143 --- pickle.py 4 Feb 2003 01:54:48 -0000 1.144 *************** *** 29,33 **** from types import * from copy_reg import dispatch_table, _reconstructor ! from copy_reg import extension_registry, inverted_registry, extension_cache import marshal import sys --- 29,33 ---- from types import * from copy_reg import dispatch_table, _reconstructor ! from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal import sys *************** *** 846,850 **** if self.proto >= 2: ! code = extension_registry.get((module, name)) if code: assert code > 0 --- 846,850 ---- if self.proto >= 2: ! code = _extension_registry.get((module, name)) if code: assert code > 0 *************** *** 1239,1251 **** def get_extension(self, code): nil = [] ! obj = extension_cache.get(code, nil) if obj is not nil: self.append(obj) return ! key = inverted_registry.get(code) if not key: raise ValueError("unregistered extension code %d" % code) obj = self.find_class(*key) ! extension_cache[code] = obj self.append(obj) --- 1239,1251 ---- def get_extension(self, code): nil = [] ! obj = _extension_cache.get(code, nil) if obj is not nil: self.append(obj) return ! key = _inverted_registry.get(code) if not key: raise ValueError("unregistered extension code %d" % code) obj = self.find_class(*key) ! _extension_cache[code] = obj self.append(obj) Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** copy_reg.py 4 Feb 2003 00:21:06 -0000 1.14 --- copy_reg.py 4 Feb 2003 01:54:49 -0000 1.15 *************** *** 79,85 **** # reserved. ! extension_registry = {} # key -> code ! inverted_registry = {} # code -> key ! extension_cache = {} # code -> object # Don't ever rebind those names: cPickle grabs a reference to them when # it's initialized, and won't see a rebinding. --- 79,85 ---- # reserved. ! _extension_registry = {} # key -> code ! _inverted_registry = {} # code -> key ! _extension_cache = {} # code -> object # Don't ever rebind those names: cPickle grabs a reference to them when # it's initialized, and won't see a rebinding. *************** *** 91,120 **** raise ValueError, "code out of range" key = (module, name) ! if (extension_registry.get(key) == code and ! inverted_registry.get(code) == key): return # Redundant registrations are benign ! if key in extension_registry: raise ValueError("key %s is already registered with code %s" % ! (key, extension_registry[key])) ! if code in inverted_registry: raise ValueError("code %s is already in use for key %s" % ! (code, inverted_registry[code])) ! extension_registry[key] = code ! inverted_registry[code] = key def remove_extension(module, name, code): """Unregister an extension code. For testing only.""" key = (module, name) ! if (extension_registry.get(key) != code or ! inverted_registry.get(code) != key): raise ValueError("key %s is not registered with code %s" % (key, code)) ! del extension_registry[key] ! del inverted_registry[code] ! if code in extension_cache: ! del extension_cache[code] def clear_extension_cache(): ! extension_cache.clear() # Standard extension code assignments --- 91,120 ---- raise ValueError, "code out of range" key = (module, name) ! if (_extension_registry.get(key) == code and ! _inverted_registry.get(code) == key): return # Redundant registrations are benign ! if key in _extension_registry: raise ValueError("key %s is already registered with code %s" % ! (key, _extension_registry[key])) ! if code in _inverted_registry: raise ValueError("code %s is already in use for key %s" % ! (code, _inverted_registry[code])) ! _extension_registry[key] = code ! _inverted_registry[code] = key def remove_extension(module, name, code): """Unregister an extension code. For testing only.""" key = (module, name) ! if (_extension_registry.get(key) != code or ! _inverted_registry.get(code) != key): raise ValueError("key %s is not registered with code %s" % (key, code)) ! del _extension_registry[key] ! del _inverted_registry[code] ! if code in _extension_cache: ! del _extension_cache[code] def clear_extension_cache(): ! _extension_cache.clear() # Standard extension code assignments From gvanrossum@users.sourceforge.net Tue Feb 4 01:54:52 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 03 Feb 2003 17:54:52 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.120,2.121 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv3141/Modules Modified Files: cPickle.c Log Message: Rename the extension registry variables to have leading underscores -- this clarifies that they are part of an internal API (albeit shared between pickle.py, copy_reg.py and cPickle.c). I'd like to do the same for copy_reg.dispatch_table, but worry that it might be used by existing code. This risk doesn't exist for the extension registry. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.120 retrieving revision 2.121 diff -C2 -d -r2.120 -r2.121 *** cPickle.c 4 Feb 2003 00:30:46 -0000 2.120 --- cPickle.c 4 Feb 2003 01:54:49 -0000 2.121 *************** *** 103,111 **** /* For EXT[124] opcodes. */ ! /* copy_reg.extension_registry, {(module_name, function_name): code} */ static PyObject *extension_registry; ! /* copy_reg.inverted_registry, {code: (module_name, function_name)} */ static PyObject *inverted_registry; ! /* copy_reg.extension_cache, {code: object} */ static PyObject *extension_cache; --- 103,111 ---- /* For EXT[124] opcodes. */ ! /* copy_reg._extension_registry, {(module_name, function_name): code} */ static PyObject *extension_registry; ! /* copy_reg._inverted_registry, {code: (module_name, function_name)} */ static PyObject *inverted_registry; ! /* copy_reg._extension_cache, {code: object} */ static PyObject *extension_cache; *************** *** 5093,5105 **** extension_registry = PyObject_GetAttrString(copy_reg, ! "extension_registry"); if (!extension_registry) return -1; inverted_registry = PyObject_GetAttrString(copy_reg, ! "inverted_registry"); if (!inverted_registry) return -1; extension_cache = PyObject_GetAttrString(copy_reg, ! "extension_cache"); if (!extension_cache) return -1; --- 5093,5105 ---- extension_registry = PyObject_GetAttrString(copy_reg, ! "_extension_registry"); if (!extension_registry) return -1; inverted_registry = PyObject_GetAttrString(copy_reg, ! "_inverted_registry"); if (!inverted_registry) return -1; extension_cache = PyObject_GetAttrString(copy_reg, ! "_extension_cache"); if (!extension_cache) return -1; From tim@zope.com Tue Feb 4 02:16:15 2003 From: tim@zope.com (Tim Peters) Date: Mon, 3 Feb 2003 21:16:15 -0500 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.143,1.144 copy_reg.py,1.14,1.15 In-Reply-To: Message-ID: > Rename the extension registry variables to have leading underscores -- > this clarifies that they are part of an internal API (albeit shared > between pickle.py, copy_reg.py and cPickle.c). Good idea! > I'd like to do the same for copy_reg.dispatch_table, but worry that it > might be used by existing code. Zope3's src/zodb/code/patch.py imports dispatch_table (as well as being the only known caller of pickle.Pickler.save_empty_tuple()). We should quiz Jeremy about why he needs to cheat so badly here <0.5 wink>. From tim_one@users.sourceforge.net Tue Feb 4 05:06:19 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 21:06:19 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv29814/Lib Modified Files: copy_reg.py Log Message: cPickle can load pickles using proto 2 EXT[124] now, but can't yet generate these opcodes. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** copy_reg.py 4 Feb 2003 01:54:49 -0000 1.15 --- copy_reg.py 4 Feb 2003 05:06:17 -0000 1.16 *************** *** 88,92 **** """Register an extension code.""" code = int(code) ! if not 1 <= code < 0x7fffffff: raise ValueError, "code out of range" key = (module, name) --- 88,92 ---- """Register an extension code.""" code = int(code) ! if not 1 <= code <= 0x7fffffff: raise ValueError, "code out of range" key = (module, name) From tim_one@users.sourceforge.net Tue Feb 4 05:06:20 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 21:06:20 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.121,2.122 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29814/Modules Modified Files: cPickle.c Log Message: cPickle can load pickles using proto 2 EXT[124] now, but can't yet generate these opcodes. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.121 retrieving revision 2.122 diff -C2 -d -r2.121 -r2.122 *** cPickle.c 4 Feb 2003 01:54:49 -0000 2.121 --- cPickle.c 4 Feb 2003 05:06:17 -0000 2.122 *************** *** 3734,3737 **** --- 3734,3805 ---- } + /* Push an object from the extension registry (EXT[124]). nbytes is + * the number of bytes following the opcode, holding the index (code) value. + */ + static int + load_extension(Unpicklerobject *self, int nbytes) + { + char *codebytes; /* the nbytes bytes after the opcode */ + long code; /* calc_binint returns long */ + PyObject *py_code; /* code as a Python int */ + PyObject *obj; /* the object to push */ + PyObject *pair; /* (module_name, class_name) */ + PyObject *module_name, *class_name; + + assert(nbytes == 1 || nbytes == 2 || nbytes == 4); + if (self->read_func(self, &codebytes, nbytes) < 0) return -1; + code = calc_binint(codebytes, nbytes); + if (code <= 0) { /* note that 0 is forbidden */ + /* Corrupt or hostile pickle. */ + PyErr_SetString(UnpicklingError, "EXT specifies code <= 0"); + return -1; + } + + /* Look for the code in the cache. */ + py_code = PyInt_FromLong(code); + if (py_code == NULL) return -1; + obj = PyDict_GetItem(extension_cache, py_code); + if (obj != NULL) { + /* Bingo. */ + Py_DECREF(py_code); + PDATA_APPEND(self->stack, obj, -1); + return 0; + } + + /* Look up the (module_name, class_name) pair. */ + pair = PyDict_GetItem(inverted_registry, py_code); + if (pair == NULL) { + Py_DECREF(py_code); + PyErr_Format(PyExc_ValueError, "unregistered extension " + "code %ld", code); + return -1; + } + /* Since the extension registry is manipulable via Python code, + * confirm that obj is really a 2-tuple of strings. + */ + if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 || + !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) || + !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) { + Py_DECREF(py_code); + PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] " + "isn't a 2-tuple of strings", code); + return -1; + } + /* Load the object. */ + obj = find_class(module_name, class_name, self->find_class); + if (obj == NULL) { + Py_DECREF(py_code); + return -1; + } + /* Cache code -> obj. */ + code = PyDict_SetItem(extension_cache, py_code, obj); + Py_DECREF(py_code); + if (code < 0) { + Py_DECREF(obj); + return -1; + } + PDATA_PUSH(self->stack, obj, -1); + return 0; + } static int *************** *** 4215,4218 **** --- 4283,4300 ---- continue; + case EXT1: + if (load_extension(self, 1) < 0) + break; + continue; + + case EXT2: + if (load_extension(self, 2) < 0) + break; + continue; + + case EXT4: + if (load_extension(self, 4) < 0) + break; + continue; case MARK: if (load_mark(self) < 0) *************** *** 4371,4374 **** --- 4453,4467 ---- } + static int + noload_extension(Unpicklerobject *self, int nbytes) + { + char *codebytes; + + assert(nbytes == 1 || nbytes == 2 || nbytes == 4); + if (self->read_func(self, &codebytes, nbytes) < 0) return -1; + PDATA_APPEND(self->stack, Py_None, -1); + return 0; + } + static PyObject * *************** *** 4555,4558 **** --- 4648,4666 ---- case GET: if (load_get(self) < 0) + break; + continue; + + case EXT1: + if (noload_extension(self, 1) < 0) + break; + continue; + + case EXT2: + if (noload_extension(self, 2) < 0) + break; + continue; + + case EXT4: + if (noload_extension(self, 4) < 0) break; continue; From tim_one@users.sourceforge.net Tue Feb 4 05:20:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 03 Feb 2003 21:20:34 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.122,2.123 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2303/Modules Modified Files: cPickle.c Log Message: Typo in comment. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.122 retrieving revision 2.123 diff -C2 -d -r2.122 -r2.123 *** cPickle.c 4 Feb 2003 05:06:17 -0000 2.122 --- cPickle.c 4 Feb 2003 05:20:32 -0000 2.123 *************** *** 3776,3780 **** } /* Since the extension registry is manipulable via Python code, ! * confirm that obj is really a 2-tuple of strings. */ if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 || --- 3776,3780 ---- } /* Since the extension registry is manipulable via Python code, ! * confirm that pair is really a 2-tuple of strings. */ if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 || From rhettinger@users.sourceforge.net Tue Feb 4 05:47:33 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Mon, 03 Feb 2003 21:47:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_random.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv11766 Modified Files: test_random.py Log Message: Add refcount test. Index: test_random.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_random.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** test_random.py 17 Jan 2003 17:23:23 -0000 1.7 --- test_random.py 4 Feb 2003 05:47:30 -0000 1.8 *************** *** 75,79 **** trials = 10000 # large num prevents false negatives without slowing normal case def factorial(n): ! return n==0 and 1 or n * factorial(n-1) for k in xrange(n): expected = factorial(n) / factorial(n-k) --- 75,79 ---- trials = 10000 # large num prevents false negatives without slowing normal case def factorial(n): ! return reduce(int.__mul__, xrange(1, n), 1) for k in xrange(n): expected = factorial(n) / factorial(n-k) *************** *** 272,276 **** self.failUnless(Set(random.__all__) <= Set(dir(random))) ! def test_main(): suite = unittest.TestSuite() for testclass in (WichmannHill_TestBasicOps, --- 272,276 ---- self.failUnless(Set(random.__all__) <= Set(dir(random))) ! def test_main(verbose=None): suite = unittest.TestSuite() for testclass in (WichmannHill_TestBasicOps, *************** *** 281,284 **** test_support.run_suite(suite) if __name__ == "__main__": ! test_main() --- 281,293 ---- test_support.run_suite(suite) + # verify reference counting + import sys + if verbose and hasattr(sys, "gettotalrefcount"): + counts = [] + for i in xrange(5): + test_support.run_suite(suite) + counts.append(sys.gettotalrefcount()-i) + print counts + if __name__ == "__main__": ! test_main(verbose=True) From gvanrossum@users.sourceforge.net Tue Feb 4 14:50:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 04 Feb 2003 06:50:26 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv13853 Modified Files: pep-0307.txt Log Message: Fix crucial typo found by Niki Spahiev. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** pep-0307.txt 3 Feb 2003 20:22:23 -0000 1.7 --- pep-0307.txt 4 Feb 2003 14:50:23 -0000 1.8 *************** *** 262,266 **** When __reduce__ exists, __getstate__ is not called (unless your ! __reduce__ implementation calls it), but __getstate__ will be called with the third item from the tuple returned by __reduce__, if not None. --- 262,266 ---- When __reduce__ exists, __getstate__ is not called (unless your ! __reduce__ implementation calls it), but __setstate__ will be called with the third item from the tuple returned by __reduce__, if not None. From montanaro@users.sourceforge.net Tue Feb 4 14:54:56 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 06:54:56 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv16326 Modified Files: _csv.c Log Message: memory allocated with PyMem_Malloc needs to be freed with PyMem_Free Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _csv.c 3 Feb 2003 02:43:08 -0000 1.12 --- _csv.c 4 Feb 2003 14:54:54 -0000 1.13 *************** *** 517,521 **** self->rec = PyMem_Realloc(self->rec, self->rec_size); if (self->rec == NULL) ! free(old_rec); } if (self->rec == NULL) { --- 517,521 ---- self->rec = PyMem_Realloc(self->rec, self->rec_size); if (self->rec == NULL) ! PyMem_Free(old_rec); } if (self->rec == NULL) { *************** *** 645,654 **** { if (self->field) ! free(self->field); Py_XDECREF(self->fields); Py_XDECREF(self->lineterminator); if (self->rec) ! free(self->rec); PyMem_DEL(self); --- 645,654 ---- { if (self->field) ! PyMem_Free(self->field); Py_XDECREF(self->fields); Py_XDECREF(self->lineterminator); if (self->rec) ! PyMem_Free(self->rec); PyMem_DEL(self); From fdrake@users.sourceforge.net Tue Feb 4 15:01:40 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 04 Feb 2003 07:01:40 -0800 Subject: [Python-checkins] python/dist/src/Doc/perl python.perl,1.132,1.133 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/perl In directory sc8-pr-cvs1:/tmp/cvs-serv20576 Modified Files: python.perl Log Message: Twiddle. Index: python.perl =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/perl/python.perl,v retrieving revision 1.132 retrieving revision 1.133 diff -C2 -d -r1.132 -r1.133 *** python.perl 15 Nov 2002 19:04:10 -0000 1.132 --- python.perl 4 Feb 2003 15:01:37 -0000 1.133 *************** *** 102,106 **** sub do_cmd_ABC{ 'ABC' . $_[0]; } ! sub do_cmd_UNIX{ 'Unix'. $_[0]; } sub do_cmd_ASCII{ 'ASCII' . $_[0]; } sub do_cmd_POSIX{ 'POSIX' . $_[0]; } --- 102,107 ---- sub do_cmd_ABC{ 'ABC' . $_[0]; } ! sub do_cmd_UNIX{ 'Unix' ! . $_[0]; } sub do_cmd_ASCII{ 'ASCII' . $_[0]; } sub do_cmd_POSIX{ 'POSIX' . $_[0]; } From fdrake@users.sourceforge.net Tue Feb 4 15:12:09 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 04 Feb 2003 07:12:09 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libtime.tex,1.54,1.55 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv27179 Modified Files: libtime.tex Log Message: Update to better reflect the usage of struct_time instances throughout; continuing to call these "time tuples" is misleading at best. Closes SF bug #671731; will backport to 2.2.x. Index: libtime.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libtime.tex,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** libtime.tex 31 Dec 2002 04:41:38 -0000 1.54 --- libtime.tex 4 Feb 2003 15:12:06 -0000 1.55 *************** *** 30,39 **** depends on the platform's C library, which generally doesn't have year 2000 issues, since all dates and times are represented internally as ! seconds since the epoch. Functions accepting a time tuple (see below) ! generally require a 4-digit year. For backward compatibility, 2-digit ! years are supported if the module variable \code{accept2dyear} is a ! non-zero integer; this variable is initialized to \code{1} unless the ! environment variable \envvar{PYTHONY2K} is set to a non-empty string, ! in which case it is initialized to \code{0}. Thus, you can set \envvar{PYTHONY2K} to a non-empty string in the environment to require 4-digit years for all year input. When 2-digit years are accepted, they are --- 30,40 ---- depends on the platform's C library, which generally doesn't have year 2000 issues, since all dates and times are represented internally as ! seconds since the epoch. Functions accepting a \class{struct_time} ! (see below) generally require a 4-digit year. For backward ! compatibility, 2-digit years are supported if the module variable ! \code{accept2dyear} is a non-zero integer; this variable is ! initialized to \code{1} unless the environment variable ! \envvar{PYTHONY2K} is set to a non-empty string, in which case it is ! initialized to \code{0}. Thus, you can set \envvar{PYTHONY2K} to a non-empty string in the environment to require 4-digit years for all year input. When 2-digit years are accepted, they are *************** *** 100,108 **** When a tuple with an incorrect length is passed to a function ! expecting a time tuple, or having elements of the wrong type, a \exception{TypeError} is raised. \versionchanged[The time value sequence was changed from a tuple to a ! specialized type, with the addition of attribute names for the fields]{2.2} \end{itemize} --- 101,109 ---- When a tuple with an incorrect length is passed to a function ! expecting a \class{struct_time}, or having elements of the wrong type, a \exception{TypeError} is raised. \versionchanged[The time value sequence was changed from a tuple to a ! \class{struct_time}, with the addition of attribute names for the fields]{2.2} \end{itemize} *************** *** 125,137 **** \end{datadesc} ! \begin{funcdesc}{asctime}{\optional{tuple}} ! Convert a tuple representing a time as returned by \function{gmtime()} or \function{localtime()} to a 24-character string of the following form: ! \code{'Sun Jun 20 23:21:05 1993'}. If \var{tuple} is not provided, the current time as returned by \function{localtime()} is used. Locale information is not used by \function{asctime()}. \note{Unlike the C function of the same name, there is no trailing newline.} ! \versionchanged[Allowed \var{tuple} to be omitted]{2.1} \end{funcdesc} --- 126,139 ---- \end{datadesc} ! \begin{funcdesc}{asctime}{\optional{t}} ! Convert a tuple or \class{struct_time} representing a time as returned ! by \function{gmtime()} or \function{localtime()} to a 24-character string of the following form: ! \code{'Sun Jun 20 23:21:05 1993'}. If \var{t} is not provided, the current time as returned by \function{localtime()} is used. Locale information is not used by \function{asctime()}. \note{Unlike the C function of the same name, there is no trailing newline.} ! \versionchanged[Allowed \var{t} to be omitted]{2.1} \end{funcdesc} *************** *** 165,173 **** \begin{funcdesc}{gmtime}{\optional{secs}} ! Convert a time expressed in seconds since the epoch to a time tuple in UTC in which the dst flag is always zero. If \var{secs} is not provided, the current time as returned by \function{time()} is used. Fractions of a second are ignored. See above for a description of the ! tuple lay-out. \versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} --- 167,175 ---- \begin{funcdesc}{gmtime}{\optional{secs}} ! Convert a time expressed in seconds since the epoch to a \class{struct_time} in UTC in which the dst flag is always zero. If \var{secs} is not provided, the current time as returned by \function{time()} is used. Fractions of a second are ignored. See above for a description of the ! \class{struct_time} object. \versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} *************** *** 179,186 **** \end{funcdesc} ! \begin{funcdesc}{mktime}{tuple} This is the inverse function of \function{localtime()}. Its argument ! is the full 9-tuple (since the dst flag is needed; use \code{-1} as ! the dst flag if it is unknown) which expresses the time in \emph{local} time, not UTC. It returns a floating point number, for compatibility with \function{time()}. If the input value cannot be --- 181,189 ---- \end{funcdesc} ! \begin{funcdesc}{mktime}{t} This is the inverse function of \function{localtime()}. Its argument ! is the \class{struct_time} or full 9-tuple (since the dst flag is ! needed; use \code{-1} as the dst flag if it is unknown) which ! expresses the time in \emph{local} time, not UTC. It returns a floating point number, for compatibility with \function{time()}. If the input value cannot be *************** *** 201,210 **** \end{funcdesc} ! \begin{funcdesc}{strftime}{format\optional{, tuple}} ! Convert a tuple representing a time as returned by \function{gmtime()} ! or \function{localtime()} to a string as specified by the \var{format} ! argument. If \var{tuple} is not provided, the current time as returned by ! \function{localtime()} is used. \var{format} must be a string. ! \versionchanged[Allowed \var{tuple} to be omitted]{2.1} The following directives can be embedded in the \var{format} string. --- 204,214 ---- \end{funcdesc} ! \begin{funcdesc}{strftime}{format\optional{, t}} ! Convert a tuple or \class{struct_time} representing a time as returned ! by \function{gmtime()} or \function{localtime()} to a string as ! specified by the \var{format} argument. If \var{t} is not ! provided, the current time as returned by \function{localtime()} is ! used. \var{format} must be a string. ! \versionchanged[Allowed \var{t} to be omitted]{2.1} The following directives can be embedded in the \var{format} string. *************** *** 278,282 **** \begin{funcdesc}{strptime}{string\optional{, format}} Parse a string representing a time according to a format. The return ! value is a tuple as returned by \function{gmtime()} or \function{localtime()}. The \var{format} parameter uses the same directives as those used by \function{strftime()}; it defaults to --- 282,286 ---- \begin{funcdesc}{strptime}{string\optional{, format}} Parse a string representing a time according to a format. The return ! value is a \class{struct_time} as returned by \function{gmtime()} or \function{localtime()}. The \var{format} parameter uses the same directives as those used by \function{strftime()}; it defaults to From fdrake@users.sourceforge.net Tue Feb 4 15:13:27 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 04 Feb 2003 07:13:27 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libtime.tex,1.48.6.3,1.48.6.4 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv27806 Modified Files: Tag: release22-maint libtime.tex Log Message: Update to better reflect the usage of struct_time instances throughout; continuing to call these "time tuples" is misleading at best. Closes SF bug #671731; backported from rev 1.55. Index: libtime.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libtime.tex,v retrieving revision 1.48.6.3 retrieving revision 1.48.6.4 diff -C2 -d -r1.48.6.3 -r1.48.6.4 *** libtime.tex 15 Nov 2002 23:01:37 -0000 1.48.6.3 --- libtime.tex 4 Feb 2003 15:13:25 -0000 1.48.6.4 *************** *** 30,39 **** depends on the platform's C library, which generally doesn't have year 2000 issues, since all dates and times are represented internally as ! seconds since the epoch. Functions accepting a time tuple (see below) ! generally require a 4-digit year. For backward compatibility, 2-digit ! years are supported if the module variable \code{accept2dyear} is a ! non-zero integer; this variable is initialized to \code{1} unless the ! environment variable \envvar{PYTHONY2K} is set to a non-empty string, ! in which case it is initialized to \code{0}. Thus, you can set \envvar{PYTHONY2K} to a non-empty string in the environment to require 4-digit years for all year input. When 2-digit years are accepted, they are --- 30,40 ---- depends on the platform's C library, which generally doesn't have year 2000 issues, since all dates and times are represented internally as ! seconds since the epoch. Functions accepting a \class{struct_time} ! (see below) generally require a 4-digit year. For backward ! compatibility, 2-digit years are supported if the module variable ! \code{accept2dyear} is a non-zero integer; this variable is ! initialized to \code{1} unless the environment variable ! \envvar{PYTHONY2K} is set to a non-empty string, in which case it is ! initialized to \code{0}. Thus, you can set \envvar{PYTHONY2K} to a non-empty string in the environment to require 4-digit years for all year input. When 2-digit years are accepted, they are *************** *** 100,108 **** When a tuple with an incorrect length is passed to a function ! expecting a time tuple, or having elements of the wrong type, a \exception{TypeError} is raised. \versionchanged[The time value sequence was changed from a tuple to a ! specialized type, with the addition of attribute names for the fields]{2.2} \end{itemize} --- 101,109 ---- When a tuple with an incorrect length is passed to a function ! expecting a \class{struct_time}, or having elements of the wrong type, a \exception{TypeError} is raised. \versionchanged[The time value sequence was changed from a tuple to a ! \class{struct_time}, with the addition of attribute names for the fields]{2.2} \end{itemize} *************** *** 125,137 **** \end{datadesc} ! \begin{funcdesc}{asctime}{\optional{tuple}} ! Convert a tuple representing a time as returned by \function{gmtime()} or \function{localtime()} to a 24-character string of the following form: ! \code{'Sun Jun 20 23:21:05 1993'}. If \var{tuple} is not provided, the current time as returned by \function{localtime()} is used. Locale information is not used by \function{asctime()}. \note{Unlike the C function of the same name, there is no trailing newline.} ! \versionchanged[Allowed \var{tuple} to be omitted]{2.1} \end{funcdesc} --- 126,139 ---- \end{datadesc} ! \begin{funcdesc}{asctime}{\optional{t}} ! Convert a tuple or \class{struct_time} representing a time as returned ! by \function{gmtime()} or \function{localtime()} to a 24-character string of the following form: ! \code{'Sun Jun 20 23:21:05 1993'}. If \var{t} is not provided, the current time as returned by \function{localtime()} is used. Locale information is not used by \function{asctime()}. \note{Unlike the C function of the same name, there is no trailing newline.} ! \versionchanged[Allowed \var{t} to be omitted]{2.1} \end{funcdesc} *************** *** 165,173 **** \begin{funcdesc}{gmtime}{\optional{secs}} ! Convert a time expressed in seconds since the epoch to a time tuple in UTC in which the dst flag is always zero. If \var{secs} is not provided, the current time as returned by \function{time()} is used. Fractions of a second are ignored. See above for a description of the ! tuple lay-out. \versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} --- 167,175 ---- \begin{funcdesc}{gmtime}{\optional{secs}} ! Convert a time expressed in seconds since the epoch to a \class{struct_time} in UTC in which the dst flag is always zero. If \var{secs} is not provided, the current time as returned by \function{time()} is used. Fractions of a second are ignored. See above for a description of the ! \class{struct_time} object. \versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} *************** *** 179,186 **** \end{funcdesc} ! \begin{funcdesc}{mktime}{tuple} This is the inverse function of \function{localtime()}. Its argument ! is the full 9-tuple (since the dst flag is needed; use \code{-1} as ! the dst flag if it is unknown) which expresses the time in \emph{local} time, not UTC. It returns a floating point number, for compatibility with \function{time()}. If the input value cannot be --- 181,189 ---- \end{funcdesc} ! \begin{funcdesc}{mktime}{t} This is the inverse function of \function{localtime()}. Its argument ! is the \class{struct_time} or full 9-tuple (since the dst flag is ! needed; use \code{-1} as the dst flag if it is unknown) which ! expresses the time in \emph{local} time, not UTC. It returns a floating point number, for compatibility with \function{time()}. If the input value cannot be *************** *** 201,210 **** \end{funcdesc} ! \begin{funcdesc}{strftime}{format\optional{, tuple}} ! Convert a tuple representing a time as returned by \function{gmtime()} ! or \function{localtime()} to a string as specified by the \var{format} ! argument. If \var{tuple} is not provided, the current time as returned by ! \function{localtime()} is used. \var{format} must be a string. ! \versionchanged[Allowed \var{tuple} to be omitted]{2.1} The following directives can be embedded in the \var{format} string. --- 204,214 ---- \end{funcdesc} ! \begin{funcdesc}{strftime}{format\optional{, t}} ! Convert a tuple or \class{struct_time} representing a time as returned ! by \function{gmtime()} or \function{localtime()} to a string as ! specified by the \var{format} argument. If \var{t} is not ! provided, the current time as returned by \function{localtime()} is ! used. \var{format} must be a string. ! \versionchanged[Allowed \var{t} to be omitted]{2.1} The following directives can be embedded in the \var{format} string. *************** *** 278,282 **** \begin{funcdesc}{strptime}{string\optional{, format}} Parse a string representing a time according to a format. The return ! value is a tuple as returned by \function{gmtime()} or \function{localtime()}. The \var{format} parameter uses the same directives as those used by \function{strftime()}; it defaults to --- 282,286 ---- \begin{funcdesc}{strptime}{string\optional{, format}} Parse a string representing a time according to a format. The return ! value is a \class{struct_time} as returned by \function{gmtime()} or \function{localtime()}. The \var{format} parameter uses the same directives as those used by \function{strftime()}; it defaults to From jackjansen@users.sourceforge.net Tue Feb 4 15:35:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 04 Feb 2003 07:35:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/qt _Qtmodule.c,1.14,1.15 qtscan.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/qt In directory sc8-pr-cvs1:/tmp/cvs-serv7139 Modified Files: _Qtmodule.c qtscan.py Log Message: Changed an edit instruction because of a changed parameter name (sigh). Index: _Qtmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/_Qtmodule.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** _Qtmodule.c 23 Dec 2002 23:16:24 -0000 1.14 --- _Qtmodule.c 4 Feb 2003 15:35:06 -0000 1.15 *************** *** 15,21 **** /* Macro to test whether a weak-loaded CFM function exists */ #define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\ ! PyErr_SetString(PyExc_NotImplementedError, \ ! "Not available in this shared library/OS version"); \ ! return NULL; \ }} while(0) --- 15,21 ---- /* Macro to test whether a weak-loaded CFM function exists */ #define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\ ! PyErr_SetString(PyExc_NotImplementedError, \ ! "Not available in this shared library/OS version"); \ ! return NULL; \ }} while(0) *************** *** 9341,9345 **** PyMac_PRECHECK(ConvertTime); #endif ! if (!PyArg_ParseTuple(_args, "O&", TimeBaseObj_Convert, &newBase)) return NULL; --- 9341,9346 ---- PyMac_PRECHECK(ConvertTime); #endif ! if (!PyArg_ParseTuple(_args, "O&O&", ! QtTimeRecord_Convert, &theTime, TimeBaseObj_Convert, &newBase)) return NULL; *************** *** 9359,9363 **** PyMac_PRECHECK(ConvertTimeScale); #endif ! if (!PyArg_ParseTuple(_args, "l", &newScale)) return NULL; --- 9360,9365 ---- PyMac_PRECHECK(ConvertTimeScale); #endif ! if (!PyArg_ParseTuple(_args, "O&l", ! QtTimeRecord_Convert, &theTime, &newScale)) return NULL; *************** *** 9692,9698 **** PyDoc_STR("() -> (TimeBase _rv)")}, {"ConvertTime", (PyCFunction)Qt_ConvertTime, 1, ! PyDoc_STR("(TimeBase newBase) -> (TimeRecord theTime)")}, {"ConvertTimeScale", (PyCFunction)Qt_ConvertTimeScale, 1, ! PyDoc_STR("(TimeScale newScale) -> (TimeRecord theTime)")}, {"AddTime", (PyCFunction)Qt_AddTime, 1, PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")}, --- 9694,9700 ---- PyDoc_STR("() -> (TimeBase _rv)")}, {"ConvertTime", (PyCFunction)Qt_ConvertTime, 1, ! PyDoc_STR("(TimeRecord theTime, TimeBase newBase) -> (TimeRecord theTime)")}, {"ConvertTimeScale", (PyCFunction)Qt_ConvertTimeScale, 1, ! PyDoc_STR("(TimeRecord theTime, TimeScale newScale) -> (TimeRecord theTime)")}, {"AddTime", (PyCFunction)Qt_AddTime, 1, PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")}, Index: qtscan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/qtscan.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** qtscan.py 12 Dec 2002 10:31:52 -0000 1.21 --- qtscan.py 4 Feb 2003 15:35:07 -0000 1.22 *************** *** 140,143 **** --- 140,144 ---- # ConvertTime and ConvertTimeScale ([('TimeRecord', 'inout', 'OutMode')], [('TimeRecord', 'inout', 'InOutMode')]), + ([('TimeRecord', 'theTime', 'OutMode')], [('TimeRecord', 'theTime', 'InOutMode')]), # AddTime and SubtractTime From jackjansen@users.sourceforge.net Tue Feb 4 15:36:46 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 04 Feb 2003 07:36:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac videoreader.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv7687 Modified Files: videoreader.py Log Message: - Handle the img and MediaFormat modules not being available (by not providing the format info, only the raw data). - Get rid of fsspecs. - Make the demo program at least do something if img not available. Index: videoreader.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/videoreader.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** videoreader.py 30 Dec 2002 22:04:20 -0000 1.1 --- videoreader.py 4 Feb 2003 15:36:42 -0000 1.2 *************** *** 13,21 **** from Carbon import QDOffscreen from Carbon import Res ! import MediaDescr ! import imgformat import os # import audio.format - import macfs class VideoFormat: --- 13,30 ---- from Carbon import QDOffscreen from Carbon import Res ! try: ! import MediaDescr ! except ImportError: ! def _audiodescr(data): ! return None ! else: ! def _audiodescr(data): ! return MediaDescr.SoundDescription.decode(data) ! try: ! from imgformat import macrgb ! except ImportError: ! macrgb = "Macintosh RGB format" import os # import audio.format class VideoFormat: *************** *** 41,46 **** class _Reader: def __init__(self, path): ! fsspec = macfs.FSSpec(path) ! fd = Qt.OpenMovieFile(fsspec, 0) self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0) self.movietimescale = self.movie.GetMovieTimeScale() --- 50,54 ---- class _Reader: def __init__(self, path): ! fd = Qt.OpenMovieFile(path, 0) self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0) self.movietimescale = self.movie.GetMovieTimeScale() *************** *** 56,60 **** n = self.audiomedia.GetMediaSampleDescriptionCount() self.audiomedia.GetMediaSampleDescription(1, handle) ! self.audiodescr = MediaDescr.SoundDescription.decode(handle.data) self.audiotimescale = self.audiomedia.GetMediaTimeScale() del handle --- 64,68 ---- n = self.audiomedia.GetMediaSampleDescriptionCount() self.audiomedia.GetMediaSampleDescription(1, handle) ! self.audiodescr = _audiodescr(handle.data) self.audiotimescale = self.audiomedia.GetMediaTimeScale() del handle *************** *** 140,143 **** --- 148,153 ---- def GetAudioFormat(self): + if not self.audiodescr: + return None, None, None, None, None bps = self.audiodescr['sampleSize'] nch = self.audiodescr['numChannels'] *************** *** 168,171 **** --- 178,183 ---- def GetAudioFrameRate(self): + if not self.audiodescr: + return None return int(self.audiodescr['sampleRate']) *************** *** 173,177 **** width = self.videodescr['width'] height = self.videodescr['height'] ! return VideoFormat('dummy_format', 'Dummy Video Format', width, height, imgformat.macrgb) def GetVideoFrameRate(self): --- 185,189 ---- width = self.videodescr['width'] height = self.videodescr['height'] ! return VideoFormat('dummy_format', 'Dummy Video Format', width, height, macrgb) def GetVideoFrameRate(self): *************** *** 237,252 **** def _test(): ! import img import MacOS Qt.EnterMovies() ! fss, ok = macfs.PromptGetFile('Video to convert') ! if not ok: sys.exit(0) ! path = fss.as_pathname() rdr = reader(path) if not rdr: sys.exit(1) ! dstfss, ok = macfs.StandardPutFile('Name for output folder') ! if not ok: sys.exit(0) ! dstdir = dstfss.as_pathname() num = 0 os.mkdir(dstdir) --- 249,266 ---- def _test(): ! import EasyDialogs ! try: ! import img ! except ImportError: ! img = None import MacOS Qt.EnterMovies() ! path = EasyDialogs.AskFileForOpen(message='Video to convert') ! if not path: sys.exit(0) rdr = reader(path) if not rdr: sys.exit(1) ! dstdir = EasyDialogs.AskFileForSave(message='Name for output folder') ! if not dstdir: sys.exit(0) num = 0 os.mkdir(dstdir) *************** *** 259,272 **** num = num+1 pname = os.path.join(dstdir, fname) ! print 'Writing', fname, imgw, imgh, len(data) ! wrt = img.writer(imgfmt, pname) ! wrt.width = imgw ! wrt.height = imgh ! wrt.write(data) ! timestamp, data = rdr.ReadVideo() ! MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG') ! if num > 20: ! print 'stopping at 20 frames so your disk does not fill up:-)' ! break print 'Total frames:', num --- 273,288 ---- num = num+1 pname = os.path.join(dstdir, fname) ! if not img: print 'Not', ! print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)) ! if img: ! wrt = img.writer(imgfmt, pname) ! wrt.width = imgw ! wrt.height = imgh ! wrt.write(data) ! timestamp, data = rdr.ReadVideo() ! MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG') ! if num > 20: ! print 'stopping at 20 frames so your disk does not fill up:-)' ! break print 'Total frames:', num From doerwalter@users.sourceforge.net Tue Feb 4 16:28:02 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 08:28:02 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv5503/Lib/test Modified Files: test_builtin.py Log Message: filterstring() and filterunicode() in Python/bltinmodule.c blindly assumed that tp_as_sequence->sq_item always returns a str or unicode object. This might fail with str or unicode subclasses. This patch checks whether the object returned from __getitem__ is a str/unicode object and raises a TypeError if not (and the filter function returned true). Furthermore the result for __getitem__ can be more than one character long, so checks for enough memory have to be done. Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_builtin.py 28 Jan 2003 19:21:18 -0000 1.6 --- test_builtin.py 4 Feb 2003 16:28:00 -0000 1.7 *************** *** 368,371 **** --- 368,381 ---- self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234")) + class badstr2(str): + def __getitem__(self, index): + return 42 + self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234")) + + class weirdstr(str): + def __getitem__(self, index): + return weirdstr(2*str.__getitem__(self, index)) + self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344") + if have_unicode: # test bltinmodule.c::filterunicode() *************** *** 374,377 **** --- 384,398 ---- self.assertRaises(TypeError, filter, 42, unicode("12")) self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234"))) + + class badunicode(unicode): + def __getitem__(self, index): + return 42 + self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234")) + + class weirdunicode(unicode): + def __getitem__(self, index): + return weirdunicode(2*unicode.__getitem__(self, index)) + self.assertEqual( + filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344")) def test_float(self): From doerwalter@users.sourceforge.net Tue Feb 4 16:28:02 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 08:28:02 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.272,2.273 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv5503/Python Modified Files: bltinmodule.c Log Message: filterstring() and filterunicode() in Python/bltinmodule.c blindly assumed that tp_as_sequence->sq_item always returns a str or unicode object. This might fail with str or unicode subclasses. This patch checks whether the object returned from __getitem__ is a str/unicode object and raises a TypeError if not (and the filter function returned true). Furthermore the result for __getitem__ can be more than one character long, so checks for enough memory have to be done. Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.272 retrieving revision 2.273 diff -C2 -d -r2.272 -r2.273 *** bltinmodule.c 3 Feb 2003 20:23:33 -0000 2.272 --- bltinmodule.c 4 Feb 2003 16:28:00 -0000 2.273 *************** *** 1893,1896 **** --- 1893,1897 ---- register int i, j; int len = PyString_Size(strobj); + int outlen = len; if (func == Py_None) { *************** *** 1922,1932 **** ok = PyObject_IsTrue(good); Py_DECREF(good); ! if (ok) ! PyString_AS_STRING((PyStringObject *)result)[j++] = ! PyString_AS_STRING((PyStringObject *)item)[0]; Py_DECREF(item); } ! if (j < len) _PyString_Resize(&result, j); --- 1923,1963 ---- ok = PyObject_IsTrue(good); Py_DECREF(good); ! if (ok) { ! int reslen; ! if (!PyString_Check(item)) { ! PyErr_SetString(PyExc_TypeError, "can't filter str to str:" ! " __getitem__ returned different type"); ! Py_DECREF(item); ! goto Fail_1; ! } ! reslen = PyString_GET_SIZE(item); ! if (reslen == 1) { ! PyString_AS_STRING(result)[j++] = ! PyString_AS_STRING(item)[0]; ! } else { ! /* do we need more space? */ ! int need = j + reslen + len-i-1; ! if (need > outlen) { ! /* overallocate, to avoid reallocations */ ! if (need<2*outlen) ! need = 2*outlen; ! if (_PyString_Resize(&result, need)) { ! Py_DECREF(item); ! return NULL; ! } ! outlen = need; ! } ! memcpy( ! PyString_AS_STRING(result) + j, ! PyString_AS_STRING(item), ! reslen ! ); ! j += reslen; ! } ! } Py_DECREF(item); } ! if (j < outlen) _PyString_Resize(&result, j); *************** *** 1947,1950 **** --- 1978,1982 ---- register int i, j; int len = PyUnicode_GetSize(strobj); + int outlen = len; if (func == Py_None) { *************** *** 1976,1986 **** ok = PyObject_IsTrue(good); Py_DECREF(good); ! if (ok) ! PyUnicode_AS_UNICODE((PyStringObject *)result)[j++] = ! PyUnicode_AS_UNICODE((PyStringObject *)item)[0]; Py_DECREF(item); } ! if (j < len) PyUnicode_Resize(&result, j); --- 2008,2048 ---- ok = PyObject_IsTrue(good); Py_DECREF(good); ! if (ok) { ! int reslen; ! if (!PyUnicode_Check(item)) { ! PyErr_SetString(PyExc_TypeError, "can't filter unicode to unicode:" ! " __getitem__ returned different type"); ! Py_DECREF(item); ! goto Fail_1; ! } ! reslen = PyUnicode_GET_SIZE(item); ! if (reslen == 1) { ! PyUnicode_AS_UNICODE(result)[j++] = ! PyUnicode_AS_UNICODE(item)[0]; ! } else { ! /* do we need more space? */ ! int need = j + reslen + len-i-1; ! if (need > outlen) { ! /* overallocate, to avoid reallocations */ ! if (need<2*outlen) ! need = 2*outlen; ! if (PyUnicode_Resize(&result, need)) { ! Py_DECREF(item); ! return NULL; ! } ! outlen = need; ! } ! memcpy( ! PyUnicode_AS_UNICODE(result) + j, ! PyUnicode_AS_UNICODE(item), ! reslen*sizeof(Py_UNICODE) ! ); ! j += reslen; ! } ! } Py_DECREF(item); } ! if (j < outlen) PyUnicode_Resize(&result, j); From neal@metaslash.com Tue Feb 4 16:51:10 2003 From: neal@metaslash.com (Neal Norwitz) Date: Tue, 04 Feb 2003 11:51:10 -0500 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.272,2.273 In-Reply-To: References: Message-ID: <20030204165110.GA24222@epoch.metaslash.com> > ! if (PyUnicode_Resize(&result, need)) { > ! Py_DECREF(item); > ! return NULL; > ! } Instead of returning NULL, should this goto Fail_1? It appears that _PyString_Resize() will free it's argument (result) on failure, but PyUnicode_Resize() doesn't. Neal From doerwalter@users.sourceforge.net Tue Feb 4 16:57:51 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 08:57:51 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.273,2.274 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv24350/Python Modified Files: bltinmodule.c Log Message: PyUnicode_Resize() doesn't free its argument in case of a failure, so we can jump to the error handling code that does. (Spotted by Neal Norwitz) Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.273 retrieving revision 2.274 diff -C2 -d -r2.273 -r2.274 *** bltinmodule.c 4 Feb 2003 16:28:00 -0000 2.273 --- bltinmodule.c 4 Feb 2003 16:57:49 -0000 2.274 *************** *** 2029,2033 **** if (PyUnicode_Resize(&result, need)) { Py_DECREF(item); ! return NULL; } outlen = need; --- 2029,2033 ---- if (PyUnicode_Resize(&result, need)) { Py_DECREF(item); ! goto Fail_1; } outlen = need; From doerwalter@users.sourceforge.net Tue Feb 4 17:04:04 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 09:04:04 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv27954/Lib/test Modified Files: test_builtin.py Log Message: Add a test that checks that filter() honors the sq_item slot for str and unicode subclasses not just for generating the output but for testing too. Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** test_builtin.py 4 Feb 2003 16:28:00 -0000 1.7 --- test_builtin.py 4 Feb 2003 17:04:01 -0000 1.8 *************** *** 378,381 **** --- 378,386 ---- self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344") + class shiftstr(str): + def __getitem__(self, index): + return chr(ord(str.__getitem__(self, index))+1) + self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345") + if have_unicode: # test bltinmodule.c::filterunicode() *************** *** 395,398 **** --- 400,411 ---- self.assertEqual( filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344")) + + class shiftunicode(unicode): + def __getitem__(self, index): + return unichr(ord(unicode.__getitem__(self, index))+1) + self.assertEqual( + filter(lambda x: x>=unicode("3"), shiftunicode("1234")), + unicode("345") + ) def test_float(self): From tim_one@users.sourceforge.net Tue Feb 4 17:49:40 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 09:49:40 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy_reg.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv20029/Lib/test Modified Files: test_copy_reg.py Log Message: Added basic tests of copy_reg's extension registry. Index: test_copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy_reg.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_copy_reg.py 26 Jan 2003 11:32:44 -0000 1.5 --- test_copy_reg.py 4 Feb 2003 17:49:36 -0000 1.6 *************** *** 8,11 **** --- 8,32 ---- + class ExtensionSaver: + # Remember current registration for code (if any), and remove it (if + # there is one). + def __init__(self, code): + self.code = code + if code in copy_reg._inverted_registry: + self.pair = copy_reg._inverted_registry[code] + copy_reg.remove_extension(self.pair[0], self.pair[1], code) + else: + self.pair = None + + # Restore previous registration for code. + def restore(self): + code = self.code + curpair = copy_reg._inverted_registry.get(code) + if curpair is not None: + copy_reg.remove_extension(curpair[0], curpair[1], code) + pair = self.pair + if pair is not None: + copy_reg.add_extension(pair[0], pair[1], code) + class CopyRegTestCase(unittest.TestCase): *************** *** 26,29 **** --- 47,107 ---- self.assertEquals(True, copy.copy(True)) + def test_extension_registry(self): + mod, func, code = 'junk1 ', ' junk2', 0xabcd + e = ExtensionSaver(code) + try: + # Shouldn't be in registry now. + self.assertRaises(ValueError, copy_reg.remove_extension, + mod, func, code) + copy_reg.add_extension(mod, func, code) + # Should be in the registry. + self.assert_(copy_reg._extension_registry[mod, func] == code) + self.assert_(copy_reg._inverted_registry[code] == (mod, func)) + # Shouldn't be in the cache. + self.assert_(code not in copy_reg._extension_cache) + # Redundant registration should be OK. + copy_reg.add_extension(mod, func, code) # shouldn't blow up + # Conflicting code. + self.assertRaises(ValueError, copy_reg.add_extension, + mod, func, code + 1) + self.assertRaises(ValueError, copy_reg.remove_extension, + mod, func, code + 1) + # Conflicting module name. + self.assertRaises(ValueError, copy_reg.add_extension, + mod[1:], func, code ) + self.assertRaises(ValueError, copy_reg.remove_extension, + mod[1:], func, code ) + # Conflicting function name. + self.assertRaises(ValueError, copy_reg.add_extension, + mod, func[1:], code) + self.assertRaises(ValueError, copy_reg.remove_extension, + mod, func[1:], code) + # Can't remove one that isn't registered at all. + if code + 1 not in copy_reg._inverted_registry: + self.assertRaises(ValueError, copy_reg.remove_extension, + mod[1:], func[1:], code + 1) + + finally: + e.restore() + + # Shouldn't be there anymore. + self.assert_((mod, func) not in copy_reg._extension_registry) + # The code *may* be in copy_reg._extension_registry, though, if + # we happened to pick on a registered code. So don't check for + # that. + + # Check valid codes at the limits. + for code in 1, 0x7fffffff: + e = ExtensionSaver(code) + try: + copy_reg.add_extension(mod, func, code) + copy_reg.remove_extension(mod, func, code) + finally: + e.restore() + + # Ensure invalid codes blow up. + for code in -1, 0, 0x80000000L: + self.assertRaises(ValueError, copy_reg.add_extension, + mod, func, code) def test_main(): From gvanrossum@users.sourceforge.net Tue Feb 4 17:53:59 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 04 Feb 2003 09:53:59 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv22116 Modified Files: pep-0307.txt Log Message: Refactored according to 3 main cases. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** pep-0307.txt 4 Feb 2003 14:50:23 -0000 1.8 --- pep-0307.txt 4 Feb 2003 17:53:55 -0000 1.9 *************** *** 217,395 **** ! XXX Refactoring needed ! The following sections should really be reorganized according to ! the following cases: ! 1. classic classes, all protocols ! 2. new-style classes, protocols 0 and 1 ! 3. new-style classes, protocol 2 - The __newobj__ unpickling function ! When the unpickling function returned by __reduce__ (the first ! item of the returned tuple) has the name __newobj__, something ! special happens for pickle protocol 2. An unpickling function ! named __newobj__ is assumed to have the following semantics: ! def __newobj__(cls, *args): ! return cls.__new__(cls, *args) ! Pickle protocol 2 special-cases an unpickling function with this ! name, and emits a pickling opcode that, given 'cls' and 'args', ! will return cls.__new__(cls, *args) without also pickling a ! reference to __newobj__. This is the main reason why protocol 2 ! pickles are so much smaller than classic pickles. Of course, the ! pickling code cannot verify that a function named __newobj__ ! actually has the expected semantics. If you use an unpickling ! function named __newobj__ that returns something different, you ! deserve what you get. ! It is safe to use this feature under Python 2.2; there's nothing ! in the recommended implementation of __newobj__ that depends on ! Python 2.3. ! The __getstate__ and __setstate__ methods ! When there is no __reduce__ for an object, the primary ways to ! customize pickling is by specifying __getstate__ and/or ! __setstate__ methods. These are supported for classic classes as ! well as for new-style classes for which no __reduce__ exists. ! When __reduce__ exists, __getstate__ is not called (unless your ! __reduce__ implementation calls it), but __setstate__ will be ! called with the third item from the tuple returned by __reduce__, ! if not None. ! There's a subtle difference between classic and new-style classes ! here: if a classic class's __getstate__ returns None, ! self.__setstate__(None) will be called as part of unpickling. But ! if a new-style class's __getstate__ returns None, its __setstate__ ! won't be called at all as part of unpickling. ! The __getstate__ method is supposed to return a picklable version ! of an object's state that does not reference the object itself. ! If no __getstate__ method exists, a default state is assumed. ! There are several cases: ! - For a classic class, the default state is self.__dict__. ! - For a new-style class that has an instance __dict__ and no ! __slots__, the default state is self.__dict__. ! - For a new-style class that has no instance __dict__ and no ! __slots__, the default __state__ is None. ! - For a new-style class that has an instance __dict__ and ! __slots__, the default state is a tuple consisting of two ! dictionaries: the first being self.__dict__, and the second ! being a dictionary mapping slot names to slot values. Only ! slots that have a value are included in the latter. ! - For a new-style class that has __slots__ and no instance ! __dict__, the default state is a tuple whose first item is None ! and whose second item is a dictionary mapping slot names to slot ! values described in the previous bullet. ! The __setstate__ should take one argument; it will be called with ! the value returned by __getstate__ or with the default state ! described above if no __setstate__ method is defined. ! If no __setstate__ method exists, a default implementation is ! provided that can handle the state returned by the default ! __getstate__. - It is fine if a class implements one of these but not the other, - as long as it is compatible with the default version. ! New-style classes that inherit a default __reduce__ implementation ! from the ultimate base class 'object'. This implementation is not ! used for protocol 2, and then last four bullets above apply. For ! protocols 0 and 1, the default implementation looks for a ! __getstate__ method, and if none exists, it uses a simpler default ! strategy: ! - If there is an instance __dict__, the state is self.__dict__. ! - Otherwise, the state is None (and __setstate__ will not be ! called). Note that this strategy ignores slots. New-style classes that define slots and don't define __getstate__ in the same class that defines the slots automatically have a __getstate__ method added ! that raises TypeError. Protocol 2 ignores this __getstate__ ! method (recognized by the specific text of the error message). ! The __getinitargs__ and __getnewargs__ methods ! The __setstate__ method (or its default implementation) requires ! that a new object already exists so that its __setstate__ method ! can be called. The point is to create a new object that isn't ! fully initialized; in particular, the class's __init__ method ! should not be called if possible. ! The way this is done differs between classic and new-style ! classes. ! For classic classes, these are the possibilities: ! - Normally, the following trick is used: create an instance of a ! trivial classic class (one without any methods or instance ! variables) and then use __class__ assignment to change its class ! to the desired class. This creates an instance of the desired ! class with an empty __dict__ whose __init__ has not been called. ! - However, if the class has a method named __getinitargs__, the ! above trick is not used, and a class instance is created by ! using the tuple returned by __getinitargs__ as an argument list ! to the class constructor. This is done even if __getinitargs__ ! returns an empty tuple -- a __getinitargs__ method that returns ! () is not equivalent to not having __getinitargs__ at all. ! __getinitargs__ *must* return a tuple. ! - In restricted execution mode, the trick from the first bullet ! doesn't work; in this case, the class constructor is called with ! an empty argument list if no __getinitargs__ method exists. ! This means that in order for a classic class to be unpicklable ! in restricted mode, it must either implement __getinitargs__ or ! its constructor (i.e., its __init__ method) must be callable ! without arguments. ! For new-style classes, these are the possibilities: ! - When using protocol 0 or 1, a default __reduce__ implementation ! is normally inherited from the ultimate base class class ! 'object'. This implementation finds the nearest base class that ! is implemented in C (either as a built-in type or as a type ! defined by an extension class). Calling this base class B and ! the class of the object to be pickled C, the new object is ! created at unpickling time using the following code: ! obj = B.__new__(C, state) ! B.__init__(obj, state) ! where state is a value computed at pickling time as follows: ! state = B(obj) ! This only works when B is not C, and only for certain classes ! B. It does work for the following built-in classes: int, long, ! float, complex, str, unicode, tuple, list, dict; and this is its ! main redeeming factor. ! - When using protocol 2, the default __reduce__ implementation ! inherited from 'object' is ignored. Instead, a new pickling ! opcode is generated that causes a new object to be created as ! follows: obj = C.__new__(C, *args) where args is either the empty tuple, or the tuple returned by ! the __getnewargs__ method, if defined. --- 217,490 ---- ! Customizing pickling absent a __reduce__ implementation ! If no __reduce__ implementation is available for a particular ! class, there are three cases that need to be considered ! separately, because they are handled differently: ! 1. classic class instances, all protocols ! 2. new-style class instances, protocols 0 and 1 ! 3. new-style class instances, protocol 2 + Types implemented in C are considered new-style classes. However, + except for the common built-in types, these need to provide a + __reduce__ implementation in order to be picklable with protocols + 0 or 1. Protocol 2 supports built-in types providing + __getnewargs__, __getstate__ and __setstate__ as well. ! Case 1: pickling classic class instances ! This case is the same for all protocols, and is unchanged from ! Python 2.1. ! For classic classes, __reduce__ is not used. Instead, classic ! classes can customize their pickling by providing methods named ! __getstate__, __setstate__ and __getinitargs__. Absent these, a ! default pickling strategy for classic class instances is ! implemented that works as long as all instance variables are ! picklable. This default strategy is documented in terms of ! default implementations of __getstate__ and __setstate__. ! The primary ways to customize pickling of classic class instances ! is by specifying __getstate__ and/or __setstate__ methods. It is ! fine if a class implements one of these but not the other, as long ! as it is compatible with the default version. + The __getstate__ method ! The __getstate__ method should return a picklable value ! representing the object's state without referencing the object ! itself. If no __getstate__ method exists, a default ! implementation is used that returns self.__dict__. ! The __setstate__ method ! The __setstate__ method should take one argument; it will be ! called with the value returned by __getstate__ (or its default ! implementation). ! If no __setstate__ method exists, a default implementation is ! provided that assumes the state is a dictionary mapping instance ! variable names to values. The default implementation tries two ! things: ! - First, it tries to call self.__dict__.update(state). ! - If the update() call fails with a RuntimeError exception, it ! calls setattr(self, key, value) for each (key, value) pair in ! the state dictionary. This only happens when unpickling in ! restricted execution mode (see the rexec standard library ! module). ! The __getinitargs__ method ! The __setstate__ method (or its default implementation) requires ! that a new object already exists so that its __setstate__ method ! can be called. The point is to create a new object that isn't ! fully initialized; in particular, the class's __init__ method ! should not be called if possible. ! These are the possibilities: ! - Normally, the following trick is used: create an instance of a ! trivial classic class (one without any methods or instance ! variables) and then use __class__ assignment to change its ! class to the desired class. This creates an instance of the ! desired class with an empty __dict__ whose __init__ has not ! been called. ! - However, if the class has a method named __getinitargs__, the ! above trick is not used, and a class instance is created by ! using the tuple returned by __getinitargs__ as an argument ! list to the class constructor. This is done even if ! __getinitargs__ returns an empty tuple -- a __getinitargs__ ! method that returns () is not equivalent to not having ! __getinitargs__ at all. __getinitargs__ *must* return a ! tuple. ! - In restricted execution mode, the trick from the first bullet ! doesn't work; in this case, the class constructor is called ! with an empty argument list if no __getinitargs__ method ! exists. This means that in order for a classic class to be ! unpicklable in restricted execution mode, it must either ! implement __getinitargs__ or its constructor (i.e., its ! __init__ method) must be callable without arguments. ! Case 2: pickling new-style class instances using protocols 0 or 1 ! This case is unchanged from Python 2.2. For better pickling of ! new-style class instances when backwards compatibility is not an ! issue, protocol 2 should be used; see case 3 below. ! New-style classes, whether implemented in C or in Python, inherit ! a default __reduce__ implementation from the universal base class ! 'object'. ! ! This default __reduce__ implementation is not used for those ! built-in types for which the pickle module has built-in support. ! Here's a full list of those types: ! ! - Concrete built-in types: NoneType, bool, int, float, complex, ! str, unicode, tuple, list, dict. (Complex is supported by ! virtue of a __reduce__ implementation registered in copy_reg.) ! In Jython, PyStringMap is also included in this list. ! ! - Classic instances. ! ! - Classic class objects, Python function objects, built-in ! function and method objects, and new-style type objects (== ! new-style class objects). These are pickled by name, not by ! value: at unpickling time, a reference to an object with the ! same name (the fully qualified module name plus the variable ! name in that module) is substituted. ! ! The default __reduce__ implementation will fail at pickling time ! for built-in types not mentioned above. ! ! For new-style classes implemented in Python, the default ! __reduce__ implementation works as follows: ! ! Let D be the class on the object to be pickled. First, find the ! nearest base class that is implemented in C (either as a ! built-in type or as a type defined by an extension class). Call ! this base class B, and the class of the object to be pickled D. ! Unless B is the class 'object', instances of class B must be ! picklable, either by having built-in support (as defined in the ! above three bullet points), or by having a non-default ! __reduce__ implementation. B must not be the same class as D ! (if it were, it would mean that D is not implemented in Python). ! ! The new object is created at unpickling time using the following ! code: ! ! obj = B.__new__(D, state) ! B.__init__(obj, state) ! ! where state is a value computed at pickling time as follows: ! ! state = B(obj) ! ! Objects for which this default __reduce__ implementation is used ! can customize it by defining __getstate__ and/or __setstate__ ! methods. These work almost the same as described for classic ! classes above, except that if __getstate__ returns an object (of ! any type) whose value is considered false (e.g. None, or a number ! that is zero, or an empty sequence or mapping), this state is not ! pickled and __setstate__ will not be called at all. Note that this strategy ignores slots. New-style classes that define slots and don't define __getstate__ in the same class that defines the slots automatically have a __getstate__ method added ! that raises TypeError. ! Case 3: pickling new-style class instances using protocol 2 ! Under protocol 2, the default __reduce__ implementation inherited ! from the 'object' base class is *ignored*. Instead, a different ! default implementation is used, which allows more efficient ! pickling of new-style class instances than possible with protocols ! 0 or 1, at the cost of backward incompatibility with Python 2.2. ! The customization uses three special methods: __getstate__, ! __setstate__ and __getnewargs__. It is fine if a class implements ! one or more but not all of these, as long as it is compatible with ! the default implementations. ! The __getstate__ method ! The __getstate__ method should return a picklable value ! representing the object's state without referencing the object ! itself. If no __getstate__ method exists, a default ! implementation is used which is described below. ! There's a subtle difference between classic and new-style ! classes here: if a classic class's __getstate__ returns None, ! self.__setstate__(None) will be called as part of unpickling. ! But if a new-style class's __getstate__ returns None, its ! __setstate__ won't be called at all as part of unpickling. ! If no __getstate__ method exists, a default state is assumed. ! There are several cases: ! - For a new-style class that has an instance __dict__ and no ! __slots__, the default state is self.__dict__. ! - For a new-style class that has no instance __dict__ and no ! __slots__, the default __state__ is None. ! - For a new-style class that has an instance __dict__ and ! __slots__, the default state is a tuple consisting of two ! dictionaries: the first being self.__dict__, and the second ! being a dictionary mapping slot names to slot values. Only ! slots that have a value are included in the latter. ! - For a new-style class that has __slots__ and no instance ! __dict__, the default state is a tuple whose first item is ! None and whose second item is a dictionary mapping slot names ! to slot values described in the previous bullet. ! Note that new-style classes that define slots and don't define ! __getstate__ in the same class that defines the slots ! automatically have a __getstate__ method added that raises ! TypeError. Protocol 2 ignores this __getstate__ method ! (recognized by the specific text of the error message). ! The __setstate__ method ! The __setstate__ should take one argument; it will be called ! with the value returned by __getstate__ or with the default ! state described above if no __setstate__ method is defined. ! ! If no __setstate__ method exists, a default implementation is ! provided that can handle the state returned by the default ! __getstate__, described above. ! ! The __getnewargs__ method ! ! Like for classic classes, the __setstate__ method (or its ! default implementation) requires that a new object already ! exists so that its __setstate__ method can be called. ! ! In protocol 2, a new pickling opcode is used that causes a new ! object to be created as follows: obj = C.__new__(C, *args) where args is either the empty tuple, or the tuple returned by ! the __getnewargs__ method, if defined. __getnewargs__ must ! return a tuple. The absence of a __getnewargs__ method is ! equivalent to the existence of one that returns (). ! ! ! The __newobj__ unpickling function ! ! When the unpickling function returned by __reduce__ (the first ! item of the returned tuple) has the name __newobj__, something ! special happens for pickle protocol 2. An unpickling function ! named __newobj__ is assumed to have the following semantics: ! ! def __newobj__(cls, *args): ! return cls.__new__(cls, *args) ! ! Pickle protocol 2 special-cases an unpickling function with this ! name, and emits a pickling opcode that, given 'cls' and 'args', ! will return cls.__new__(cls, *args) without also pickling a ! reference to __newobj__ (this is the same pickling opcode used by ! protocol 2 for a new-style class instance when no __reduce__ ! implementation exists). This is the main reason why protocol 2 ! pickles are much smaller than classic pickles. Of course, the ! pickling code cannot verify that a function named __newobj__ ! actually has the expected semantics. If you use an unpickling ! function named __newobj__ that returns something different, you ! deserve what you get. ! ! It is safe to use this feature under Python 2.2; there's nothing ! in the recommended implementation of __newobj__ that depends on ! Python 2.3. From doerwalter@users.sourceforge.net Tue Feb 4 18:02:31 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 10:02:31 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25990/Modules Modified Files: _iconv_codec.c Log Message: Use size_t instead of int for various variables to prevent signed/unsigned comparison warnings on the call to iconv(). Fix comment typos. >From SF patch #680146. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** _iconv_codec.c 31 Jan 2003 17:19:07 -0000 1.7 --- _iconv_codec.c 4 Feb 2003 18:02:28 -0000 1.8 *************** *** 43,47 **** staticforward PyTypeObject iconvcodec_Type; ! /* does the choosen internal encoding require * byteswapping to get native endianness? * 0=no, 1=yes, -1=unknown */ --- 43,47 ---- staticforward PyTypeObject iconvcodec_Type; ! /* does the chosen internal encoding require * byteswapping to get native endianness? * 0=no, 1=yes, -1=unknown */ *************** *** 147,151 **** while (inplen > 0) { ! if (iconv(self->enchdl, (char**)&inp, &inplen, &out, &outlen) == -1) { char reason[128]; int errpos; --- 147,151 ---- while (inplen > 0) { ! if (iconv(self->enchdl, (char**)&inp, &inplen, &out, &outlen) == (size_t)-1) { char reason[128]; int errpos; *************** *** 354,358 **** while (inplen > 0) { char *oldout = out; ! char res = iconv(self->dechdl, (char**)&inp, &inplen, &out, &outlen); if (byteswap) { --- 354,358 ---- while (inplen > 0) { char *oldout = out; ! size_t res = iconv(self->dechdl, (char**)&inp, &inplen, &out, &outlen); if (byteswap) { *************** *** 373,377 **** } } ! if (res == -1) { char reason[128], *reasonpos = (char *)reason; int errpos; --- 373,377 ---- } } ! if (res == (size_t)-1) { char reason[128], *reasonpos = (char *)reason; int errpos; *************** *** 663,671 **** char in = 1; char *inptr = ∈ ! int insize = 1; Py_UNICODE out = 0; char *outptr = (char *)&out; ! int outsize = sizeof(out); ! int res; iconv_t hdl = iconv_open(UNICODE_ENCODING, "ASCII"); --- 663,671 ---- char in = 1; char *inptr = ∈ ! size_t insize = 1; Py_UNICODE out = 0; char *outptr = (char *)&out; ! size_t outsize = sizeof(out); ! size_t res; iconv_t hdl = iconv_open(UNICODE_ENCODING, "ASCII"); *************** *** 675,682 **** res = iconv(hdl, &inptr, &insize, &outptr, &outsize); ! if (res == -1) Py_FatalError("can't initialize the _iconv_codec module: iconv() failed"); ! /* Check whether conv() returned native endianess or not for the choosen encoding */ if (out == 0x1) byteswap = 0; --- 675,682 ---- res = iconv(hdl, &inptr, &insize, &outptr, &outsize); ! if (res == (size_t)-1) Py_FatalError("can't initialize the _iconv_codec module: iconv() failed"); ! /* Check whether conv() returned native endianess or not for the chosen encoding */ if (out == 0x1) byteswap = 0; From gvanrossum@users.sourceforge.net Tue Feb 4 19:12:28 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 04 Feb 2003 11:12:28 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv26330 Modified Files: pep-0307.txt Log Message: Introduce extension codes. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** pep-0307.txt 4 Feb 2003 17:53:55 -0000 1.9 --- pep-0307.txt 4 Feb 2003 19:12:25 -0000 1.10 *************** *** 489,492 **** --- 489,568 ---- + The extension registry + + Protocol 2 supports a new mechanism to reduce the size of pickles. + + When class instances (classic or new-style) are pickled, the full + name of the class (module name including package name, and class + name) is included in the pickle. Especially for applications that + generate many small pickles, this is a lot of overhead that has to + be repeated in each pickle. For large pickles, when using + protocol 1, repeated references to the same class name are + compressed using the "memo" feature; but each class name must be + spelled in full at least once per pickle, and this causes a lot of + overhead for small pickles. + + The extension registry allows one to represent the most frequently + used names by small integers, which are pickled very efficiently: + an extension code in the range 1-255 requires only two bytes + including the opcode, one in the range 256-65535 requires only + three bytes including the opcode. + + One of the design goals of the pickle protocol is to make pickles + "context-free": as long as you have installed the modules + containing the classes referenced by a pickle, you can unpickle + it, without needing to import any of those classes ahead of time. + + Unbridled use of extension codes could jeopardize this desirable + property of pickles. Therefore, the main use of extension codes + is reserved for a set of codes to be standardized by some + standard-setting body. This being Python, the standard-setting + body is the PSF. From time to time, the PSF will decide on a + table mapping extension codes to class names (or occasionally + names of other global objects; functions are also eligible). This + table will be incorporated in the next Python release(s). + + However, for some applications, like Zope, context-free pickles + are not a requirement, and waiting for the PSF to standardize + some codes may not be practical. Two solutions are offered for + such applications. + + First of all, a few ranges of extension codes is reserved for + private use. Any application can register codes in these ranges. + Two applications exchanging pickles using codes in these ranges + need to have some out-of-band mechanism to agree on the mapping + between extension codes and names. + + Second, some large Python projects (e.g. Zope or Twisted) can be + assigned a range of extension codes outside the "private use" + range that they can assign as they see fit. + + The extension registry is defined as a mapping between extension + codes and names. When an extension code is unpickled, it ends up + producing an object, but this object is gotten by interpreting the + name as a module name followed by a class (or function) name. The + mapping from names to objects is cached. It is quite possible + that certain names cannot be imported; that should not be a + problem as long as no pickle containing a reference to such names + has to be unpickled. (The same issue already exists for direct + references to such names in pickles that use protocols 0 or 1.) + + Here is the proposed initial assigment of extension code ranges: + + First Last Count Purpose + + 0 0 1 Reserved -- will never be used + 1 127 127 Reserved for Python standard library + 128 191 64 Reserved for Zope 3 + 192 239 48 Reserved for 3rd parties + 240 255 16 Reserved for private use (will never be assigned) + 256 Max Max Reserved for future assignment + + 'Max' stands for 2147483647, or 2**31-1. This is a hard + limitation of the protocol as currently defined. + + At the moment, no specific extension codes have been assigned yet. + + TBD From fdrake@users.sourceforge.net Tue Feb 4 19:13:09 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 04 Feb 2003 11:13:09 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libposixpath.tex,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv26414 Modified Files: libposixpath.tex Log Message: supports_unicode_filenames was not in the right location. Index: libposixpath.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libposixpath.tex,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** libposixpath.tex 31 Dec 2002 13:38:28 -0000 1.32 --- libposixpath.tex 4 Feb 2003 19:13:07 -0000 1.33 *************** *** 230,240 **** assignment.) - \begin{datadesc}{supports_unicode_filenames} - True if arbitrary Unicode strings can be used as file names (within - limitations imposed by the file system), and if os.listdir returns - Unicode strings for a Unicode argument. - \versionadded{2.3} - \end{datadesc} - \begin{notice} Symbolic links to directories are not treated as subdirectories, and --- 230,233 ---- *************** *** 246,247 **** --- 239,248 ---- \end{notice} \end{funcdesc} + + \begin{datadesc}{supports_unicode_filenames} + True if arbitrary Unicode strings can be used as file names (within + limitations imposed by the file system), and if + \function{os.listdir()} returns Unicode strings for a Unicode + argument. + \versionadded{2.3} + \end{datadesc} From gvanrossum@users.sourceforge.net Tue Feb 4 19:28:19 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 04 Feb 2003 11:28:19 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv639 Modified Files: pep-0307.txt Log Message: Document the extension registry API. Remove mention of Twisted (they don't want it). Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** pep-0307.txt 4 Feb 2003 19:12:25 -0000 1.10 --- pep-0307.txt 4 Feb 2003 19:28:16 -0000 1.11 *************** *** 534,540 **** between extension codes and names. ! Second, some large Python projects (e.g. Zope or Twisted) can be ! assigned a range of extension codes outside the "private use" ! range that they can assign as they see fit. The extension registry is defined as a mapping between extension --- 534,540 ---- between extension codes and names. ! Second, some large Python projects (e.g. Zope) can be assigned a ! range of extension codes outside the "private use" range that they ! can assign as they see fit. The extension registry is defined as a mapping between extension *************** *** 557,566 **** 192 239 48 Reserved for 3rd parties 240 255 16 Reserved for private use (will never be assigned) ! 256 Max Max Reserved for future assignment ! 'Max' stands for 2147483647, or 2**31-1. This is a hard ! limitation of the protocol as currently defined. At the moment, no specific extension codes have been assigned yet. --- 557,597 ---- 192 239 48 Reserved for 3rd parties 240 255 16 Reserved for private use (will never be assigned) ! 256 MAX MAX Reserved for future assignment ! MAX stands for 2147483647, or 2**31-1. This is a hard limitation ! of the protocol as currently defined. At the moment, no specific extension codes have been assigned yet. + + + Extension registry API + + The extension registry is maintained as private global variables + in the copy_reg module. The following three functions are defined + in this module to manipulate the registry: + + add_extension(module, name, code) + Register an extension code. The module and name arguments + must be strings; code must be an int in the inclusive range 1 + through MAX. This must either register a new (module, name) + pair to a new code, or be a redundant repeat of a previous + call that was not canceled by a remove_extension() call; a + (module, name) pair may not be mapped to more than one code, + nor may a code be mapped to more than one (module, name) + pair. (XXX Aliasing may actually cause as problem for this + requirement; we'll see as we go.) + + remove_extension(module, name, code) + Arguments are as for add_extension(). Remove a previously + registered mapping between (module, name) and code. + + clear_extension_cache() + The implementation of extension codes may use a cache to speed + up loading objects that are named frequently. This cache can + be emptied (removing references to cached objects) by calling + this method. + + Note that the API does not enforce the standard range assignments. + It is up to applications to respect these. From lemburg@users.sourceforge.net Tue Feb 4 19:35:08 2003 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Tue, 04 Feb 2003 11:35:08 -0800 Subject: [Python-checkins] python/dist/src/Modules _codecsmodule.c,2.16,2.17 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2848/Modules Modified Files: _codecsmodule.c Log Message: Fix for [ 543344 ] Interpreter crashes when recoding; suggested by Michael Stone (mbrierst). Python 2.1.4, 2.2.2 candidate. Index: _codecsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_codecsmodule.c,v retrieving revision 2.16 retrieving revision 2.17 diff -C2 -d -r2.16 -r2.17 *** _codecsmodule.c 31 Oct 2002 13:36:29 -0000 2.16 --- _codecsmodule.c 4 Feb 2003 19:35:03 -0000 2.17 *************** *** 168,173 **** return NULL; ! if (PyUnicode_Check(obj)) return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); else { if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) --- 168,175 ---- return NULL; ! if (PyUnicode_Check(obj)) { ! Py_INCREF(obj); return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); + } else { if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) From doerwalter@users.sourceforge.net Tue Feb 4 20:24:48 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:24:48 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25412/Lib/test Modified Files: test_builtin.py Log Message: Make sure filter() never returns tuple, str or unicode subclasses. (Discussed in SF patch #665835) Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** test_builtin.py 4 Feb 2003 17:04:01 -0000 1.8 --- test_builtin.py 4 Feb 2003 20:24:45 -0000 1.9 *************** *** 409,412 **** --- 409,435 ---- ) + def test_filter_subclasses(self): + # test, that filter() never returns tuple, str or unicode subclasses + funcs = (None, lambda x: True) + class tuple2(tuple): + pass + class str2(str): + pass + inputs = { + tuple2: [(), (1,2,3)], + str2: ["", "123"] + } + if have_unicode: + class unicode2(unicode): + pass + inputs[unicode2] = [unicode(), unicode("123")] + + for func in funcs: + for (cls, inps) in inputs.iteritems(): + for inp in inps: + out = filter(func, cls(inp)) + self.assertEqual(inp, out) + self.assert_(not isinstance(out, cls)) + def test_float(self): self.assertEqual(float(3.14), 3.14) From doerwalter@users.sourceforge.net Tue Feb 4 20:24:48 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:24:48 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.274,2.275 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv25412/Python Modified Files: bltinmodule.c Log Message: Make sure filter() never returns tuple, str or unicode subclasses. (Discussed in SF patch #665835) Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.274 retrieving revision 2.275 diff -C2 -d -r2.274 -r2.275 *** bltinmodule.c 4 Feb 2003 16:57:49 -0000 2.274 --- bltinmodule.c 4 Feb 2003 20:24:43 -0000 2.275 *************** *** 1839,1843 **** if (len == 0) { ! Py_INCREF(tuple); return tuple; } --- 1839,1846 ---- if (len == 0) { ! if (PyTuple_CheckExact(tuple)) ! Py_INCREF(tuple); ! else ! tuple = PyTuple_New(0); return tuple; } *************** *** 1896,1901 **** if (func == Py_None) { ! /* No character is ever false -- share input string */ ! Py_INCREF(strobj); return strobj; } --- 1899,1911 ---- if (func == Py_None) { ! /* No character is ever false -- share input string ! * (if it's not a subclass) */ ! if (PyString_CheckExact(strobj)) ! Py_INCREF(strobj); ! else ! strobj = PyString_FromStringAndSize( ! PyString_AS_STRING(strobj), ! len ! ); return strobj; } *************** *** 1981,1986 **** if (func == Py_None) { ! /* No character is ever false -- share input string */ ! Py_INCREF(strobj); return strobj; } --- 1991,2003 ---- if (func == Py_None) { ! /* No character is ever false -- share input string ! * (it if's not a subclass) */ ! if (PyUnicode_CheckExact(strobj)) ! Py_INCREF(strobj); ! else ! strobj = PyUnicode_FromUnicode( ! PyUnicode_AS_UNICODE(strobj), ! len ! ); return strobj; } From lemburg@users.sourceforge.net Tue Feb 4 19:35:36 2003 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Tue, 04 Feb 2003 11:35:36 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_codecs.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2848/Lib/test Modified Files: test_codecs.py Log Message: Fix for [ 543344 ] Interpreter crashes when recoding; suggested by Michael Stone (mbrierst). Python 2.1.4, 2.2.2 candidate. Index: test_codecs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_codecs.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_codecs.py 3 Sep 2002 13:53:40 -0000 1.4 --- test_codecs.py 4 Feb 2003 19:35:01 -0000 1.5 *************** *** 28,31 **** --- 28,39 ---- self.assertEquals(codecs.escape_decode(""), ("", 0)) + class RecodingTest(unittest.TestCase): + def test_recoding(self): + f = StringIO.StringIO() + f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8") + f2.write(u"a") + f2.close() + # Python used to crash on this at exit because of a refcount + # bug in _codecsmodule.c def test_main(): *************** *** 33,36 **** --- 41,45 ---- suite.addTest(unittest.makeSuite(UTF16Test)) suite.addTest(unittest.makeSuite(EscapeDecodeTest)) + suite.addTest(unittest.makeSuite(RecodingTest)) test_support.run_suite(suite) From nnorwitz@users.sourceforge.net Tue Feb 4 20:45:23 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:45:23 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.56,1.57 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2882/Modules Modified Files: datetimemodule.c Log Message: Whitespace normalization Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** datetimemodule.c 1 Feb 2003 04:40:04 -0000 1.56 --- datetimemodule.c 4 Feb 2003 20:45:17 -0000 1.57 *************** *** 2871,2875 **** PyDoc_STR("Abstract base class for time zone info objects."); ! statichere PyTypeObject PyDateTime_TZInfoType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ --- 2871,2875 ---- PyDoc_STR("Abstract base class for time zone info objects."); ! statichere PyTypeObject PyDateTime_TZInfoType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ From nnorwitz@users.sourceforge.net Tue Feb 4 20:46:53 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:46:53 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv3804/Modules Modified Files: _iconv_codec.c Log Message: Remove forward static reference since it is not required Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** _iconv_codec.c 4 Feb 2003 18:02:28 -0000 1.8 --- _iconv_codec.c 4 Feb 2003 20:46:50 -0000 1.9 *************** *** 41,46 **** PyDoc_STRVAR(iconvcodec_doc, "iconvcodec object"); - staticforward PyTypeObject iconvcodec_Type; - /* does the chosen internal encoding require * byteswapping to get native endianness? --- 41,44 ---- *************** *** 609,613 **** } ! statichere PyTypeObject iconvcodec_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* Number of items for varobject */ --- 607,611 ---- } ! static PyTypeObject iconvcodec_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* Number of items for varobject */ From nascheme@users.sourceforge.net Tue Feb 4 20:55:46 2003 From: nascheme@users.sourceforge.net (nascheme@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:55:46 -0800 Subject: [Python-checkins] python/dist/src/Python getargs.c,2.95,2.96 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv8360/Python Modified Files: getargs.c Log Message: If a float is passed where a int is expected, issue a DeprecationWarning instead of raising a TypeError. Closes #660144 (again). Index: getargs.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/getargs.c,v retrieving revision 2.95 retrieving revision 2.96 diff -C2 -d -r2.95 -r2.96 *** getargs.c 24 Jan 2003 22:15:21 -0000 2.95 --- getargs.c 4 Feb 2003 20:55:40 -0000 2.96 *************** *** 388,391 **** --- 388,404 ---- #define CONV_UNICODE "(unicode conversion error)" + /* explicitly check for float arguments when integers are expected. For now + * signal a warning. Returns true if an exception was raised. */ + static int + float_argument_error(PyObject *arg) + { + if (PyFloat_Check(arg) && + PyErr_Warn(PyExc_DeprecationWarning, + "integer argument expected, got float" )) + return 1; + else + return 0; + } + /* Convert a non-tuple argument. Return NULL if conversion went OK, or a string with a message describing the failure. The message is *************** *** 410,415 **** char *p = va_arg(*p_va, char *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 423,428 ---- char *p = va_arg(*p_va, char *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) *************** *** 434,439 **** char *p = va_arg(*p_va, char *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 447,452 ---- char *p = va_arg(*p_va, char *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) *************** *** 457,462 **** short *p = va_arg(*p_va, short *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 470,475 ---- short *p = va_arg(*p_va, short *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) *************** *** 481,486 **** unsigned short *p = va_arg(*p_va, unsigned short *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 494,499 ---- unsigned short *p = va_arg(*p_va, unsigned short *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) *************** *** 504,509 **** int *p = va_arg(*p_va, int *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 517,522 ---- int *p = va_arg(*p_va, int *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) *************** *** 527,532 **** long *p = va_arg(*p_va, long *); long ival; ! if (PyFloat_Check(arg)) ! return converterr("integer", arg, msgbuf, bufsize); ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) --- 540,545 ---- long *p = va_arg(*p_va, long *); long ival; ! if (float_argument_error(arg)) ! return NULL; ival = PyInt_AsLong(arg); if (ival == -1 && PyErr_Occurred()) From tim_one@users.sourceforge.net Tue Feb 4 20:56:46 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:56:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.42,1.43 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv7825/Lib/test Modified Files: pickletester.py Log Message: cPickle now generates proto 2 EXT[124] when appropriate. Moved such EXT tests as currently exist from TempAbstractPickleTests to AbstractPickleTests, so that test_cpickle runs them too. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** pickletester.py 3 Feb 2003 22:32:18 -0000 1.42 --- pickletester.py 4 Feb 2003 20:56:08 -0000 1.43 *************** *** 584,604 **** self.assertEqual(x.__dict__, y.__dict__, detail) - # XXX Temporary hack, so long as the C implementation of pickle protocol - # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests - # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests - # XXX along with the references to it in test_pickle.py. - class TempAbstractPickleTests(unittest.TestCase): - - def test_newobj_list_slots(self): - x = SlotList([1, 2, 3]) - x.foo = 42 - x.bar = "hello" - s = self.dumps(x, 2) - y = self.loads(s) - self.assertEqual(list(x), list(y)) - self.assertEqual(x.__dict__, y.__dict__) - self.assertEqual(x.foo, y.foo) - self.assertEqual(x.bar, y.bar) - # Register a type with copy_reg, with extension code extcode. Pickle # an object of that type. Check that the resulting pickle uses opcode --- 584,587 ---- *************** *** 639,643 **** def test_global_ext4(self): ! self.produce_global_ext(0xffffff0, pickle.EXT4) --- 622,643 ---- def test_global_ext4(self): ! self.produce_global_ext(0xabcdef0, pickle.EXT4) ! ! # XXX Temporary hack, so long as the C implementation of pickle protocol ! # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests ! # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests ! # XXX along with the references to it in test_pickle.py. ! class TempAbstractPickleTests(unittest.TestCase): ! ! def test_newobj_list_slots(self): ! x = SlotList([1, 2, 3]) ! x.foo = 42 ! x.bar = "hello" ! s = self.dumps(x, 2) ! y = self.loads(s) ! self.assertEqual(list(x), list(y)) ! self.assertEqual(x.__dict__, y.__dict__) ! self.assertEqual(x.foo, y.foo) ! self.assertEqual(x.bar, y.bar) From nascheme@users.sourceforge.net Tue Feb 4 20:59:49 2003 From: nascheme@users.sourceforge.net (nascheme@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:59:49 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.640,1.641 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv10115/Misc Modified Files: NEWS Log Message: If a float is passed where a int is expected, issue a DeprecationWarning instead of raising a TypeError. Closes #660144 (again). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.640 retrieving revision 1.641 diff -C2 -d -r1.640 -r1.641 *** NEWS 3 Feb 2003 20:53:14 -0000 1.640 --- NEWS 4 Feb 2003 20:59:40 -0000 1.641 *************** *** 224,230 **** ----- ! - The PyArg_Parse functions now raise a TypeError instead of truncating float ! arguments if an integer is specified (this affects the 'b', 'B', 'h', 'H', ! 'i', and 'l' codes). --- 224,231 ---- ----- ! - The PyArg_Parse functions now issue a DeprecationWarning if a float ! argument is provided when an integer is specified (this affects the 'b', ! 'B', 'h', 'H', 'i', and 'l' codes). Future versions of Python will ! raise a TypeError. From tim_one@users.sourceforge.net Tue Feb 4 20:56:50 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 12:56:50 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.123,2.124 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7825/Modules Modified Files: cPickle.c Log Message: cPickle now generates proto 2 EXT[124] when appropriate. Moved such EXT tests as currently exist from TempAbstractPickleTests to AbstractPickleTests, so that test_cpickle runs them too. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.123 retrieving revision 2.124 diff -C2 -d -r2.123 -r2.124 *** cPickle.c 4 Feb 2003 05:20:32 -0000 2.123 --- cPickle.c 4 Feb 2003 20:56:09 -0000 2.124 *************** *** 110,113 **** --- 110,116 ---- static PyObject *extension_cache; + /* For looking up name pairs in copy_reg._extension_registry. */ + static PyObject *two_tuple; + static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, *************** *** 1932,1936 **** Py_DECREF(klass); cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: it's not the same object as %s.%s", "OSS", args, module, global_name); goto finally; --- 1935,1940 ---- Py_DECREF(klass); cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: it's not the same object " ! "as %s.%s", "OSS", args, module, global_name); goto finally; *************** *** 1938,1941 **** --- 1942,2002 ---- Py_DECREF(klass); + if (self->proto >= 2) { + /* See whether this is in the extension registry, and if + * so generate an EXT opcode. + */ + PyObject *py_code; /* extension code as Python object */ + long code; /* extensoin code as C value */ + char c_str[5]; + int n; + + PyTuple_SET_ITEM(two_tuple, 0, module); + PyTuple_SET_ITEM(two_tuple, 1, global_name); + py_code = PyDict_GetItem(extension_registry, two_tuple); + if (py_code == NULL) + goto gen_global; /* not registered */ + + /* Verify py_code has the right type and value. */ + if (!PyInt_Check(py_code)) { + cPickle_ErrFormat(PicklingError, "Can't pickle %s: " + "extension code %s isn't n integer", + "OO", args, py_code); + goto finally; + } + code = PyInt_AS_LONG(py_code); + if (code <= 0 || code > 0x7fffffffL) { + cPickle_ErrFormat(PicklingError, "Can't pickle %s: " + "extension code %ld is out of range", + "Ol", args, code); + goto finally; + } + + /* Generate an EXT opcode. */ + if (code <= 0xff) { + c_str[0] = EXT1; + c_str[1] = (char)code; + n = 2; + } + else if (code <= 0xffff) { + c_str[0] = EXT2; + c_str[1] = (char)(code & 0xff); + c_str[2] = (char)((code >> 8) & 0xff); + n = 3; + } + else { + c_str[0] = EXT4; + c_str[1] = (char)(code & 0xff); + c_str[2] = (char)((code >> 8) & 0xff); + c_str[3] = (char)((code >> 16) & 0xff); + c_str[4] = (char)((code >> 24) & 0xff); + n = 5; + } + + if (self->write_func(self, c_str, n) >= 0) + res = 0; + goto finally; /* and don't memoize */ + } + + gen_global: if (self->write_func(self, &global, 1) < 0) goto finally; *************** *** 5214,5218 **** Py_DECREF(copy_reg); ! if (!( empty_tuple = PyTuple_New(0))) return -1; --- 5275,5283 ---- Py_DECREF(copy_reg); ! if (!(empty_tuple = PyTuple_New(0))) ! return -1; ! ! two_tuple = PyTuple_New(2); ! if (two_tuple == NULL) return -1; From tim_one@users.sourceforge.net Tue Feb 4 21:47:53 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 13:47:53 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.124,2.125 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv31627/Modules Modified Files: cPickle.c Log Message: cPickle: exempt two_tuple from GC -- it's a speed hack, and doesn't guarantee to keep valid pointers in its slots. tests: Moved ExtensionSaver from test_copy_reg into pickletester, and use it both places. Once extension codes get assigned, it won't be safe to overwrite them willy nilly in test suites, and ExtensionSaver does a thorough job of undoing any possible damage. Beefed up the EXT[124] tests a bit, to check the smallest and largest codes in each opcode's range too. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.124 retrieving revision 2.125 diff -C2 -d -r2.124 -r2.125 *** cPickle.c 4 Feb 2003 20:56:09 -0000 2.124 --- cPickle.c 4 Feb 2003 21:47:44 -0000 2.125 *************** *** 1947,1951 **** */ PyObject *py_code; /* extension code as Python object */ ! long code; /* extensoin code as C value */ char c_str[5]; int n; --- 1947,1951 ---- */ PyObject *py_code; /* extension code as Python object */ ! long code; /* extension code as C value */ char c_str[5]; int n; *************** *** 5281,5284 **** --- 5281,5289 ---- if (two_tuple == NULL) return -1; + /* We use this temp container with no regard to refcounts, or to + * keeping containees alive. Exempt from GC, because we don't + * want anything looking at two_tuple() by magic. + */ + PyObject_GC_UnTrack(two_tuple); /* Ugh */ From tim_one@users.sourceforge.net Tue Feb 4 21:48:18 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 13:48:18 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.43,1.44 test_copy_reg.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv31627/Lib/test Modified Files: pickletester.py test_copy_reg.py Log Message: cPickle: exempt two_tuple from GC -- it's a speed hack, and doesn't guarantee to keep valid pointers in its slots. tests: Moved ExtensionSaver from test_copy_reg into pickletester, and use it both places. Once extension codes get assigned, it won't be safe to overwrite them willy nilly in test suites, and ExtensionSaver does a thorough job of undoing any possible damage. Beefed up the EXT[124] tests a bit, to check the smallest and largest codes in each opcode's range too. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** pickletester.py 4 Feb 2003 20:56:08 -0000 1.43 --- pickletester.py 4 Feb 2003 21:47:43 -0000 1.44 *************** *** 2,5 **** --- 2,6 ---- import pickle import pickletools + import copy_reg from test.test_support import TestFailed, have_unicode, TESTFN *************** *** 18,21 **** --- 19,53 ---- return False + # We can't very well test the extension registry without putting known stuff + # in it, but we have to be careful to restore its original state. Code + # should do this: + # + # e = ExtensionSaver(extension_code) + # try: + # fiddle w/ the extension registry's stuff for extension_code + # finally: + # e.restore() + + class ExtensionSaver: + # Remember current registration for code (if any), and remove it (if + # there is one). + def __init__(self, code): + self.code = code + if code in copy_reg._inverted_registry: + self.pair = copy_reg._inverted_registry[code] + copy_reg.remove_extension(self.pair[0], self.pair[1], code) + else: + self.pair = None + + # Restore previous registration for code. + def restore(self): + code = self.code + curpair = copy_reg._inverted_registry.get(code) + if curpair is not None: + copy_reg.remove_extension(curpair[0], curpair[1], code) + pair = self.pair + if pair is not None: + copy_reg.add_extension(pair[0], pair[1], code) + class C: def __cmp__(self, other): *************** *** 587,594 **** # an object of that type. Check that the resulting pickle uses opcode # (EXT[124]) under proto 2, and not in proto 1. def produce_global_ext(self, extcode, opcode): ! import copy_reg ! copy_reg.add_extension(__name__, "MyList", extcode) try: x = MyList([1, 2, 3]) x.foo = 42 --- 619,627 ---- # an object of that type. Check that the resulting pickle uses opcode # (EXT[124]) under proto 2, and not in proto 1. + def produce_global_ext(self, extcode, opcode): ! e = ExtensionSaver(extcode) try: + copy_reg.add_extension(__name__, "MyList", extcode) x = MyList([1, 2, 3]) x.foo = 42 *************** *** 597,626 **** # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) y = self.loads(s1) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) - self.assert_(s1.find(__name__) >= 0) - self.assert_(s1.find("MyList") >= 0) # Dump using protocol 2 for test. s2 = self.dumps(x, 2) ! self.assertEqual(s2.find(__name__), -1) ! self.assertEqual(s2.find("MyList"), -1) y = self.loads(s2) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) - self.assertEqual(opcode_in_pickle(opcode, s2), True) finally: ! copy_reg.remove_extension(__name__, "MyList", extcode) def test_global_ext1(self): ! self.produce_global_ext(0xf0, pickle.EXT1) def test_global_ext2(self): ! self.produce_global_ext(0xfff0, pickle.EXT2) def test_global_ext4(self): ! self.produce_global_ext(0xabcdef0, pickle.EXT4) # XXX Temporary hack, so long as the C implementation of pickle protocol --- 630,668 ---- # Dump using protocol 1 for comparison. s1 = self.dumps(x, 1) + self.assert_(__name__ in s1) + self.assert_("MyList" in s1) + self.assertEqual(opcode_in_pickle(opcode, s1), False) + y = self.loads(s1) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) # Dump using protocol 2 for test. s2 = self.dumps(x, 2) ! self.assert_(__name__ not in s2) ! self.assert_("MyList" not in s2) ! self.assertEqual(opcode_in_pickle(opcode, s2), True) ! y = self.loads(s2) self.assertEqual(list(x), list(y)) self.assertEqual(x.__dict__, y.__dict__) finally: ! e.restore() def test_global_ext1(self): ! self.produce_global_ext(0x00000001, pickle.EXT1) # smallest EXT1 code ! self.produce_global_ext(0x000000ff, pickle.EXT1) # largest EXT1 code def test_global_ext2(self): ! self.produce_global_ext(0x00000100, pickle.EXT2) # smallest EXT2 code ! self.produce_global_ext(0x0000ffff, pickle.EXT2) # largest EXT2 code ! self.produce_global_ext(0x0000abcd, pickle.EXT2) # check endianness def test_global_ext4(self): ! self.produce_global_ext(0x00010000, pickle.EXT4) # smallest EXT4 code ! self.produce_global_ext(0x7fffffff, pickle.EXT4) # largest EXT4 code ! self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness ! # XXX Temporary hack, so long as the C implementation of pickle protocol Index: test_copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy_reg.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_copy_reg.py 4 Feb 2003 17:49:36 -0000 1.6 --- test_copy_reg.py 4 Feb 2003 21:47:43 -0000 1.7 *************** *** 1,31 **** import copy_reg import unittest - from test import test_support class C: pass - - class ExtensionSaver: - # Remember current registration for code (if any), and remove it (if - # there is one). - def __init__(self, code): - self.code = code - if code in copy_reg._inverted_registry: - self.pair = copy_reg._inverted_registry[code] - copy_reg.remove_extension(self.pair[0], self.pair[1], code) - else: - self.pair = None - - # Restore previous registration for code. - def restore(self): - code = self.code - curpair = copy_reg._inverted_registry.get(code) - if curpair is not None: - copy_reg.remove_extension(curpair[0], curpair[1], code) - pair = self.pair - if pair is not None: - copy_reg.add_extension(pair[0], pair[1], code) class CopyRegTestCase(unittest.TestCase): --- 1,11 ---- import copy_reg import unittest + from test import test_support + from test.pickletester import ExtensionSaver class C: pass class CopyRegTestCase(unittest.TestCase): From montanaro@users.sourceforge.net Tue Feb 4 22:10:57 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 14:10:57 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv11868 Modified Files: test_csv.py Log Message: myexceltsv needs to subclass csv.excel, not csv.Dialect. doh! Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** test_csv.py 3 Feb 2003 20:26:26 -0000 1.14 --- test_csv.py 4 Feb 2003 22:10:54 -0000 1.15 *************** *** 216,220 **** def test_dialect_class(self): ! class myexceltsv(csv.Dialect): delimiter = "\t" fileobj = StringIO() --- 216,220 ---- def test_dialect_class(self): ! class myexceltsv(csv.excel): delimiter = "\t" fileobj = StringIO() From andrewmcnamara@users.sourceforge.net Wed Feb 5 00:45:41 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Tue, 04 Feb 2003 16:45:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv8594 Modified Files: csv.py Log Message: Import the C module's __version__ symbol into the python module. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** csv.py 3 Feb 2003 20:25:19 -0000 1.19 --- csv.py 5 Feb 2003 00:45:37 -0000 1.20 *************** *** 1,9 **** import _csv ! from _csv import Error __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", "Error", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", ! "unregister_dialect" ] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) --- 1,9 ---- import _csv ! from _csv import Error, __version__ __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", "Error", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", ! "unregister_dialect", "__version__" ] QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) From montanaro@users.sourceforge.net Wed Feb 5 01:49:58 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 17:49:58 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv28414 Modified Files: _csv.c Log Message: export QUOTE_* constants for use by csv.py Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _csv.c 4 Feb 2003 14:54:54 -0000 1.13 --- _csv.c 5 Feb 2003 01:49:54 -0000 1.14 *************** *** 143,146 **** --- 143,147 ---- } + #if 0 static void parse_prepend_char(ParserObj *self, char c) *************** *** 152,155 **** --- 153,157 ---- self->field_len++; } + #endif static void *************** *** 940,943 **** --- 942,947 ---- PyObject *dict; PyObject *rev; + PyObject *v; + int res; if (PyType_Ready(&Parser_Type) < 0) *************** *** 957,960 **** --- 961,996 ---- return; if (PyDict_SetItemString(dict, "__version__", rev) < 0) + return; + + v = PyInt_FromLong(QUOTE_MINIMAL); + if (v == NULL) + return; + res = PyDict_SetItemString(dict, "QUOTE_MINIMAL", v); + Py_DECREF(v); + if (res < 0) + return; + + v = PyInt_FromLong(QUOTE_ALL); + if (v == NULL) + return; + res = PyDict_SetItemString(dict, "QUOTE_ALL", v); + Py_DECREF(v); + if (res < 0) + return; + + v = PyInt_FromLong(QUOTE_NONNUMERIC); + if (v == NULL) + return; + res = PyDict_SetItemString(dict, "QUOTE_NONNUMERIC", v); + Py_DECREF(v); + if (res < 0) + return; + + v = PyInt_FromLong(QUOTE_NONE); + if (v == NULL) + return; + res = PyDict_SetItemString(dict, "QUOTE_NONE", v); + Py_DECREF(v); + if (res < 0) return; From montanaro@users.sourceforge.net Wed Feb 5 01:53:21 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 17:53:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv29985 Modified Files: csv.py Log Message: import QUOTE_* constants from low-level module Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** csv.py 5 Feb 2003 00:45:37 -0000 1.20 --- csv.py 5 Feb 2003 01:53:19 -0000 1.21 *************** *** 1,4 **** --- 1,5 ---- import _csv from _csv import Error, __version__ + from _csv import QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", *************** *** 6,11 **** "register_dialect", "get_dialect", "list_dialects", "unregister_dialect", "__version__" ] - - QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) _dialects = {} --- 7,10 ---- From montanaro@users.sourceforge.net Wed Feb 5 02:21:44 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 18:21:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv6964 Modified Files: csv.py Log Message: rearrange the Dialect class some more. I'm not sure this is the best way to do things. We can yank stuff out though. It gives us something to argue about. ;-) * Make the Dialect class patently invalid. * Put excel's settings in the excel class. * Add a _name attribute to Dialect which is filled in by register_dialect(). * Add a _validate method which is called from __init__. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** csv.py 5 Feb 2003 01:53:19 -0000 1.21 --- csv.py 5 Feb 2003 02:21:42 -0000 1.22 *************** *** 13,18 **** if not issubclass(dialect, Dialect): raise TypeError, "dialect not a subclass of Dialect" dialect._name = name ! _dialects[name] = dialect() def get_dialect(name): --- 13,21 ---- if not issubclass(dialect, Dialect): raise TypeError, "dialect not a subclass of Dialect" + if dialect == Dialect: + raise ValueError, "Dialect is an abstract class" + d = dialect() dialect._name = name ! _dialects[name] = d def get_dialect(name): *************** *** 27,40 **** class Dialect: _name = "" delimiter = ',' quotechar = '"' - escapechar = None doublequote = True skipinitialspace = False lineterminator = '\r\n' quoting = QUOTE_MINIMAL - - class excel(Dialect): - pass register_dialect("excel", excel) --- 30,73 ---- class Dialect: _name = "" + _valid = False + # placeholders + delimiter = None + quotechar = None + escapechar = None + doublequote = None + skipinitialspace = None + lineterminator = None + quoting = None + + def __init__(self): + if self.__class__ != Dialect: + self._valid = True + errors = self._validate() + if errors != []: + raise Error, "Dialect did not validate: %s" % ", ".join(errors) + + def _validate(self): + errors = [] + if not self._valid: + errors.append("can't directly instantiate Dialect class") + if self.delimiter is None: + errors.append("delimiter not set") + if self.quotechar is None: + errors.append("quotechar not set") + if self.lineterminator is None: + errors.append("lineterminator not set") + if self.doublequote not in (True, False): + errors.append("doublequote setting must be True or False") + if self.skipinitialspace not in (True, False): + errors.append("skipinitialspace setting must be True or False") + return errors + + class excel(Dialect): delimiter = ',' quotechar = '"' doublequote = True skipinitialspace = False lineterminator = '\r\n' quoting = QUOTE_MINIMAL register_dialect("excel", excel) From montanaro@users.sourceforge.net Wed Feb 5 02:22:12 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 04 Feb 2003 18:22:12 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv7157 Modified Files: test_csv.py Log Message: add a test for incomplete dialects Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_csv.py 4 Feb 2003 22:10:54 -0000 1.15 --- test_csv.py 5 Feb 2003 02:22:10 -0000 1.16 *************** *** 215,218 **** --- 215,223 ---- "myexceltsv", myexceltsv) + def test_incomplete_dialect(self): + class myexceltsv(csv.Dialect): + delimiter = "\t" + self.assertRaises(csv.Error, myexceltsv) + def test_dialect_class(self): class myexceltsv(csv.excel): From andrewmcnamara@users.sourceforge.net Wed Feb 5 03:20:54 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Tue, 04 Feb 2003 19:20:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv24979 Modified Files: _csv.c Log Message: Raise an exception if quotechar is None and quoting attribute is set to a value that requires a quotechar. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** _csv.c 5 Feb 2003 01:49:54 -0000 1.14 --- _csv.c 5 Feb 2003 03:20:51 -0000 1.15 *************** *** 736,739 **** --- 736,743 ---- return -1; } + if (!self->have_quotechar && n != QUOTE_NONE) { + PyErr_BadArgument(); + return -1; + } if (n == QUOTE_NONE) self->have_quotechar = 0; From andrewmcnamara@users.sourceforge.net Wed Feb 5 03:21:42 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Tue, 04 Feb 2003 19:21:42 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv25230/test Modified Files: test_csv.py Log Message: Added a bunch of tests to get better coverage of the underlying _csv module. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_csv.py 5 Feb 2003 02:22:10 -0000 1.16 --- test_csv.py 5 Feb 2003 03:21:39 -0000 1.17 *************** *** 6,9 **** --- 6,125 ---- from StringIO import StringIO import csv + import _csv + + class Test_Csv(unittest.TestCase): + """ + Test the underlying C csv parser in ways that are not appropriate + from the high level interface. + """ + def test_init(self): + "test that the module returns a parser" + parser = _csv.parser() + self.failUnless(hasattr(parser, 'parse')) + + def test_parameter_validation(self): + self.assertRaises(TypeError, _csv.parser, FlibbleWort = 0) + self.assertRaises(ValueError, _csv.parser, quoting = -1) + self.assertRaises(ValueError, _csv.parser, quoting = csv.QUOTE_NONE + 1) + self.assertRaises(TypeError, _csv.parser, delimiter = None) + self.assertRaises(TypeError, _csv.parser, skipinitialspace = None) + + def test_parameter(self): + parser = _csv.parser(delimiter = "\t") + self.assertEqual(parser.delimiter, "\t") + + parser = _csv.parser(quotechar = "'") + self.assertEqual(parser.quotechar, "'") + + parser = _csv.parser(quoting = csv.QUOTE_NONE) + self.assertEqual(parser.quotechar, None) + + parser = _csv.parser(quotechar=None,quoting=csv.QUOTE_ALL) + self.assertEqual(parser.quoting, csv.QUOTE_NONE) + + def test_attr_validation(self): + parser = _csv.parser() + self.assertRaises(AttributeError, delattr, parser, 'quoting') + self.assertRaises(TypeError, setattr, parser, 'quoting', -1) + self.assertRaises(TypeError, setattr, parser, 'quoting', + csv.QUOTE_NONE + 1) + self.assertRaises(TypeError, setattr, parser, 'quotechar', 0) + self.assertRaises(TypeError, setattr, parser, 'escapechar', 0) + parser.quotechar=None + self.assertRaises(TypeError, setattr, parser, 'quoting', 1) + self.assertRaises(TypeError, setattr, parser, 'lineterminator', None) + + def test_setattr(self): + parser = _csv.parser() + parser.delimiter = "\t" + self.assertEqual(parser.delimiter, "\t") + + parser = _csv.parser() + parser.quotechar = "'" + self.assertEqual(parser.quotechar, "'") + + parser = _csv.parser() + parser.quoting = csv.QUOTE_NONE + self.assertEqual(parser.quotechar, None) + + def test_join_bigfield(self): + # This exercises the buffer realloc functionality + parser = _csv.parser() + bigstring = 'X' * 50000 + result = parser.join([bigstring,bigstring]) + self.assertEqual(result, '%s,%s%s' % \ + (bigstring, bigstring, parser.lineterminator)) + + def test_join_quoting(self): + parser = _csv.parser() + self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') + parser = _csv.parser(quoting = csv.QUOTE_NONE) + self.assertRaises(_csv.Error, parser.join, ['a','1','p,q']) + parser = _csv.parser(quoting = csv.QUOTE_MINIMAL) + self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') + parser = _csv.parser(quoting = csv.QUOTE_NONNUMERIC) + self.assertEqual(parser.join(['a','1','p,q']), '"a",1,"p,q"\r\n') + parser = _csv.parser(quoting = csv.QUOTE_ALL) + self.assertEqual(parser.join(['a','1','p,q']), '"a","1","p,q"\r\n') + + def test_join_escape(self): + parser = _csv.parser(escapechar='\\') + self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') + parser.doublequote = 0 + # FAIL - need to fix + # self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') + parser.quotechar = None + self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') + + def test_parse(self): + parser = _csv.parser() + self.assertRaises(TypeError, parser.parse, None) + self.assertEqual(parser.parse(''), []) + + def test_parse_eol(self): + parser = _csv.parser() + self.assertEqual(parser.parse('a,b'), ['a','b']) + self.assertEqual(parser.parse('a,b\n'), ['a','b']) + self.assertEqual(parser.parse('a,b\r\n'), ['a','b']) + self.assertEqual(parser.parse('a,b\r'), ['a','b']) + self.assertRaises(csv.Error, parser.parse, 'a,b\rc,d') + self.assertRaises(csv.Error, parser.parse, 'a,b\nc,d') + self.assertRaises(csv.Error, parser.parse, 'a,b\r\nc,d') + + def test_parse_escape(self): + parser = _csv.parser(escapechar='\\') + self.assertEqual(parser.parse('a,\\b,c'), ['a', '\\b', 'c']) + self.assertEqual(parser.parse('a,b\\,c'), ['a', 'b,c']) + self.assertEqual(parser.parse('a,"b\\,c"'), ['a', 'b,c']) + self.assertEqual(parser.parse('a,"b,\\c"'), ['a', 'b,\\c']) + self.assertEqual(parser.parse('a,"b,c\\""'), ['a', 'b,c"']) + self.assertEqual(parser.parse('a,"b,c"\\'), ['a', 'b,c\\']) + + def test_parse_bigfield(self): + # This exercises the buffer realloc functionality + parser = _csv.parser() + bigstring = 'X' * 50000 + bigline = '%s,%s%s' % (bigstring, bigstring, parser.lineterminator) + self.assertEqual(parser.parse(bigline), [bigstring, bigstring]) class TestCsvBase(unittest.TestCase): From tim_one@users.sourceforge.net Wed Feb 5 03:46:19 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 19:46:19 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.125,2.126 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv32596/Modules Modified Files: cPickle.c Log Message: Typo repair. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.125 retrieving revision 2.126 diff -C2 -d -r2.125 -r2.126 *** cPickle.c 4 Feb 2003 21:47:44 -0000 2.125 --- cPickle.c 5 Feb 2003 03:46:17 -0000 2.126 *************** *** 1481,1485 **** /* A helper for save_tuple. Push the len elements in tuple t on the stack. */ static int ! store_tuple_elememts(Picklerobject *self, PyObject *t, int len) { int i; --- 1481,1485 ---- /* A helper for save_tuple. Push the len elements in tuple t on the stack. */ static int ! store_tuple_elements(Picklerobject *self, PyObject *t, int len) { int i; *************** *** 1504,1508 **** /* Tuples are ubiquitous in the pickle protocols, so many techniques are * used across protocols to minimize the space needed to pickle them. ! * Tuples are also the only builtin immuatable type that can be recursive * (a tuple can be reached from itself), and that requires some subtle * magic so that it works in all cases. IOW, this is a long routine. --- 1504,1508 ---- /* Tuples are ubiquitous in the pickle protocols, so many techniques are * used across protocols to minimize the space needed to pickle them. ! * Tuples are also the only builtin immutable type that can be recursive * (a tuple can be reached from itself), and that requires some subtle * magic so that it works in all cases. IOW, this is a long routine. *************** *** 1554,1558 **** if (len <= 3 && self->proto >= 2) { /* Use TUPLE{1,2,3} opcodes. */ ! if (store_tuple_elememts(self, args, len) < 0) goto finally; if (PyDict_GetItem(self->memo, py_tuple_id)) { --- 1554,1558 ---- if (len <= 3 && self->proto >= 2) { /* Use TUPLE{1,2,3} opcodes. */ ! if (store_tuple_elements(self, args, len) < 0) goto finally; if (PyDict_GetItem(self->memo, py_tuple_id)) { *************** *** 1579,1583 **** goto finally; ! if (store_tuple_elememts(self, args, len) < 0) goto finally; --- 1579,1583 ---- goto finally; ! if (store_tuple_elements(self, args, len) < 0) goto finally; From tim_one@users.sourceforge.net Wed Feb 5 03:53:13 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 19:53:13 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.126,2.127 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2551/Modules Modified Files: cPickle.c Log Message: More typo repair. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.126 retrieving revision 2.127 diff -C2 -d -r2.126 -r2.127 *** cPickle.c 5 Feb 2003 03:46:17 -0000 2.126 --- cPickle.c 5 Feb 2003 03:53:10 -0000 2.127 *************** *** 1960,1964 **** if (!PyInt_Check(py_code)) { cPickle_ErrFormat(PicklingError, "Can't pickle %s: " ! "extension code %s isn't n integer", "OO", args, py_code); goto finally; --- 1960,1964 ---- if (!PyInt_Check(py_code)) { cPickle_ErrFormat(PicklingError, "Can't pickle %s: " ! "extension code %s isn't an integer", "OO", args, py_code); goto finally; From tim_one@users.sourceforge.net Wed Feb 5 04:08:19 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 04 Feb 2003 20:08:19 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv7682/Lib/test Modified Files: test_datetime.py Log Message: Build pickler_choices list in a lazier way. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** test_datetime.py 3 Feb 2003 01:32:33 -0000 1.34 --- test_datetime.py 5 Feb 2003 04:08:07 -0000 1.35 *************** *** 17,36 **** from datetime import date, datetime ! ! pickle_choices = [ ! (pickle, pickle, 0), ! (pickle, pickle, 1), ! (pickle, pickle, 2), ! (cPickle, cPickle, 0), ! (cPickle, cPickle, 1), ! (cPickle, cPickle, 2), ! (pickle, cPickle, 0), ! (pickle, cPickle, 1), ! (pickle, cPickle, 2), ! (cPickle, pickle, 0), ! (cPickle, pickle, 1), ! (cPickle, pickle, 2), ! ] ! # XXX The test suite uncovered a bug in Python 2.2.2: if x and y are --- 17,25 ---- from datetime import date, datetime ! pickle_choices = [(pickler, unpickler, proto) ! for pickler in pickle, cPickle ! for unpickler in pickle, cPickle ! for proto in range(3)] ! assert len(pickle_choices) == 2*2*3 # XXX The test suite uncovered a bug in Python 2.2.2: if x and y are From rhettinger@users.sourceforge.net Wed Feb 5 04:12:44 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 04 Feb 2003 20:12:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb dbobj.py,1.3,1.4 dbshelve.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb In directory sc8-pr-cvs1:/tmp/cvs-serv8663 Modified Files: dbobj.py dbshelve.py Log Message: SF patch #674396: Apply UserDict.DictMixin to expand dbshelve and dbojb to have a full dictionary interface. Index: dbobj.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbobj.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** dbobj.py 30 Dec 2002 20:52:07 -0000 1.3 --- dbobj.py 5 Feb 2003 04:12:41 -0000 1.4 *************** *** 17,20 **** --- 17,21 ---- import db + from UserDict import DictMixin class DBEnv: *************** *** 86,90 **** ! class DB: def __init__(self, dbenv, *args, **kwargs): # give it the proper DBEnv C object that its expecting --- 87,91 ---- ! class DB(DictMixin): def __init__(self, dbenv, *args, **kwargs): # give it the proper DBEnv C object that its expecting Index: dbshelve.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbshelve.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** dbshelve.py 28 Jan 2003 17:20:42 -0000 1.5 --- dbshelve.py 5 Feb 2003 04:12:41 -0000 1.6 *************** *** 31,34 **** --- 31,35 ---- import cPickle + from UserDict import DictMixin try: # For Python 2.3 *************** *** 76,80 **** #--------------------------------------------------------------------------- ! class DBShelf: """ A shelf to hold pickled objects, built upon a bsddb DB object. It --- 77,81 ---- #--------------------------------------------------------------------------- ! class DBShelf(DictMixin): """ A shelf to hold pickled objects, built upon a bsddb DB object. It From andrea" ------=_NextPart_000_00D6_16E36C1E.E3312C73 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: base64 KiBSZWR1Y2UgdGhlIGFtb3VudCBvZiBzbGVlcCB5b3UgbmVlZA0KKiBDYXVz ZSB3b3VuZHMgdG8gaGVhbCBmYXN0ZXINCiogTG9zZSB3ZWlnaHQgd2hpbGUg eW91ciBzbGVlcGluZw0KKiBCZWNvbWUgbGVzcyB3aW5kZWQgd2hlbiBleGNl cnNpemluZw0KKiBQdXQgY29sb3IgYmFjayBpbiBncmV5IGhhaXINCiogR3Jv dyBoYWlyIGJhY2sgd2hlcmUgaXQgaGFkIG9uY2UgZmFsbGVuIG91dA0KKiBU aWdodGVuIHNraW4NCiogU3RyZW5ndGhlbiBib25lcw0KKiBCb2R5IGJ1aWxk ZXJzIC0gdXNlIHRoaXMgdG8gYnVpbGQgeW91ciBtdXNjbGVzIHF1aWNrZXIN Ci4uLi4uLi4uLi5UaGUgTGlzdCB0cnVseSBnb2VzIG9uIGFuZCBvbi4uLi4u Li4uLi4NCg0KQXMgc2VlbiBvbiBOQkMsIENCUywgQ05OLCBhbmQgT3ByYWgh IFRoZSBoZWFsdGggZGlzY292ZXJ5IA0KdGhhdCBhY3R1YWxseSByZXZlcnNl cyBhZ2luZyBzeW1wdG9tcyB3aXRob3V0IGRpZXRpbmcgb3IgZXhlcmNpc2Uh IA0KVGhpcyBQUk9WRU4gZGlzY292ZXJ5IGhhcyBiZWVuIHJlcG9ydGVkIG9u IGJ5IHRoZSANCk5ldyBFbmdsYW5kIEpvdXJuYWwgb2YgTWVkaWNpbmUgLSBk b24ndCBqdXN0IHRha2Ugb3VyIHdvcmQgZm9yIGl0Lg0KDQpJbiBmYWN0IHdl J2QgbGlrZSB5b3UgdG8gcmVjZWl2ZSBhIEYuUi5FLkUgdGhpcnR5IGRheSBz dXBwbHk7IGxvb2sgYW5kIGZlZWwgDQp5b3VuZ2VyLCBsb3NlIHdlaWdodCwg cmVkdWNlIHNsZWVwLCBUaGUgbGlzdCBnb2VzIG9uLCB3ZSANCmVuY291cmFn ZSB5b3UgdG8gYXQgbGVhc3QgdGFrZSBhIGxvb2sgYXQgdGhlIGluZm9ybWF0 aW9uIGFzIHRvDQp3aGF0IGVsc2UgaXQgY2FuIGRvDQoNCmh0dHA6Ly9oaWRk ZW4uY29tLm1zLXNjcmlwdC42NTE2ODUuOTg3MzY2MS0wMzMyMTk4NzYzNTEz NTMxODQxLmVuY29kZS4zMzM3MTgxNTA3NDYwNTU2NC5lbHNlLjE0MDU1ODYz NzIwMjU4OTQ2MzAyMTU1MDYzNzMyLm1zL3d3dy5ncm93eW91bmcuY29tLz9s aWZlcw0KDQoNCjc3OTB5RmFpNy01OTJCd3BtNzA3N3dNbXQ0LTgzM2tBWnYz MjU1bDM2 From davecole@users.sourceforge.net Wed Feb 5 10:30:09 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Wed, 05 Feb 2003 02:30:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30447 Modified Files: _csv.c Log Message: Replace the cut & paste QUOTE_* code in module init with a loop. Removed the have_quotechar attribute and use quoting == QUOTE_NONE instead. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** _csv.c 5 Feb 2003 03:20:51 -0000 1.15 --- _csv.c 5 Feb 2003 10:30:06 -0000 1.16 *************** *** 50,58 **** typedef struct { PyObject_HEAD int doublequote; /* is " represented by ""? */ char delimiter; /* field separator */ - int have_quotechar; /* is a quotechar defined */ char quotechar; /* quote character */ int have_escapechar; /* is an escapechar defined */ --- 50,70 ---- typedef struct { + QuoteStyle style; + char *name; + } StyleDesc; + + static StyleDesc quote_styles[] = { + { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, + { QUOTE_ALL, "QUOTE_ALL" }, + { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, + { QUOTE_NONE, "QUOTE_NONE" }, + { 0 } + }; + + typedef struct { PyObject_HEAD int doublequote; /* is " represented by ""? */ char delimiter; /* field separator */ char quotechar; /* quote character */ int have_escapechar; /* is an escapechar defined */ *************** *** 262,266 **** case QUOTE_IN_QUOTED_FIELD: /* doublequote - seen a quote in an quoted field */ ! if (self->have_quotechar && c == self->quotechar) { /* save "" as " */ parse_add_char(self, c); --- 274,278 ---- case QUOTE_IN_QUOTED_FIELD: /* doublequote - seen a quote in an quoted field */ ! if (self->quoting != QUOTE_NONE && c == self->quotechar) { /* save "" as " */ parse_add_char(self, c); *************** *** 447,451 **** * quote. */ ! if (self->have_quotechar && c == self->quotechar && self->doublequote) { if (copy_phase) --- 459,463 ---- * quote. */ ! if (self->quoting != QUOTE_NONE && c == self->quotechar && self->doublequote) { if (copy_phase) *************** *** 464,469 **** && (c == self->delimiter || c == self->escapechar || c == '\n' || c == '\r')) { ! if (self->have_quotechar ! && self->quoting != QUOTE_NONE) *quoted = 1; else if (self->escapechar) { --- 476,480 ---- && (c == self->delimiter || c == self->escapechar || c == '\n' || c == '\r')) { ! if (self->quoting != QUOTE_NONE) *quoted = 1; else if (self->escapechar) { *************** *** 486,491 **** /* If field is empty check if it needs to be quoted. */ ! if (i == 0 && quote_empty && self->have_quotechar) ! *quoted = 1; /* Handle final quote character on field. --- 497,507 ---- /* If field is empty check if it needs to be quoted. */ ! if (i == 0 && quote_empty) { ! if (self->quoting == QUOTE_NONE) { ! raise_exception("single empty field record must be quoted"); ! return -1; ! } else ! *quoted = 1; ! } /* Handle final quote character on field. *************** *** 679,684 **** PyObject *rv; ! if ((strcmp(name, "quotechar") == 0 && !self->have_quotechar) ! || (strcmp(name, "escapechar") == 0 && !self->have_escapechar)) { Py_INCREF(Py_None); return Py_None; --- 695,699 ---- PyObject *rv; ! if (strcmp(name, "escapechar") == 0 && !self->have_escapechar) { Py_INCREF(Py_None); return Py_None; *************** *** 723,730 **** return -1; } ! if (strcmp(name, "quotechar") == 0) ! return _set_char_attr(&self->quotechar, ! &self->have_quotechar, v); ! else if (strcmp(name, "escapechar") == 0) return _set_char_attr(&self->escapechar, &self->have_escapechar, v); --- 738,742 ---- return -1; } ! if (strcmp(name, "escapechar") == 0) return _set_char_attr(&self->escapechar, &self->have_escapechar, v); *************** *** 736,745 **** return -1; } - if (!self->have_quotechar && n != QUOTE_NONE) { - PyErr_BadArgument(); - return -1; - } - if (n == QUOTE_NONE) - self->have_quotechar = 0; self->quoting = n; return 0; --- 748,751 ---- *************** *** 834,838 **** NULL }; ! PyObject *quotechar, *escapechar; ParserObj *self = PyObject_NEW(ParserObj, &Parser_Type); --- 840,844 ---- NULL }; ! PyObject *escapechar; ParserObj *self = PyObject_NEW(ParserObj, &Parser_Type); *************** *** 841,845 **** self->quotechar = '"'; - self->have_quotechar = 1; self->delimiter = ','; self->escapechar = '\0'; --- 847,850 ---- *************** *** 869,882 **** self->num_fields = 0; ! quotechar = escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|OcOiSiiii", keywords, ! "echar, &self->delimiter, &escapechar, &self->skipinitialspace, &self->lineterminator, &self->quoting, &self->doublequote, &self->autoclear, &self->strict) - && !_set_char_attr(&self->quotechar, - &self->have_quotechar, quotechar) && !_set_char_attr(&self->escapechar, &self->have_escapechar, escapechar)) { --- 874,885 ---- self->num_fields = 0; ! escapechar = NULL; ! if (PyArg_ParseTupleAndKeywords(args, keyword_args, "|ccOiSiiii", keywords, ! &self->quotechar, &self->delimiter, &escapechar, &self->skipinitialspace, &self->lineterminator, &self->quoting, &self->doublequote, &self->autoclear, &self->strict) && !_set_char_attr(&self->escapechar, &self->have_escapechar, escapechar)) { *************** *** 889,899 **** if (self->quoting < 0 || self->quoting > QUOTE_NONE) PyErr_SetString(PyExc_ValueError, "bad quoting value"); ! else { ! if (self->quoting == QUOTE_NONE) ! self->have_quotechar = 0; ! else if (!self->have_quotechar) ! self->quoting = QUOTE_NONE; return (PyObject*)self; - } } --- 892,897 ---- if (self->quoting < 0 || self->quoting > QUOTE_NONE) PyErr_SetString(PyExc_ValueError, "bad quoting value"); ! else return (PyObject*)self; } *************** *** 948,951 **** --- 946,950 ---- PyObject *v; int res; + StyleDesc *style; if (PyType_Ready(&Parser_Type) < 0) *************** *** 967,1001 **** return; ! v = PyInt_FromLong(QUOTE_MINIMAL); ! if (v == NULL) ! return; ! res = PyDict_SetItemString(dict, "QUOTE_MINIMAL", v); ! Py_DECREF(v); ! if (res < 0) ! return; ! ! v = PyInt_FromLong(QUOTE_ALL); ! if (v == NULL) ! return; ! res = PyDict_SetItemString(dict, "QUOTE_ALL", v); ! Py_DECREF(v); ! if (res < 0) ! return; ! ! v = PyInt_FromLong(QUOTE_NONNUMERIC); ! if (v == NULL) ! return; ! res = PyDict_SetItemString(dict, "QUOTE_NONNUMERIC", v); ! Py_DECREF(v); ! if (res < 0) ! return; ! ! v = PyInt_FromLong(QUOTE_NONE); ! if (v == NULL) ! return; ! res = PyDict_SetItemString(dict, "QUOTE_NONE", v); ! Py_DECREF(v); ! if (res < 0) ! return; /* Add the CSV exception object to the module. */ --- 966,979 ---- return; ! /* Add quote styles into disctionary */ ! for (style = quote_styles; style->name; style++) { ! v = PyInt_FromLong(style->style); ! if (v == NULL) ! return; ! res = PyDict_SetItemString(dict, style->name, v); ! Py_DECREF(v); ! if (res < 0) ! return; ! } /* Add the CSV exception object to the module. */ From jackjansen@users.sourceforge.net Wed Feb 5 11:14:18 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 03:14:18 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_macostools.py,1.2,1.3 test_macfs.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12602 Modified Files: test_macostools.py test_macfs.py Log Message: Use os.path.realpath() in stead of abspath(), so the tests don't fail if we have a symlink somewhere in the TESTFN path. Index: test_macostools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_macostools.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_macostools.py 28 Jan 2003 23:54:05 -0000 1.2 --- test_macostools.py 5 Feb 2003 11:14:15 -0000 1.3 *************** *** 69,73 **** macostools.mkalias(test_support.TESTFN, TESTFN2) fss, _, _ = macfs.ResolveAliasFile(TESTFN2) ! self.assertEqual(fss.as_pathname(), os.path.abspath(test_support.TESTFN)) def test_mkalias_relative(self): --- 69,73 ---- macostools.mkalias(test_support.TESTFN, TESTFN2) fss, _, _ = macfs.ResolveAliasFile(TESTFN2) ! self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) def test_mkalias_relative(self): *************** *** 78,82 **** macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) fss, _, _ = macfs.ResolveAliasFile(TESTFN2) ! self.assertEqual(fss.as_pathname(), os.path.abspath(test_support.TESTFN)) --- 78,82 ---- macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) fss, _, _ = macfs.ResolveAliasFile(TESTFN2) ! self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) Index: test_macfs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_macfs.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_macfs.py 28 Jan 2003 21:39:28 -0000 1.1 --- test_macfs.py 5 Feb 2003 11:14:16 -0000 1.2 *************** *** 22,30 **** def test_fsspec(self): fss = macfs.FSSpec(test_support.TESTFN) ! self.assertEqual(os.path.abspath(test_support.TESTFN), fss.as_pathname()) def test_fsref(self): fsr = macfs.FSRef(test_support.TESTFN) ! self.assertEqual(os.path.abspath(test_support.TESTFN), fsr.as_pathname()) def test_coercion(self): --- 22,30 ---- def test_fsspec(self): fss = macfs.FSSpec(test_support.TESTFN) ! self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname()) def test_fsref(self): fsr = macfs.FSRef(test_support.TESTFN) ! self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname()) def test_coercion(self): From jackjansen@users.sourceforge.net Wed Feb 5 13:36:32 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 05:36:32 -0800 Subject: [Python-checkins] python/dist/src/Mac/Build PythonCore.mcp,1.42,1.43 PythonStandSmall.mcp,1.48,1.49 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Build In directory sc8-pr-cvs1:/tmp/cvs-serv982 Modified Files: PythonCore.mcp PythonStandSmall.mcp Log Message: Added itertools module. Index: PythonCore.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonCore.mcp,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 Binary files /tmp/cvsofBHns and /tmp/cvs6dlIcM differ Index: PythonStandSmall.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonStandSmall.mcp,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 Binary files /tmp/cvs0BdQWI and /tmp/cvs4Qs1ti differ From jackjansen@users.sourceforge.net Wed Feb 5 13:36:52 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 05:36:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules macconfig.c,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv1228 Modified Files: macconfig.c Log Message: Added itertools module. Index: macconfig.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/macconfig.c,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** macconfig.c 30 Dec 2002 23:11:30 -0000 1.37 --- macconfig.c 5 Feb 2003 13:36:50 -0000 1.38 *************** *** 178,181 **** --- 178,182 ---- extern void initxreadlines(); extern void initzipimport(); + extern void inititertools(); /* -- ADDMODULE MARKER 1 -- */ *************** *** 302,305 **** --- 303,307 ---- {"xreadlines", initxreadlines}, {"zipimport", initzipimport}, + {"itertools", inititertools}, /* -- ADDMODULE MARKER 2 -- */ From jackjansen@users.sourceforge.net Wed Feb 5 13:39:07 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 05:39:07 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac buildtools.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv2325 Modified Files: buildtools.py Log Message: Fixed a few typos, and changed FSCreateResourceFile filename argument to unicode. Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** buildtools.py 2 Feb 2003 23:03:50 -0000 1.3 --- buildtools.py 5 Feb 2003 13:39:04 -0000 1.4 *************** *** 55,59 **** file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1) break ! except (Carbon.File.error, ValueError): continue else: --- 55,59 ---- file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1) break ! except (Carbon.File.Error, ValueError): continue else: *************** *** 176,180 **** except MacOS.Error: destdir, destfile = os.path.split(destname) ! Res.FSCreateResourceFile(destdir, destfile, RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) --- 176,180 ---- except MacOS.Error: destdir, destfile = os.path.split(destname) ! Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) *************** *** 262,266 **** # Now set the creator, type and bundle bit of the destination. # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) ! dset_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype --- 262,266 ---- # Now set the creator, type and bundle bit of the destination. # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) ! dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype From jlt63@users.sourceforge.net Wed Feb 5 15:16:21 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:16:21 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.142,1.143 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv13582 Modified Files: setup.py Log Message: This patch reverts the following: It also prevents building against the real X headers, if installed. After discussions with the Cygwin project lead, I believe that building against the real X headers is OK. Especially, since the psuedo-X headers are *not* installed by the Cygwin Tcl/Tk binary package. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.142 retrieving revision 1.143 diff -C2 -d -r1.142 -r1.143 *** setup.py 5 Feb 2003 15:06:46 -0000 1.142 --- setup.py 5 Feb 2003 15:16:17 -0000 1.143 *************** *** 954,962 **** include_dirs.append('/usr/openwin/include') added_lib_dirs.append('/usr/openwin/lib') - elif platform == 'cygwin': - # Verify that the pseudo-X headers are installed before proceeding - x11_inc = find_file('X11/Xlib.h', [], inc_dirs) - if x11_inc is None: - return elif os.path.exists('/usr/X11R6/include'): include_dirs.append('/usr/X11R6/include') --- 954,957 ---- *************** *** 969,972 **** --- 964,973 ---- include_dirs.append('/usr/X11/include') added_lib_dirs.append('/usr/X11/lib') + + # If Cygwin, then verify that X is installed before proceeding + if platform == 'cygwin': + x11_inc = find_file('X11/Xlib.h', [], include_dirs) + if x11_inc is None: + return # Check for BLT extension From jlt63@users.sourceforge.net Wed Feb 5 15:06:54 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:06:54 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.141,1.142 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv7952 Modified Files: setup.py Log Message: This patch enables Cygwin Python to build _tkinter against Tcl/Tk 8.4. Note that this patch just reverts the lib_prefix (i.e., "cyg") portion of my Tcl/Tk 8.3 patch. It seems that Cygwin Tcl/Tk is using a more normal file naming convention again. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.141 retrieving revision 1.142 diff -C2 -d -r1.141 -r1.142 *** setup.py 2 Feb 2003 17:59:05 -0000 1.141 --- setup.py 5 Feb 2003 15:06:46 -0000 1.142 *************** *** 916,925 **** return - # Set platform specific library prefix, if any - if platform == 'cygwin': - lib_prefix = 'cyg' - else: - lib_prefix = '' - # Assume we haven't found any of the libraries or include files # The versions with dots are used on Unix, and the versions without --- 916,919 ---- *************** *** 928,935 **** for version in ['8.4', '84', '8.3', '83', '8.2', '82', '8.1', '81', '8.0', '80']: ! tklib = self.compiler.find_library_file(lib_dirs, ! lib_prefix + 'tk' + version) ! tcllib = self.compiler.find_library_file(lib_dirs, ! lib_prefix + 'tcl' + version) if tklib and tcllib: # Exit the loop when we've found the Tcl/Tk libraries --- 922,927 ---- for version in ['8.4', '84', '8.3', '83', '8.2', '82', '8.1', '81', '8.0', '80']: ! tklib = self.compiler.find_library_file(lib_dirs, 'tk' + version) ! tcllib = self.compiler.find_library_file(lib_dirs, 'tcl' + version) if tklib and tcllib: # Exit the loop when we've found the Tcl/Tk libraries *************** *** 989,994 **** # Add the Tcl/Tk libraries ! libs.append(lib_prefix + 'tk'+ version) ! libs.append(lib_prefix + 'tcl'+ version) if platform in ['aix3', 'aix4']: --- 981,986 ---- # Add the Tcl/Tk libraries ! libs.append('tk'+ version) ! libs.append('tcl'+ version) if platform in ['aix3', 'aix4']: From jackjansen@users.sourceforge.net Wed Feb 5 15:40:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:40:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE Wbase.py,1.11,1.12 Wtext.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv27987 Modified Files: Wbase.py Wtext.py Log Message: Cast various floats to ints so we don't get warnings. Index: Wbase.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wbase.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Wbase.py 30 Nov 2002 00:01:27 -0000 1.11 --- Wbase.py 5 Feb 2003 15:40:04 -0000 1.12 *************** *** 402,406 **** def _darkencolor((r, g, b)): ! return 0.75 * r, 0.75 * g, 0.75 * b class BevelBox(Widget): --- 402,406 ---- def _darkencolor((r, g, b)): ! return int(0.75 * r), int(0.75 * g), int(0.75 * b) class BevelBox(Widget): Index: Wtext.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wtext.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** Wtext.py 30 Nov 2002 00:01:28 -0000 1.18 --- Wtext.py 5 Feb 2003 15:40:05 -0000 1.19 *************** *** 530,533 **** --- 530,534 ---- delta = min(maxdelta, delta) delta = max(mindelta, delta) + delta = int(delta) self.ted.WEScroll(0, delta) self.updatescrollbars() *************** *** 557,560 **** --- 558,562 ---- delta = min(maxdelta, delta) delta = max(mindelta, delta) + delta = int(delta) self.ted.WEScroll(delta, 0) self.updatescrollbars() From jackjansen@users.sourceforge.net Wed Feb 5 15:41:26 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:41:26 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PythonIDEMain.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv28271 Modified Files: PythonIDEMain.py Log Message: Added "Open File by Name" command which presens a filename dialog. If the clipboard contains a filename that filename is used as the default. Index: PythonIDEMain.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PythonIDEMain.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** PythonIDEMain.py 26 Jan 2003 22:15:48 -0000 1.25 --- PythonIDEMain.py 5 Feb 2003 15:41:09 -0000 1.26 *************** *** 71,74 **** --- 71,75 ---- newitem = FrameWork.MenuItem(m, "New", "N", 'new') openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') + openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') *************** *** 208,211 **** --- 209,228 ---- def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) + if filename: + self.openscript(filename) + + def domenu_openbyname(self, *args): + # Open a file by name. If the clipboard contains a filename + # use that as the default. + from Carbon import Scrap + try: + sc = Scrap.GetCurrentScrap() + dft = sc.GetScrapFlavorData("TEXT") + except Scrap.Error: + dft = "" + else: + if not os.path.exists(dft): + dft = "" + filename = EasyDialogs.AskString("Open File Named:", default=dft, ok="Open") if filename: self.openscript(filename) From jackjansen@users.sourceforge.net Wed Feb 5 15:49:22 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:49:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac ic.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv31640 Modified Files: ic.py Log Message: Getting rid of macfs and FSSpecs. Index: ic.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/ic.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ic.py 30 Dec 2002 22:04:20 -0000 1.1 --- ic.py 5 Feb 2003 15:49:19 -0000 1.2 *************** *** 4,8 **** --- 4,10 ---- import string import sys + import os from Carbon import Res + import Carbon.File import macfs import macostools *************** *** 217,227 **** def settypecreator(self, file): ! if type(file) == type(''): ! fss = macfs.FSSpec(file) ! else: ! fss = file ! name = fss.as_tuple()[2] ! record = self.mapfile(name) ! fss.SetCreatorType(record[2], record[1]) macostools.touched(fss) --- 219,225 ---- def settypecreator(self, file): ! file = Carbon.File.pathname(file) ! record = self.mapfile(os.path.split(file)[1]) ! MacOS.SetCreatorAndType(file, record[2], record[1]) macostools.touched(fss) From jackjansen@users.sourceforge.net Wed Feb 5 15:44:06 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 07:44:06 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac cfmfile.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv29618 Modified Files: cfmfile.py Log Message: Got rid of macfs Index: cfmfile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/cfmfile.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** cfmfile.py 30 Dec 2002 22:04:20 -0000 1.1 --- cfmfile.py 5 Feb 2003 15:44:03 -0000 1.2 *************** *** 6,10 **** __author__ = "jvr" ! import macfs import struct from Carbon import Res --- 6,10 ---- __author__ = "jvr" ! import Carbon.File import struct from Carbon import Res *************** *** 29,36 **** srclist = list(srclist) for i in range(len(srclist)): ! if type(srclist[i]) == macfs.FSSpecType: ! srclist[i] = srclist[i].as_pathname() ! if type(dst) == macfs.FSSpecType: ! dst = dst.as_pathname() dstfile = open(dst, "wb") --- 29,34 ---- srclist = list(srclist) for i in range(len(srclist)): ! srclist[i] = Carbon.File.pathname(srclist[i]) ! dst = Carbon.File.pathname(dst) dstfile = open(dst, "wb") From jlt63@users.sourceforge.net Wed Feb 5 16:46:04 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Wed, 05 Feb 2003 08:46:04 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.122,1.123 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23501 Modified Files: regrtest.py Log Message: Patch #551977: Regression exceptions for cygwin Applied the skip test_ossaudiodev patch. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.122 retrieving revision 1.123 diff -C2 -d -r1.122 -r1.123 *** regrtest.py 3 Feb 2003 15:19:27 -0000 1.122 --- regrtest.py 5 Feb 2003 16:46:01 -0000 1.123 *************** *** 869,872 **** --- 869,873 ---- test_mpz test_nis + test_ossaudiodev test_socketserver test_sunaudiodev From tim_one@users.sourceforge.net Wed Feb 5 18:29:35 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 10:29:35 -0800 Subject: [Python-checkins] python/dist/src/Lib repr.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv15673/Lib Modified Files: repr.py Log Message: [680789] Debug with long array takes forever Added array.array to the types repr.py knows about, after a suggestion from Jurjen N.E. Bos. Index: repr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/repr.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** repr.py 29 Oct 2001 22:25:44 -0000 1.14 --- repr.py 5 Feb 2003 18:29:33 -0000 1.15 *************** *** 8,11 **** --- 8,12 ---- self.maxtuple = 6 self.maxlist = 6 + self.maxarray = 5 self.maxdict = 4 self.maxstring = 30 *************** *** 49,52 **** --- 50,70 ---- if n > self.maxlist: s = s + ', ...' return '[' + s + ']' + + def repr_array(self, x, level): + n = len(x) + header = "array('%s', [" % x.typecode + if n == 0: + return header + "])" + if level <= 0: + return header + "...])" + s = '' + for i in range(min(n, self.maxarray)): + if s: + s += ', ' + s += self.repr1(x[i], level-1) + if n > self.maxarray: + s += ', ...' + return header + s + "])" + def repr_dict(self, x, level): n = len(x) From tim_one@users.sourceforge.net Wed Feb 5 18:29:36 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 10:29:36 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_repr.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15673/Lib/test Modified Files: test_repr.py Log Message: [680789] Debug with long array takes forever Added array.array to the types repr.py knows about, after a suggestion from Jurjen N.E. Bos. Index: test_repr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_repr.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_repr.py 16 Jan 2003 04:56:52 -0000 1.15 --- test_repr.py 5 Feb 2003 18:29:33 -0000 1.16 *************** *** 35,38 **** --- 35,40 ---- def test_container(self): + from array import array + eq = self.assertEquals # Tuples give up after 6 elements *************** *** 56,59 **** --- 58,71 ---- d['arthur'] = 1 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}") + + # array.array after 5. + eq(r(array('i')), "array('i', [])") + eq(r(array('i', [1])), "array('i', [1])") + eq(r(array('i', [1, 2])), "array('i', [1, 2])") + eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])") + eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])") + eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])") + eq(r(array('i', [1, 2, 3, 4, 5, 6])), + "array('i', [1, 2, 3, 4, 5, ...])") def test_numbers(self): From tim_one@users.sourceforge.net Wed Feb 5 18:29:37 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 10:29:37 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.641,1.642 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv15673/Misc Modified Files: NEWS Log Message: [680789] Debug with long array takes forever Added array.array to the types repr.py knows about, after a suggestion from Jurjen N.E. Bos. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.641 retrieving revision 1.642 diff -C2 -d -r1.641 -r1.642 *** NEWS 4 Feb 2003 20:59:40 -0000 1.641 --- NEWS 5 Feb 2003 18:29:34 -0000 1.642 *************** *** 146,149 **** --- 146,152 ---- ------- + - array.array was added to the types repr.py knows about (see + ). + - The new pickletools.py contains lots of documentation about pickle internals, and supplies some helpers for working with pickles, such as From akuchling@users.sourceforge.net Wed Feb 5 20:21:53 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 05 Feb 2003 12:21:53 -0800 Subject: [Python-checkins] python/nondist/peps pep-0042.txt,1.66,1.67 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv26032 Modified Files: pep-0042.txt Log Message: Add a wish Index: pep-0042.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0042.txt,v retrieving revision 1.66 retrieving revision 1.67 diff -C2 -d -r1.66 -r1.67 *** pep-0042.txt 31 Jan 2003 00:18:59 -0000 1.66 --- pep-0042.txt 5 Feb 2003 20:21:49 -0000 1.67 *************** *** 237,240 **** --- 237,245 ---- http://www.python.org/sf/415694 + - pydoc should be integrated with the HTML docs, or at least + be able to link to them. + + http://www.python.org/sf/405554 + C API wishes From tim_one@users.sourceforge.net Wed Feb 5 19:55:56 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 11:55:56 -0800 Subject: [Python-checkins] python/dist/src/Lib pickletools.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv13931/Lib Modified Files: pickletools.py Log Message: dis(): Added an optional memo argument, so that multiple pickles in a file can be dumped without (bogus) complaint if the the pickles were created using a single pickle memo. Index: pickletools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickletools.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** pickletools.py 31 Jan 2003 16:43:39 -0000 1.25 --- pickletools.py 5 Feb 2003 19:55:53 -0000 1.26 *************** *** 1862,1866 **** # A symbolic pickle disassembler. ! def dis(pickle, out=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. --- 1862,1866 ---- # A symbolic pickle disassembler. ! def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. *************** *** 1872,1875 **** --- 1872,1881 ---- printed. It defaults to sys.stdout. + Optional arg 'memo' is a Python dict, used as the pickle's memo. It + may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. + Passing the same memo object to another dis() call then allows disassembly + to proceed across multiple pickles that were all created by the same + pickler with the same memo. Ordinarily you don't need to worry about this. + Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. *************** *** 1896,1900 **** stack = [] # crude emulation of unpickler stack ! memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes --- 1902,1907 ---- stack = [] # crude emulation of unpickler stack ! if memo is None: ! memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes *************** *** 2196,2200 **** --- 2203,2236 ---- """ + _memo_test = r""" + >>> import pickle + >>> from StringIO import StringIO + >>> f = StringIO() + >>> p = pickle.Pickler(f, 2) + >>> x = [1, 2, 3] + >>> p.dump(x) + >>> p.dump(x) + >>> f.seek(0) + >>> memo = {} + >>> dis(f, memo=memo) + 0: \x80 PROTO 2 + 2: ] EMPTY_LIST + 3: q BINPUT 0 + 5: ( MARK + 6: K BININT1 1 + 8: K BININT1 2 + 10: K BININT1 3 + 12: e APPENDS (MARK at 5) + 13: . STOP + highest protocol among opcodes = 2 + >>> dis(f, memo=memo) + 14: \x80 PROTO 2 + 16: h BINGET 0 + 18: . STOP + highest protocol among opcodes = 2 + """ + __test__ = {'disassembler_test': _dis_test, + 'disassembler_memo_test': _memo_test, } From tim_one@users.sourceforge.net Wed Feb 5 19:35:22 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 11:35:22 -0800 Subject: [Python-checkins] python/dist/src/Objects object.c,2.196,2.197 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv3511/python/Objects Modified Files: object.c Log Message: SF bug 681122: Built-in function dir() causes refcount leak in baseclasses. merge_class_dict(): This was missing a decref. Bugfix candidate. Index: object.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v retrieving revision 2.196 retrieving revision 2.197 diff -C2 -d -r2.196 -r2.197 *** object.c 20 Jan 2003 16:54:59 -0000 2.196 --- object.c 5 Feb 2003 19:35:19 -0000 2.197 *************** *** 1657,1660 **** --- 1657,1661 ---- else { for (i = 0; i < n; i++) { + int status; PyObject *base = PySequence_GetItem(bases, i); if (base == NULL) { *************** *** 1662,1666 **** return -1; } ! if (merge_class_dict(dict, base) < 0) { Py_DECREF(bases); return -1; --- 1663,1669 ---- return -1; } ! status = merge_class_dict(dict, base); ! Py_DECREF(base); ! if (status < 0) { Py_DECREF(bases); return -1; From akuchling@users.sourceforge.net Wed Feb 5 21:15:44 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 05 Feb 2003 13:15:44 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libdatetime.tex,1.42,1.43 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv18866 Modified Files: libdatetime.tex Log Message: Markup fixes; in particular, the tables are now reasonable width Index: libdatetime.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libdatetime.tex,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** libdatetime.tex 30 Jan 2003 01:03:38 -0000 1.42 --- libdatetime.tex 5 Feb 2003 21:15:38 -0000 1.43 *************** *** 35,41 **** name, and whether Daylight Saving Time is in effect. Note that no concrete \class{tzinfo} classes are supplied by the \module{datetime} ! module. Instead, they provide a framework for incorporating the level ! of detail an application may require. The rules for time adjustment across ! the world are more political than rational, and there is no standard suitable for every application. --- 35,41 ---- name, and whether Daylight Saving Time is in effect. Note that no concrete \class{tzinfo} classes are supplied by the \module{datetime} ! module. Supporting timezones at whatever level of detail is required ! is up to the application. The rules for time adjustment across the ! world are more political than rational, and there is no standard suitable for every application. *************** *** 202,237 **** % XXX this table is too wide! ! \begin{tableiii}{c|l|c}{code}{Operation}{Result}{Notes} ! \lineiii{\var{t1} = \var{t2} + \var{t3}} {Sum of \var{t2} and \var{t3}. Afterwards \var{t1}-\var{t2} == \var{t3} and \var{t1}-\var{t3} ! == \var{t2} are true.} ! {(1)} ! \lineiii{\var{t1} = \var{t2} - \var{t3}} ! {Difference of \var{t2} and \var{t3}. Afterwards \var{t1} == ! \var{t2} - \var{t3} and \var{t2} == \var{t1} + \var{t3} are ! true.} ! {(1)} ! \lineiii{\var{t1} = \var{t2} * \var{i} or \var{t1} = \var{i} * \var{t2}} {Delta multiplied by an integer or long. Afterwards \var{t1} // i == \var{t2} is true, ! provided \code{i != 0}. ! In general, \var{t1} * i == \var{t1} * (i-1) + \var{t1} is true.} ! {(1)} ! \lineiii{\var{t1} = \var{t2} // \var{i}} ! {The floor is computed and the remainder (if any) is thrown away.} ! {(3)} ! \lineiii{+\var{t1}} ! {Returns a \class{timedelta} object with the same value.} ! {(2)} ! \lineiii{-\var{t1}} {equivalent to \class{timedelta}(-\var{t1.days}, -\var{t1.seconds}, ! -\var{t1.microseconds}), and to \var{t1}* -1.} ! {(1)(4)} ! \lineiii{abs(\var{t})} {equivalent to +\var{t} when \code{t.days >= 0}, and to ! -\var{t} when \code{t.days < 0}.} ! {(2)} ! \end{tableiii} \noindent Notes: --- 202,237 ---- % XXX this table is too wide! ! \begin{tableii}{c|l}{code}{Operation}{Result} ! \lineii{\var{t1} = \var{t2} + \var{t3}} {Sum of \var{t2} and \var{t3}. Afterwards \var{t1}-\var{t2} == \var{t3} and \var{t1}-\var{t3} ! == \var{t2} are true. ! (1)} ! \lineii{\var{t1} = \var{t2} - \var{t3}} ! {Difference of \var{t2} and \var{t3}. ! Afterwards \var{t1} == \var{t2} - \var{t3} and \var{t2} == \var{t1} + \var{t3} are ! true. ! (1)} ! \lineii{\var{t1} = \var{t2} * \var{i} or \var{t1} = \var{i} * \var{t2}} {Delta multiplied by an integer or long. Afterwards \var{t1} // i == \var{t2} is true, ! provided \code{i != 0}.} ! \lineii{}{In general, \var{t1} * i == \var{t1} * (i-1) + \var{t1} is true. ! (1)} ! \lineii{\var{t1} = \var{t2} // \var{i}} ! {The floor is computed and the remainder (if any) is thrown away. ! (3)} ! \lineii{+\var{t1}} ! {Returns a \class{timedelta} object with the same value. ! (2)} ! \lineii{-\var{t1}} {equivalent to \class{timedelta}(-\var{t1.days}, -\var{t1.seconds}, ! -\var{t1.microseconds}), and to \var{t1}* -1. ! (1)(4)} ! \lineii{abs(\var{t})} {equivalent to +\var{t} when \code{t.days >= 0}, and to ! -\var{t} when \code{t.days < 0}. ! (2)} ! \end{tableii} \noindent Notes: *************** *** 349,402 **** % XXX rewrite to be a table ! \begin{itemize} ! \item ! date1 + timedelta -> date2 - timedelta + date1 -> date2 ! date2 is timedelta.days days removed from the date1, moving forward ! in time if timedelta.days > 0, or backward if timedetla.days < 0. ! date2 - date1 == timedelta.days after. timedelta.seconds and ! timedelta.microseconds are ignored. \exception{OverflowError} is ! raised if date2.year would be smaller than \constant{MINYEAR} or ! larger than \constant{MAXYEAR}. ! \item ! date1 - timedelta -> date2 ! Computes the date2 such that date2 + timedelta == date1. This ! isn't quite equivalent to date1 + (-timedelta), because -timedelta ! in isolation can overflow in cases where date1 - timedelta does ! not. timedelta.seconds and timedelta.microseconds are ignored. ! \item ! date1 - date2 -> timedelta ! This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after. ! \item ! comparison of date to date, where date1 is considered less than ! date2 when date1 precedes date2 in time. In other words, ! date1 < date2 if and only if date1.toordinal() < date2.toordinal(). ! \note{In order to stop comparison from falling back to the default ! scheme of comparing object addresses, date comparison ! normally raises \exception{TypeError} if the other comparand ! isn't also a \class{date} object. However, \code{NotImplemented} ! is returned instead if the other comparand has a ! \method{timetuple} attribute. This hook gives other kinds of ! date objects a chance at implementing mixed-type comparison.} ! ! \item ! hash, use as dict key - \item - efficient pickling ! \item ! in Boolean contexts, all \class{date} objects are considered to be true ! \end{itemize} Instance methods: --- 349,412 ---- % XXX rewrite to be a table ! \begin{tableii}{c|l}{code}{Operation}{Result} ! \lineii{\var{date2} = \var{date1} + \var{timedelta}} ! {\var{date2} is \code{\var{timedelta}.days} days removed from ! \var{date1}. (1)} ! \lineii{\var{date2} = \var{date1} - \var{timedelta}} ! {Computes \var{date2} such that \code{\var{date2} + \var{timedelta} ! == \var{date1}}. (2)} ! \lineii{\var{timedelta} = \var{date1} - \var{date2}} ! {(3)} ! \lineii{\var{date1}<\var{date2}} ! {\var{date1} is considered less than \var{date2} when \var{date1} ! precedes \var{date2} in time. (4)} ! \end{tableii} ! Notes: ! \begin{description} ! ! \item[(1)] ! \var{date2} is moved forward in time if \code{\var{timedelta}.days ! > 0}, or backward if \code{\var{timedelta}.days < 0}. Afterward ! \code{\var{date2} - \var{date1} == \var{timedelta}.days}. ! \code{\var{timedelta}.seconds} and ! \code{\var{timedelta}.microseconds} are ignored. ! \exception{OverflowError} is raised if \code{\var{date2}.year} ! would be smaller than \constant{MINYEAR} or larger than ! \constant{MAXYEAR}. ! ! \item[(2)] ! This isn't quite equivalent to date1 + ! (-timedelta), because -timedelta in isolation can overflow in cases ! where date1 - timedelta does not. \code{\var{timedelta}.seconds} ! and \code{\var{timedelta}.microseconds} are ignored. ! ! \item[(3)] ! This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after. ! \item[(4)] ! In other words, \code{date1 < date2} ! if and only if \code{\var{date1}.toordinal() < ! \var{date2}.toordinal()}. ! In order to stop comparison from falling back to the default ! scheme of comparing object addresses, date comparison ! normally raises \exception{TypeError} if the other comparand ! isn't also a \class{date} object. However, \code{NotImplemented} ! is returned instead if the other comparand has a ! \method{timetuple} attribute. This hook gives other kinds of ! date objects a chance at implementing mixed-type comparison. ! \end{description} ! Dates can be used as dictionary keys. In Boolean contexts, all ! \class{date} objects are considered to be true. Instance methods: *************** *** 415,422 **** \code{\var{d}.timetuple()} is equivalent to \code{(\var{d}.year, \var{d}.month, \var{d}.day, ! 0, 0, 0, \# h, m, s ! \var{d}.weekday(), \# 0 is Monday \var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1, - \# day of year -1)} \end{methoddesc} --- 425,431 ---- \code{\var{d}.timetuple()} is equivalent to \code{(\var{d}.year, \var{d}.month, \var{d}.day, ! 0, 0, 0, ! \var{d}.weekday(), \var{d}.toordinal() - date(\var{d}.year, 1, 1).toordinal() + 1, -1)} \end{methoddesc} *************** *** 430,434 **** \begin{methoddesc}{weekday}{} Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also \method{isoweekday()}. --- 439,443 ---- \begin{methoddesc}{weekday}{} Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. For example, \code{date(2002, 12, 4).weekday() == 2}, a Wednesday. See also \method{isoweekday()}. *************** *** 437,441 **** \begin{methoddesc}{isoweekday}{} Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3, a Wednesday. See also \method{weekday()}, \method{isocalendar()}. --- 446,450 ---- \begin{methoddesc}{isoweekday}{} Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. For example, \code{date(2002, 12, 4).isoweekday() == 3}, a Wednesday. See also \method{weekday()}, \method{isocalendar()}. *************** *** 458,464 **** year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that ! ! date(2003, 12, 29).isocalendar() == (2004, 1, 1) ! date(2004, 1, 4).isocalendar() == (2004, 1, 7) \end{methoddesc} --- 467,473 ---- year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that ! \code{date(2003, 12, 29).isocalendar() == (2004, 1, 1)} ! and ! \code{date(2004, 1, 4).isocalendar() == (2004, 1, 7)}. \end{methoddesc} *************** *** 466,470 **** Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For example, ! date(2002, 12, 4).isoformat() == '2002-12-04'. \end{methoddesc} --- 475,479 ---- Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For example, ! \code{date(2002, 12, 4).isoformat() == '2002-12-04'}. \end{methoddesc} *************** *** 591,596 **** Return the \class{datetime} corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ! \exception{ValueError} is raised unless 1 <= ordinal <= ! datetime.max.toordinal(). The hour, minute, second and microsecond of the result are all 0, and \member{tzinfo} is \code{None}. --- 600,605 ---- Return the \class{datetime} corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ! \exception{ValueError} is raised unless \code{1 <= ordinal <= ! datetime.max.toordinal()}. The hour, minute, second and microsecond of the result are all 0, and \member{tzinfo} is \code{None}. *************** *** 662,674 **** Supported operations: ! \begin{itemize} ! \item ! datetime1 + timedelta -> datetime2 ! timedelta + datetime1 -> datetime2 datetime2 is a duration of timedelta removed from datetime1, moving ! forward in time if timedelta.days > 0, or backward if ! timedelta.days < 0. The result has the same \member{tzinfo} member as the input datetime, and datetime2 - datetime1 == timedelta after. \exception{OverflowError} is raised if datetime2.year would be --- 671,694 ---- Supported operations: ! \begin{tableii}{c|l}{code}{Operation}{Result} ! \lineii{\var{datetime2} = \var{datetime1} + \var{timedelta}}{(1)} ! \lineii{\var{datetime2} = \var{datetime1} - \var{timedelta}}{(2)} ! ! \lineii{\var{timedelta} = \var{datetime1} - \var{datetime2}}{(3)} ! ! \lineii{\var{datetime1} < \var{datetime2}} ! {Compares \class{datetime} to \class{datetime}. ! (4)} ! ! \end{tableii} ! ! \begin{description} ! ! \item[(1)] datetime2 is a duration of timedelta removed from datetime1, moving ! forward in time if \code{\var{timedelta}.days} > 0, or backward if ! \code{\var{timedelta}.days} < 0. The result has the same \member{tzinfo} member as the input datetime, and datetime2 - datetime1 == timedelta after. \exception{OverflowError} is raised if datetime2.year would be *************** *** 677,683 **** aware object. ! \item ! datetime1 - timedelta -> datetime2 ! Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same \member{tzinfo} member --- 697,701 ---- aware object. ! \item[(2)] Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same \member{tzinfo} member *************** *** 688,694 **** datetime1 - timedelta does not. ! \item ! datetime1 - datetime2 -> timedelta ! Subtraction of a \class{datetime} from a \class{datetime} is defined only if both --- 706,710 ---- datetime1 - timedelta does not. ! \item[(3)] Subtraction of a \class{datetime} from a \class{datetime} is defined only if both *************** *** 709,717 **** except that the implementation never overflows. ! \item ! comparison of \class{datetime} to \class{datetime}, ! where \var{a} is considered less than \var{b} ! when \var{a} precedes \var{b} in time. If one comparand is naive and ! the other is aware, \exception{TypeError} is raised. If both comparands are aware, and have the same \member{tzinfo} member, the common \member{tzinfo} member is ignored and the base datetimes --- 725,735 ---- except that the implementation never overflows. ! \item[(4)] ! ! \var{datetime1} is considered less than \var{datetime2} ! when \var{datetime1} precedes \var{datetime2} in time. ! ! If one comparand is naive and ! the other is aware, \exception{TypeError} is raised. If both comparands are aware, and have the same \member{tzinfo} member, the common \member{tzinfo} member is ignored and the base datetimes *************** *** 728,741 **** comparison.} ! \item ! hash, use as dict key ! \item ! efficient pickling - \item - in Boolean contexts, all \class{datetime} objects are considered - to be true - \end{itemize} Instance methods: --- 746,754 ---- comparison.} ! \end{description} ! \class{datetime} objects can be used as dictionary keys. In Boolean ! contexts, all \class{datetime} objects are considered to be true. Instance methods: *************** *** 774,778 **** \code{None}). ! If code{\var{self}.tzinfo} is \var{tz}, \code{\var{self}.astimezone(\var{tz})} is equal to \var{self}: no adjustment of date or time members is performed. --- 787,791 ---- \code{None}). ! If \code{\var{self}.tzinfo} is \var{tz}, \code{\var{self}.astimezone(\var{tz})} is equal to \var{self}: no adjustment of date or time members is performed. From akuchling@users.sourceforge.net Wed Feb 5 21:35:12 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 05 Feb 2003 13:35:12 -0800 Subject: [Python-checkins] python/dist/src/Lib gzip.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv25917 Modified Files: gzip.py Log Message: [Patch #654421 from Matthew Mueller] gzip shouldn't raise ValueError on corrupt files Currently the gzip module will raise a ValueError if the file was corrupt (bad crc or bad size). I can't see how that applies to reading a corrupt file. IOError seems better, and it's what code will likely be looking for. Index: gzip.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/gzip.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** gzip.py 5 Nov 2002 20:38:54 -0000 1.37 --- gzip.py 5 Feb 2003 21:35:07 -0000 1.38 *************** *** 306,312 **** isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): ! raise ValueError, "CRC check failed" elif isize != LOWU32(self.size): ! raise ValueError, "Incorrect length of data produced" def close(self): --- 306,312 ---- isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): ! raise IOError, "CRC check failed" elif isize != LOWU32(self.size): ! raise IOError, "Incorrect length of data produced" def close(self): From tim_one@users.sourceforge.net Wed Feb 5 22:29:04 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:29:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_datetime.py,1.110,1.111 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16957 Modified Files: test_datetime.py Log Message: Bring the pickle tests into synch w/ 2.3 CVS. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.110 retrieving revision 1.111 diff -C2 -d -r1.110 -r1.111 *** test_datetime.py 1 Feb 2003 03:02:34 -0000 1.110 --- test_datetime.py 5 Feb 2003 22:29:00 -0000 1.111 *************** *** 15,33 **** from datetime import date, datetime ! ! pickle_choices = [ ! (pickle, pickle, 0), ! (pickle, pickle, 1), ! (pickle, pickle, 2), ! (cPickle, cPickle, 0), ! (cPickle, cPickle, 1), ! ## (cPickle, cPickle, 2), ! (pickle, cPickle, 0), ! (pickle, cPickle, 1), ! ## (pickle, cPickle, 2), ! (cPickle, pickle, 0), ! (cPickle, pickle, 1), ! ## (cPickle, pickle, 2), ! ] --- 15,24 ---- from datetime import date, datetime ! # Before Python 2.3, proto=2 was taken as a synonym for proto=1. ! pickle_choices = [(pickler, unpickler, proto) ! for pickler in pickle, cPickle ! for unpickler in pickle, cPickle ! for proto in range(3)] ! assert len(pickle_choices) == 2*2*3 From andrewmcnamara@users.sourceforge.net Wed Feb 5 22:30:45 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:30:45 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv17473/test Modified Files: test_csv.py Log Message: Remove a bunch of tests that were no longer relevant after quoting/quotechar were rationalised. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** test_csv.py 5 Feb 2003 03:21:39 -0000 1.17 --- test_csv.py 5 Feb 2003 22:30:42 -0000 1.18 *************** *** 32,41 **** self.assertEqual(parser.quotechar, "'") - parser = _csv.parser(quoting = csv.QUOTE_NONE) - self.assertEqual(parser.quotechar, None) - - parser = _csv.parser(quotechar=None,quoting=csv.QUOTE_ALL) - self.assertEqual(parser.quoting, csv.QUOTE_NONE) - def test_attr_validation(self): parser = _csv.parser() --- 32,35 ---- *************** *** 46,51 **** self.assertRaises(TypeError, setattr, parser, 'quotechar', 0) self.assertRaises(TypeError, setattr, parser, 'escapechar', 0) - parser.quotechar=None - self.assertRaises(TypeError, setattr, parser, 'quoting', 1) self.assertRaises(TypeError, setattr, parser, 'lineterminator', None) --- 40,43 ---- *************** *** 59,66 **** self.assertEqual(parser.quotechar, "'") - parser = _csv.parser() - parser.quoting = csv.QUOTE_NONE - self.assertEqual(parser.quotechar, None) - def test_join_bigfield(self): # This exercises the buffer realloc functionality --- 51,54 ---- *************** *** 89,93 **** # FAIL - need to fix # self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') ! parser.quotechar = None self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') --- 77,81 ---- # FAIL - need to fix # self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') ! parser.quoting = csv.QUOTE_NONE self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') From jhylton@users.sourceforge.net Wed Feb 5 22:39:32 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:39:32 -0800 Subject: [Python-checkins] python/dist/src/Objects frameobject.c,2.72,2.73 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv21960/Objects Modified Files: frameobject.c Log Message: Refactor the logic for setting f_builtins. For the case where the current globals match the previous frame's globals, eliminates three tests in two if statements. For the case where we just get __builtins__ from a module, eliminate a couple of tests. Index: frameobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/frameobject.c,v retrieving revision 2.72 retrieving revision 2.73 diff -C2 -d -r2.72 -r2.73 *** frameobject.c 31 Dec 2002 03:42:13 -0000 2.72 --- frameobject.c 5 Feb 2003 22:39:29 -0000 2.73 *************** *** 555,560 **** if (back == NULL || back->f_globals != globals) { builtins = PyDict_GetItem(globals, builtin_object); ! if (builtins != NULL && PyModule_Check(builtins)) ! builtins = PyModule_GetDict(builtins); } else { --- 555,578 ---- if (back == NULL || back->f_globals != globals) { builtins = PyDict_GetItem(globals, builtin_object); ! if (builtins) { ! if (PyModule_Check(builtins)) { ! builtins = PyModule_GetDict(builtins); ! assert(!builtins || PyDict_Check(builtins)); ! } ! else if (!PyDict_Check(builtins)) ! builtins = NULL; ! } ! if (builtins == NULL) { ! /* No builtins! Make up a minimal one ! Give them 'None', at least. */ ! builtins = PyDict_New(); ! if (builtins == NULL || ! PyDict_SetItemString( ! builtins, "None", Py_None) < 0) ! return NULL; ! } ! else ! Py_INCREF(builtins); ! } else { *************** *** 562,568 **** Save a lookup and a call. */ builtins = back->f_builtins; } - if (builtins != NULL && !PyDict_Check(builtins)) - builtins = NULL; if (free_list == NULL) { f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras); --- 580,586 ---- Save a lookup and a call. */ builtins = back->f_builtins; + assert(builtins != NULL && PyDict_Check(builtins)); + Py_INCREF(builtins); } if (free_list == NULL) { f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras); *************** *** 582,596 **** _Py_NewReference((PyObject *)f); } - if (builtins == NULL) { - /* No builtins! Make up a minimal one. */ - builtins = PyDict_New(); - if (builtins == NULL || /* Give them 'None', at least. */ - PyDict_SetItemString(builtins, "None", Py_None) < 0) { - Py_DECREF(f); - return NULL; - } - } - else - Py_INCREF(builtins); f->f_builtins = builtins; Py_XINCREF(back); --- 600,603 ---- *************** *** 600,612 **** Py_INCREF(globals); f->f_globals = globals; ! if (code->co_flags & CO_NEWLOCALS) { ! if (code->co_flags & CO_OPTIMIZED) ! locals = NULL; /* Let fast_2_locals handle it */ ! else { ! locals = PyDict_New(); ! if (locals == NULL) { ! Py_DECREF(f); ! return NULL; ! } } } --- 607,619 ---- Py_INCREF(globals); f->f_globals = globals; ! /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ ! if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == ! (CO_NEWLOCALS | CO_OPTIMIZED)) ! locals = NULL; /* PyFrame_Fast2Locals() will set. */ ! else if (code->co_flags & CO_NEWLOCALS) { ! locals = PyDict_New(); ! if (locals == NULL) { ! Py_DECREF(f); ! return NULL; } } From gvanrossum@users.sourceforge.net Wed Feb 5 22:39:50 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:39:50 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.202,2.203 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv22038 Modified Files: typeobject.c Log Message: Fix for SF #668433. I'm not explaining it here; ample comments are in the code. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.202 retrieving revision 2.203 diff -C2 -d -r2.202 -r2.203 *** typeobject.c 7 Jan 2003 13:41:36 -0000 2.202 --- typeobject.c 5 Feb 2003 22:39:45 -0000 2.203 *************** *** 641,646 **** --- 641,649 ---- /* UnTrack and re-Track around the trashcan macro, alas */ + /* See explanation at end of funtion for full disclosure */ PyObject_GC_UnTrack(self); + ++_PyTrash_delete_nesting; Py_TRASHCAN_SAFE_BEGIN(self); + --_PyTrash_delete_nesting; _PyObject_GC_TRACK(self); /* We'll untrack for real later */ *************** *** 690,694 **** --- 693,787 ---- endlabel: + ++_PyTrash_delete_nesting; Py_TRASHCAN_SAFE_END(self); + --_PyTrash_delete_nesting; + + /* Explanation of the weirdness around the trashcan macros: + + Q. What do the trashcan macros do? + + A. Read the comment titled "Trashcan mechanism" in object.h. + For one, this explains why there must be a call to GC-untrack + before the trashcan begin macro. Without understanding the + trashcan code, the answers to the following questions don't make + sense. + + Q. Why do we GC-untrack before the trashcan and then immediately + GC-track again afterward? + + A. In the case that the base class is GC-aware, the base class + probably GC-untracks the object. If it does that using the + UNTRACK macro, this will crash when the object is already + untracked. Because we don't know what the base class does, the + only safe thing is to make sure the object is tracked when we + call the base class dealloc. But... The trashcan begin macro + requires that the object is *untracked* before it is called. So + the dance becomes: + + GC untrack + trashcan begin + GC track + + Q. Why the bizarre (net-zero) manipulation of + _PyTrash_delete_nesting around the trashcan macros? + + A. Some base classes (e.g. list) also use the trashcan mechanism. + The following scenario used to be possible: + + - suppose the trashcan level is one below the trashcan limit + + - subtype_dealloc() is called + + - the trashcan limit is not yet reached, so the trashcan level + is incremented and the code between trashcan begin and end is + executed + + - this destroys much of the object's contents, including its + slots and __dict__ + + - basedealloc() is called; this is really list_dealloc(), or + some other type which also uses the trashcan macros + + - the trashcan limit is now reached, so the object is put on the + trashcan's to-be-deleted-later list + + - basedealloc() returns + + - subtype_dealloc() decrefs the object's type + + - subtype_dealloc() returns + + - later, the trashcan code starts deleting the objects from its + to-be-deleted-later list + + - subtype_dealloc() is called *AGAIN* for the same object + + - at the very least (if the destroyed slots and __dict__ don't + cause problems) the object's type gets decref'ed a second + time, which is *BAD*!!! + + The remedy is to make sure that if the code between trashcan + begin and end in subtype_dealloc() is called, the code between + trashcan begin and end in basedealloc() will also be called. + This is done by decrementing the level after passing into the + trashcan block, and incrementing it just before leaving the + block. + + But now it's possible that a chain of objects consisting solely + of objects whose deallocator is subtype_dealloc() will defeat + the trashcan mechanism completely: the decremented level means + that the effective level never reaches the limit. Therefore, we + *increment* the level *before* entering the trashcan block, and + matchingly decrement it after leaving. This means the trashcan + code will trigger a little early, but that's no big deal. + + Q. Are there any live examples of code in need of all this + complexity? + + A. Yes. See SF bug 668433 for code that crashed (when Python was + compiled in debug mode) before the trashcan level manipulations + were added. For more discussion, see SF patches 581742, 575073 + and bug 574207. + */ } From jackjansen@users.sourceforge.net Wed Feb 5 22:52:18 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:52:18 -0800 Subject: [Python-checkins] python/dist/src/Mac/Unsupported unshar.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Unsupported In directory sc8-pr-cvs1:/tmp/cvs-serv26887/Unsupported Added Files: unshar.py Log Message: I don't think this script serves a useful purpose anymore, and I can't be bothered to fix it. --- NEW FILE: unshar.py --- # Extract files from a SHAR archive. # Run this on the Mac. # Usage: # >>> import unshar # >>> f = open('SHAR') # >>> unshar.unshar(f) import string import EasyDialogs def unshar(fp, verbose=0, overwrite=0): ofp = None file = None while 1: line = fp.readline() if verbose > 3: print 'Got:', `line` if line[:1] == 'X': # Most common case first if ofp: ofp.write(line[1:]) continue if not line: if verbose: print 'EOF' if ofp: print 'Unterminated file -- closing' ofp.close() ofp = None break if line[0] == '#': if verbose: print line, continue if line[:14] == 'sed "s/^X//" >': if verbose: print "!!!", `line` i = string.find(line, "'") j = string.find(line, "'", i+1) if i >= 0 and j > i: file = line[i+1:j] if '/' in file: words = string.splitfields(file, '/') for funny in '', '.': while funny in words: words.remove(funny) for i in range(len(words)): if words[i] == '..': words[i] = '' words.insert(0, '') file = string.joinfields(words, ':') try: ofp = open(file, 'r') ofp.close() ofp = None over = 1 except IOError: over = 0 if over and not overwrite: print 'Skipping', file, '(already exists) ...' continue ofp = open(file, 'w') if over: print 'Overwriting', file, '...' else: print 'Writing', file, '...' continue if line == 'END_OF_FILE\n': if not file: print 'Unexpected END_OF_FILE marker' if ofp: print 'done' ofp.close() ofp = None else: print 'done skipping' file = None continue if verbose: print "...", `line` def main(): import sys import os if len(sys.argv) > 1: for fname in sys.argv[1:]: fp = open(fname, 'r') dir, fn = os.path.split(fname) if dir: os.chdir(dir) unshar(fp) else: import macfs fname = EasyDialogs.AskFileForOpen() if not fname: sys.exit(0) fp = open(fname, 'r') dirname = EasyDialogs.AskFolder(message='Folder to save files in:') if not dirname: sys.exit(0) os.chdir(dirname) unshar(fp) if __name__ == '__main__': main() From jackjansen@users.sourceforge.net Wed Feb 5 22:52:18 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:52:18 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts unshar.py,1.3,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv26887/scripts Removed Files: unshar.py Log Message: I don't think this script serves a useful purpose anymore, and I can't be bothered to fix it. --- unshar.py DELETED --- From jackjansen@users.sourceforge.net Wed Feb 5 22:53:31 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:53:31 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts zappycfiles.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv27436 Modified Files: zappycfiles.py Log Message: Removed unused import of macfs. Index: zappycfiles.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/zappycfiles.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** zappycfiles.py 26 Jan 2003 21:40:00 -0000 1.4 --- zappycfiles.py 5 Feb 2003 22:53:29 -0000 1.5 *************** *** 12,16 **** if not sys.argv[1:]: if os.name == 'mac': - import macfs dir = EasyDialogs.AskFolder(message='Directory to zap pyc files in') if not dir: --- 12,15 ---- From jvr@users.sourceforge.net Wed Feb 5 22:59:09 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Wed, 05 Feb 2003 14:59:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts makeclean.py,1.2,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv30078 Removed Files: makeclean.py Log Message: removing old junk --- makeclean.py DELETED --- From jackjansen@users.sourceforge.net Wed Feb 5 23:10:49 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 05 Feb 2003 15:10:49 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts findgremlins.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv2313 Modified Files: findgremlins.py Log Message: Got rid of macfs and made a bit more OSX-friendly. Index: findgremlins.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/findgremlins.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** findgremlins.py 26 Jan 2003 21:40:00 -0000 1.2 --- findgremlins.py 5 Feb 2003 23:10:46 -0000 1.3 *************** *** 6,10 **** import EasyDialogs ! import macfs import re import os --- 6,10 ---- import EasyDialogs ! import MacOS import re import os *************** *** 21,26 **** walk(path) else: ! cr, tp = macfs.FSSpec(top).GetCreatorType() ! if tp == 'TEXT' and top[-4:] <> ".hqx": data = open(top).read() badcount = 0 --- 21,26 ---- walk(path) else: ! cr, tp = MacOS.GetCreatorAndType(top) ! if tp in ('TEXT', '\0\0\0\0') and top[-4:] <> ".hqx": data = open(top).read() badcount = 0 *************** *** 45,54 **** def main(): ! pathname = EasyDialogs.AskFolder() ! if pathname: ! walk(pathname) if __name__ == '__main__': main() - sys.exit(1) # So we see the output --- 45,57 ---- def main(): ! if sys.argv[1:]: ! for pathname in sys.argv[1:]: ! walk(pathname) ! else: ! pathname = EasyDialogs.AskFolder() ! if pathname: ! walk(pathname) if __name__ == '__main__': main() From jhylton@users.sourceforge.net Wed Feb 5 23:13:29 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 05 Feb 2003 15:13:29 -0800 Subject: [Python-checkins] python/dist/src/Misc SpecialBuilds.txt,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv3401/Misc Modified Files: SpecialBuilds.txt Log Message: Small function call optimization and special build option for call stats. -DCALL_PROFILE: Count the number of function calls executed. When this symbol is defined, the ceval mainloop and helper functions count the number of function calls made. It keeps detailed statistics about what kind of object was called and whether the call hit any of the special fast paths in the code. Optimization: When we take the fast_function() path, which seems to be taken for most function calls, and there is minimal frame setup to do, avoid call PyEval_EvalCodeEx(). The eval code ex function does a lot of work to handle keywords args and star args, free variables, generators, etc. The inlined version simply allocates the frame and copies the arguments values into the frame. The optimization gets a little help from compile.c which adds a CO_NOFREE flag to code objects that don't have free variables or cell variables. This change allows fast_function() to get into the fast path with fewer tests. I measure a couple of percent speedup in pystone with this change, but there's surely more that can be done. Index: SpecialBuilds.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/SpecialBuilds.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** SpecialBuilds.txt 30 Jul 2002 15:25:57 -0000 1.12 --- SpecialBuilds.txt 5 Feb 2003 23:12:57 -0000 1.13 *************** *** 200,201 **** --- 200,211 ---- Not useful very often, but very useful when needed. + + --------------------------------------------------------------------------- + CALL_PROFILE introduced for Python 2.3 + + Count the number of function calls executed. + + When this symbol is defined, the ceval mainloop and helper functions + count the number of function calls made. It keeps detailed statistics + about what kind of object was called and whether the call hit any of + the special fast paths in the code. From jhylton@users.sourceforge.net Wed Feb 5 23:13:29 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 05 Feb 2003 15:13:29 -0800 Subject: [Python-checkins] python/dist/src/Include ceval.h,2.46,2.47 compile.h,2.39,2.40 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv3401/Include Modified Files: ceval.h compile.h Log Message: Small function call optimization and special build option for call stats. -DCALL_PROFILE: Count the number of function calls executed. When this symbol is defined, the ceval mainloop and helper functions count the number of function calls made. It keeps detailed statistics about what kind of object was called and whether the call hit any of the special fast paths in the code. Optimization: When we take the fast_function() path, which seems to be taken for most function calls, and there is minimal frame setup to do, avoid call PyEval_EvalCodeEx(). The eval code ex function does a lot of work to handle keywords args and star args, free variables, generators, etc. The inlined version simply allocates the frame and copies the arguments values into the frame. The optimization gets a little help from compile.c which adds a CO_NOFREE flag to code objects that don't have free variables or cell variables. This change allows fast_function() to get into the fast path with fewer tests. I measure a couple of percent speedup in pystone with this change, but there's surely more that can be done. Index: ceval.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/ceval.h,v retrieving revision 2.46 retrieving revision 2.47 diff -C2 -d -r2.46 -r2.47 *** ceval.h 3 Sep 2002 20:10:44 -0000 2.46 --- ceval.h 5 Feb 2003 23:12:56 -0000 2.47 *************** *** 49,52 **** --- 49,54 ---- PyAPI_FUNC(char *) PyEval_GetFuncDesc(PyObject *); + PyAPI_FUNC(PyObject *) PyEval_GetCallStats(PyObject *); + /* this used to be handled on a per-thread basis - now just two globals */ PyAPI_DATA(volatile int) _Py_Ticker; Index: compile.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/compile.h,v retrieving revision 2.39 retrieving revision 2.40 diff -C2 -d -r2.39 -r2.40 *** compile.h 11 Dec 2002 14:04:57 -0000 2.39 --- compile.h 5 Feb 2003 23:12:56 -0000 2.40 *************** *** 35,38 **** --- 35,44 ---- #define CO_NESTED 0x0010 #define CO_GENERATOR 0x0020 + /* The CO_NOFREE flag is set if there are no free or cell variables. + This information is redundant, but it allows a single flag test + to determine whether there is any extra work to be done when the + call frame it setup. + */ + #define CO_NOFREE 0x0040 /* XXX Temporary hack. Until generators are a permanent part of the language, we need a way for a code object to record that generators From jhylton@users.sourceforge.net Wed Feb 5 23:13:04 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 05 Feb 2003 15:13:04 -0800 Subject: [Python-checkins] python/dist/src/Python ceval.c,2.347,2.348 compile.c,2.272,2.273 sysmodule.c,2.112,2.113 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv3401/Python Modified Files: ceval.c compile.c sysmodule.c Log Message: Small function call optimization and special build option for call stats. -DCALL_PROFILE: Count the number of function calls executed. When this symbol is defined, the ceval mainloop and helper functions count the number of function calls made. It keeps detailed statistics about what kind of object was called and whether the call hit any of the special fast paths in the code. Optimization: When we take the fast_function() path, which seems to be taken for most function calls, and there is minimal frame setup to do, avoid call PyEval_EvalCodeEx(). The eval code ex function does a lot of work to handle keywords args and star args, free variables, generators, etc. The inlined version simply allocates the frame and copies the arguments values into the frame. The optimization gets a little help from compile.c which adds a CO_NOFREE flag to code objects that don't have free variables or cell variables. This change allows fast_function() to get into the fast path with fewer tests. I measure a couple of percent speedup in pystone with this change, but there's surely more that can be done. Index: ceval.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/ceval.c,v retrieving revision 2.347 retrieving revision 2.348 diff -C2 -d -r2.347 -r2.348 *** ceval.c 19 Jan 2003 05:08:13 -0000 2.347 --- ceval.c 5 Feb 2003 23:12:57 -0000 2.348 *************** *** 88,91 **** --- 88,147 ---- #endif + /* Function call profile */ + #ifdef CALL_PROFILE + #define PCALL_NUM 11 + static int pcall[PCALL_NUM]; + + #define PCALL_ALL 0 + #define PCALL_FUNCTION 1 + #define PCALL_FAST_FUNCTION 2 + #define PCALL_FASTER_FUNCTION 3 + #define PCALL_METHOD 4 + #define PCALL_BOUND_METHOD 5 + #define PCALL_CFUNCTION 6 + #define PCALL_TYPE 7 + #define PCALL_GENERATOR 8 + #define PCALL_OTHER 9 + #define PCALL_POP 10 + + /* Notes about the statistics + + PCALL_FAST stats + + FAST_FUNCTION means no argument tuple needs to be created. + FASTER_FUNCTION means that the fast-path frame setup code is used. + + If there is a method call where the call can be optimized by changing + the argument tuple and calling the function directly, it gets recorded + twice. + + As a result, the relationship among the statistics appears to be + PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD + + PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER + PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION + PCALL_METHOD > PCALL_BOUND_METHOD + */ + + #define PCALL(POS) pcall[POS]++ + + PyObject * + PyEval_GetCallStats(PyObject *self) + { + return Py_BuildValue("iiiiiiiiii", + pcall[0], pcall[1], pcall[2], pcall[3], + pcall[4], pcall[5], pcall[6], pcall[7], + pcall[8], pcall[9]); + } + #else + #define PCALL(O) + + PyObject * + PyEval_GetCallStats(PyObject *self) + { + Py_INCREF(Py_None); + return Py_None; + } + #endif + static PyTypeObject gentype; *************** *** 476,479 **** --- 532,536 ---- PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) { + /* XXX raise SystemError if globals is NULL */ return PyEval_EvalCodeEx(co, globals, locals, *************** *** 1981,1984 **** --- 2038,2042 ---- case CALL_FUNCTION: + PCALL(PCALL_ALL); x = call_function(&stack_pointer, oparg); PUSH(x); *************** *** 1996,1999 **** --- 2054,2058 ---- int n = na + 2 * nk; PyObject **pfunc, *func; + PCALL(PCALL_ALL); if (flags & CALL_FLAG_VAR) n++; *************** *** 2318,2324 **** } ! f = PyFrame_New(tstate, /*back*/ ! co, /*code*/ ! globals, locals); if (f == NULL) return NULL; --- 2377,2382 ---- } ! assert(globals != NULL); ! f = PyFrame_New(tstate, co, globals, locals); if (f == NULL) return NULL; *************** *** 2521,2524 **** --- 2579,2584 ---- f->f_back = NULL; + PCALL(PCALL_GENERATOR); + /* Create a new generator that owns the ready to run frame * and return that as the value. */ *************** *** 3199,3208 **** PyObject *x, *w; ! /* Always dispatch PyCFunction first, because ! these are presumed to be the most frequent ! callable object. */ if (PyCFunction_Check(func) && nk == 0) { int flags = PyCFunction_GET_FLAGS(func); if (flags & (METH_NOARGS | METH_O)) { PyCFunction meth = PyCFunction_GET_FUNCTION(func); --- 3259,3268 ---- PyObject *x, *w; ! /* Always dispatch PyCFunction first, because these are ! presumed to be the most frequent callable object. */ if (PyCFunction_Check(func) && nk == 0) { int flags = PyCFunction_GET_FLAGS(func); + PCALL(PCALL_CFUNCTION); if (flags & (METH_NOARGS | METH_O)) { PyCFunction meth = PyCFunction_GET_FUNCTION(func); *************** *** 3230,3233 **** --- 3290,3295 ---- /* optimize access to bound methods */ PyObject *self = PyMethod_GET_SELF(func); + PCALL(PCALL_METHOD); + PCALL(PCALL_BOUND_METHOD); Py_INCREF(self); func = PyMethod_GET_FUNCTION(func); *************** *** 3246,3252 **** --- 3308,3316 ---- } + /* What does this do? */ while ((*pp_stack) > pfunc) { w = EXT_POP(*pp_stack); Py_DECREF(w); + PCALL(PCALL_POP); } return x; *************** *** 3255,3258 **** --- 3319,3327 ---- /* The fast_function() function optimize calls for which no argument tuple is necessary; the objects are passed directly from the stack. + For the simplest case -- a function that takes only positional + arguments and is called with only positional arguments -- it + inlines the most primitive frame setup code from + PyEval_EvalCodeEx(), which vastly reduces the checks that must be + done before evaluating the frame. */ *************** *** 3260,3278 **** fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { ! PyObject *co = PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure = PyFunction_GET_CLOSURE(func); PyObject **d = NULL; int nd = 0; if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = ((PyTupleObject *)argdefs)->ob_size; } ! return PyEval_EvalCodeEx((PyCodeObject *)co, globals, ! (PyObject *)NULL, (*pp_stack)-n, na, ! (*pp_stack)-2*nk, nk, d, nd, ! closure); } --- 3329,3380 ---- fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { ! PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject **d = NULL; int nd = 0; + PCALL(PCALL_FUNCTION); + PCALL(PCALL_FAST_FUNCTION); + if (argdefs == NULL && co->co_argcount == n && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + PyFrameObject *f; + PyObject *retval = NULL; + PyThreadState *tstate = PyThreadState_GET(); + PyObject **fastlocals, **stack; + int i; + + PCALL(PCALL_FASTER_FUNCTION); + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + stack = (*pp_stack) - n; + + for (i = 0; i < n; i++) { + Py_INCREF(*stack); + fastlocals[i] = *stack++; + } + retval = eval_frame(f); + assert(tstate != NULL); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; + } if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = ((PyTupleObject *)argdefs)->ob_size; } ! return PyEval_EvalCodeEx(co, globals, ! (PyObject *)NULL, (*pp_stack)-n, na, ! (*pp_stack)-2*nk, nk, d, nd, ! PyFunction_GET_CLOSURE(func)); } *************** *** 3372,3375 **** --- 3474,3491 ---- if (callargs == NULL) goto call_fail; + #ifdef CALL_PROFILE + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else + PCALL(PCALL_OTHER); + #endif result = PyObject_Call(func, callargs, kwdict); call_fail: *************** *** 3427,3430 **** --- 3543,3560 ---- if (callargs == NULL) goto ext_call_fail; + #ifdef CALL_PROFILE + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else + PCALL(PCALL_OTHER); + #endif result = PyObject_Call(func, callargs, kwdict); ext_call_fail: Index: compile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/compile.c,v retrieving revision 2.272 retrieving revision 2.273 diff -C2 -d -r2.272 -r2.273 *** compile.c 16 Jan 2003 15:39:07 -0000 2.272 --- compile.c 5 Feb 2003 23:13:00 -0000 2.273 *************** *** 386,389 **** --- 386,392 ---- Py_INCREF(lnotab); co->co_lnotab = lnotab; + if (PyTuple_GET_SIZE(freevars) == 0 && + PyTuple_GET_SIZE(cellvars) == 0) + co->co_flags |= CO_NOFREE; } return co; Index: sysmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/sysmodule.c,v retrieving revision 2.112 retrieving revision 2.113 diff -C2 -d -r2.112 -r2.113 *** sysmodule.c 8 Jan 2003 14:33:48 -0000 2.112 --- sysmodule.c 5 Feb 2003 23:13:00 -0000 2.113 *************** *** 563,566 **** --- 563,588 ---- } + PyDoc_STRVAR(callstats_doc, + "callstats() -> tuple of integers\n\ + \n\ + Return a tuple of function call statistics, if CALL_PROFILE was defined\n\ + when Python was built. Otherwise, return None.\n\ + \n\ + When enabled, this function returns detailed, implementation-specific\n\ + details about the number of function calls executed. The return value is\n\ + a 11-tuple where the entries in the tuple are counts of:\n\ + 0. all function calls\n\ + 1. calls to PyFunction_Type objects\n\ + 2. PyFunction calls that do not create an argument tuple\n\ + 3. PyFunction calls that do not create an argument tuple\n\ + and bypass PyEval_EvalCodeEx()\n\ + 4. PyMethod calls\n\ + 5. PyMethod calls on bound methods\n\ + 6. PyType calls\n\ + 7. PyCFunction calls\n\ + 8. generator calls\n\ + 9. All other calls\n\ + 10. Number of stack pops performed by call_function()" + ); #ifdef Py_TRACE_REFS *************** *** 576,579 **** --- 598,603 ---- static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ + {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, + callstats_doc}, {"displayhook", sys_displayhook, METH_O, displayhook_doc}, {"exc_info", (PyCFunction)sys_exc_info, METH_NOARGS, exc_info_doc}, *************** *** 581,586 **** {"exit", sys_exit, METH_VARARGS, exit_doc}, #ifdef Py_USING_UNICODE ! {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, METH_NOARGS, ! getdefaultencoding_doc}, #endif #ifdef HAVE_DLOPEN --- 605,610 ---- {"exit", sys_exit, METH_VARARGS, exit_doc}, #ifdef Py_USING_UNICODE ! {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, ! METH_NOARGS, getdefaultencoding_doc}, #endif #ifdef HAVE_DLOPEN From montanaro@users.sourceforge.net Thu Feb 6 01:27:34 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 05 Feb 2003 17:27:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv18538 Modified Files: test_csv.py Log Message: uncomment the failing test - better left noisy as a reminder ;-) Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** test_csv.py 5 Feb 2003 22:30:42 -0000 1.18 --- test_csv.py 6 Feb 2003 01:27:31 -0000 1.19 *************** *** 75,80 **** self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') parser.doublequote = 0 ! # FAIL - need to fix ! # self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') parser.quoting = csv.QUOTE_NONE self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') --- 75,79 ---- self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') parser.doublequote = 0 ! self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') parser.quoting = csv.QUOTE_NONE self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') From anthonybaxter@users.sourceforge.net Thu Feb 6 01:45:14 2003 From: anthonybaxter@users.sourceforge.net (anthonybaxter@users.sourceforge.net) Date: Wed, 05 Feb 2003 17:45:14 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libcmd.tex,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv23648/Doc/lib Modified Files: libcmd.tex Log Message: Updated version of [ 558544 ] cmd.py: add instance-specific stdin/out This patch adds stdin, stdout as optional arguments to the cmd.Cmd constructor (defaulting to sys.stdin, sys.stdout), and changes the Cmd methods throughout to use self.stdout.write() and self.stdin.foo for output and input. This allows much greater flexibility for using cmd - for instance, hooking it into a telnet server. Patch for library module and for documentation. Index: libcmd.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libcmd.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** libcmd.tex 27 Dec 2001 05:10:18 -0000 1.12 --- libcmd.tex 6 Feb 2003 01:45:11 -0000 1.13 *************** *** 12,16 **** later be wrapped in a more sophisticated interface. ! \begin{classdesc}{Cmd}{\optional{completekey}} A \class{Cmd} instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate --- 12,16 ---- later be wrapped in a more sophisticated interface. ! \begin{classdesc}{Cmd}{\optional{completekey},\optional{stdin},\optional{stdout}} A \class{Cmd} instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate *************** *** 19,26 **** \class{Cmd}'s methods and encapsulate action methods. ! The optional argument is the \refmodule{readline} name of a completion ! key; it defaults to \kbd{Tab}. If \var{completekey} is not \code{None} ! and \module{readline} is available, command completion is done ! automatically. \end{classdesc} --- 19,32 ---- \class{Cmd}'s methods and encapsulate action methods. ! The optional argument \var{completekey} is the \refmodule{readline} name ! of a completion key; it defaults to \kbd{Tab}. If \var{completekey} is ! not \code{None} and \module{readline} is available, command completion ! is done automatically. ! ! The optional arguments \var{stdin} and \var{stdout} specify the ! input and output file objects that the Cmd instance or subclass ! instance will use for input and output. If not specified, they ! will default to \var{sys.stdin} and \var{sys.stdout}. ! \end{classdesc} From anthonybaxter@users.sourceforge.net Thu Feb 6 01:45:13 2003 From: anthonybaxter@users.sourceforge.net (anthonybaxter@users.sourceforge.net) Date: Wed, 05 Feb 2003 17:45:13 -0800 Subject: [Python-checkins] python/dist/src/Lib cmd.py,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv23648/Lib Modified Files: cmd.py Log Message: Updated version of [ 558544 ] cmd.py: add instance-specific stdin/out This patch adds stdin, stdout as optional arguments to the cmd.Cmd constructor (defaulting to sys.stdin, sys.stdout), and changes the Cmd methods throughout to use self.stdout.write() and self.stdin.foo for output and input. This allows much greater flexibility for using cmd - for instance, hooking it into a telnet server. Patch for library module and for documentation. Index: cmd.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/cmd.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** cmd.py 3 Feb 2003 11:04:27 -0000 1.34 --- cmd.py 6 Feb 2003 01:45:10 -0000 1.35 *************** *** 46,50 **** """ ! import string, sys __all__ = ["Cmd"] --- 46,50 ---- """ ! import string __all__ = ["Cmd"] *************** *** 77,89 **** use_rawinput = 1 ! def __init__(self, completekey='tab'): """Instantiate a line-oriented interpreter framework. ! The optional argument is the readline name of a completion key; ! it defaults to the Tab key. If completekey is not None and the ! readline module is available, command completion is done ! automatically. """ self.cmdqueue = [] self.completekey = completekey --- 77,100 ---- use_rawinput = 1 ! def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. ! The optional argument 'completekey' is the readline name of a ! completion key; it defaults to the Tab key. If completekey is ! not None and the readline module is available, command completion ! is done automatically. The optional arguments stdin and stdout ! specify alternate input and output file objects; if not specified, ! sys.stdin and sys.stdout are used. """ + import sys + if stdin is not None: + self.stdin = stdin + else: + self.stdin = sys.stdin + if stdout is not None: + self.stdout = stdout + else: + self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey *************** *** 100,104 **** self.intro = intro if self.intro: ! print self.intro stop = None while not stop: --- 111,115 ---- self.intro = intro if self.intro: ! self.stdout.write(str(self.intro)+"\n") stop = None while not stop: *************** *** 112,118 **** line = 'EOF' else: ! sys.stdout.write(self.prompt) ! sys.stdout.flush() ! line = sys.stdin.readline() if not len(line): line = 'EOF' --- 123,129 ---- line = 'EOF' else: ! self.stdout.write(self.prompt) ! self.stdout.flush() ! line = self.stdin.readline() if not len(line): line = 'EOF' *************** *** 216,220 **** """ ! print '*** Unknown syntax:', line def completedefault(self, *ignored): --- 227,231 ---- """ ! self.stdout.write('*** Unknown syntax: %s\n'%line) def completedefault(self, *ignored): *************** *** 285,293 **** doc=getattr(self, 'do_' + arg).__doc__ if doc: ! print doc return except AttributeError: pass ! print self.nohelp % (arg,) return func() --- 296,304 ---- doc=getattr(self, 'do_' + arg).__doc__ if doc: ! self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass ! self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() *************** *** 316,320 **** else: cmds_undoc.append(cmd) ! print self.doc_leader self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) --- 327,331 ---- else: cmds_undoc.append(cmd) ! self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) *************** *** 323,331 **** def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: ! print header if self.ruler: ! print self.ruler * len(header) self.columnize(cmds, maxcol-1) ! print def columnize(self, list, displaywidth=80): --- 334,342 ---- def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: ! self.stdout.write("%s\n"%str(header)) if self.ruler: ! self.stdout.write("%s\n"%str(self.ruler * len(header))) self.columnize(cmds, maxcol-1) ! self.stdout.write("\n") def columnize(self, list, displaywidth=80): *************** *** 336,340 **** """ if not list: ! print "" return nonstrings = [i for i in range(len(list)) --- 347,351 ---- """ if not list: ! self.stdout.write("\n") return nonstrings = [i for i in range(len(list)) *************** *** 345,349 **** size = len(list) if size == 1: ! print list[0] return # Try every row count from 1 upwards --- 356,360 ---- size = len(list) if size == 1: ! self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards *************** *** 383,385 **** for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) ! print " ".join(texts) --- 394,396 ---- for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) ! self.stdout.write("%s\n"%str(" ".join(texts))) From montanaro@users.sourceforge.net Thu Feb 6 04:49:31 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 05 Feb 2003 20:49:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv29808 Modified Files: csv.py Log Message: add optional fieldnames and restfield params to csv.reader() which allow the reader to return rows as dicts Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** csv.py 5 Feb 2003 02:21:42 -0000 1.22 --- csv.py 6 Feb 2003 04:49:29 -0000 1.23 *************** *** 94,99 **** class reader(_OCcsv): ! def __init__(self, iterobj, dialect = 'excel', **options): self.iterobj = iter(iterobj) _OCcsv.__init__(self, dialect, **options) --- 94,103 ---- class reader(_OCcsv): ! def __init__(self, iterobj, dialect = 'excel', ! fieldnames=None, restfield=None, ! **options): self.iterobj = iter(iterobj) + self.fieldnames = fieldnames + self.restfield = restfield _OCcsv.__init__(self, dialect, **options) *************** *** 105,108 **** --- 109,119 ---- fields = self.parser.parse(self.iterobj.next()) if fields: + if self.fieldnames is not None: + lf = len(self.fieldnames) + result = dict(zip(self.fieldnames, fields)) + if (lf < len(fields) and + self.restfield is not None): + result[self.restfield] = fields[lf:] + return result return fields From montanaro@users.sourceforge.net Thu Feb 6 04:50:12 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 05 Feb 2003 20:50:12 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30062 Modified Files: libcsv.tex Log Message: add missing \subsection{} Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** libcsv.tex 3 Feb 2003 06:25:30 -0000 1.3 --- libcsv.tex 6 Feb 2003 04:50:10 -0000 1.4 *************** *** 34,37 **** --- 34,39 ---- preprocessing the data returned from a {}\code{cursor.fetch*()} call. + \subsection{Module Contents} + The \module{csv} module defines the following classes. From montanaro@users.sourceforge.net Thu Feb 6 04:51:50 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 05 Feb 2003 20:51:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv30597 Modified Files: test_csv.py Log Message: add tests for reader returning dicts Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** test_csv.py 6 Feb 2003 01:27:31 -0000 1.19 --- test_csv.py 6 Feb 2003 04:51:47 -0000 1.20 *************** *** 242,246 **** class TestDictFields(unittest.TestCase): ! def test_simple_dict(self): fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel", --- 242,246 ---- class TestDictFields(unittest.TestCase): ! def test_write_simple_dict(self): fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel", *************** *** 249,256 **** self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") ! def test_no_fields(self): fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") self.assertRaises(csv.Error, writer.writerow, {"f1": 10, "f3": "abc"}) class TestArrayWrites(unittest.TestCase): --- 249,272 ---- self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") ! def test_write_no_fields(self): fileobj = StringIO() writer = csv.writer(fileobj, dialect="excel") self.assertRaises(csv.Error, writer.writerow, {"f1": 10, "f3": "abc"}) + + def test_read_dict_fields(self): + reader = csv.reader(StringIO("1,2,abc\r\n"), dialect="excel", + fieldnames=["f1", "f2", "f3"]) + self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) + + def test_read_short(self): + reader = csv.reader(StringIO("1,2,abc,4,5,6\r\n"), dialect="excel", + fieldnames=["f1", "f2"]) + self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) + + def test_read_short_with_rest(self): + reader = csv.reader(StringIO("1,2,abc,4,5,6\r\n"), dialect="excel", + fieldnames=["f1", "f2"], restfield="_rest") + self.assertEqual(reader.next(), {"f1": '1', "f2": '2', + "_rest": ["abc", "4", "5", "6"]}) class TestArrayWrites(unittest.TestCase): From nnorwitz@users.sourceforge.net Thu Feb 6 05:02:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 05 Feb 2003 21:02:43 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libcmd.tex,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv1704/lib Modified Files: libcmd.tex Log Message: Provide version changed info Index: libcmd.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libcmd.tex,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** libcmd.tex 6 Feb 2003 01:45:11 -0000 1.13 --- libcmd.tex 6 Feb 2003 05:02:39 -0000 1.14 *************** *** 29,32 **** --- 29,33 ---- will default to \var{sys.stdin} and \var{sys.stdout}. + \versionchanged[The \var{stdin} and \var{stdout} parameters were added.]{2.3} \end{classdesc} From akuchling@users.sourceforge.net Thu Feb 6 14:38:50 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 06:38:50 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libwarnings.tex,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv5176 Modified Files: libwarnings.tex Log Message: Fix description of filterwarnings() parameters (error noted by Richard Jones at http://mechanicalcat.net/cgi-bin/log/python/turning_warnings_off.html) Index: libwarnings.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libwarnings.tex,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** libwarnings.tex 14 Aug 2002 16:40:54 -0000 1.10 --- libwarnings.tex 6 Feb 2003 14:38:45 -0000 1.11 *************** *** 117,128 **** \end{tableii} ! \item \var{message} is a compiled regular expression that the warning ! message must match (the match is case-insensitive) \item \var{category} is a class (a subclass of \exception{Warning}) of which the warning category must be a subclass in order to match ! \item \var{module} is a compiled regular expression that the module ! name must match \item \var{lineno} is an integer that the line number where the --- 117,129 ---- \end{tableii} ! \item \var{message} is a string containing a regular expression that ! the warning message must match (the match is compiled to always be ! case-insensitive) \item \var{category} is a class (a subclass of \exception{Warning}) of which the warning category must be a subclass in order to match ! \item \var{module} is a string containing a regular expression that the module ! name must match (the match is compiled to be case-sensitive) \item \var{lineno} is an integer that the line number where the From akuchling@users.sourceforge.net Thu Feb 6 15:14:08 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 07:14:08 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.112,1.113 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv24641 Modified Files: whatsnew23.tex Log Message: Mention FutureWarning for large ints Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** whatsnew23.tex 3 Feb 2003 15:16:15 -0000 1.112 --- whatsnew23.tex 6 Feb 2003 15:14:04 -0000 1.113 *************** *** 2074,2077 **** --- 2074,2082 ---- exists. + \item Large octal and hex literals such as + 0xffffffff now trigger a \exception{FutureWarning} because currently + they're stored as 32-bit numbers and result in a negative value, but + in Python 2.4 they'll become positive long integers. + \item You can no longer disable assertions by assigning to \code{__debug__}. From akuchling@users.sourceforge.net Thu Feb 6 15:22:52 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 07:22:52 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.203,2.204 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv29904 Modified Files: typeobject.c Log Message: Comment typo fix Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.203 retrieving revision 2.204 diff -C2 -d -r2.203 -r2.204 *** typeobject.c 5 Feb 2003 22:39:45 -0000 2.203 --- typeobject.c 6 Feb 2003 15:22:49 -0000 2.204 *************** *** 641,645 **** /* UnTrack and re-Track around the trashcan macro, alas */ ! /* See explanation at end of funtion for full disclosure */ PyObject_GC_UnTrack(self); ++_PyTrash_delete_nesting; --- 641,645 ---- /* UnTrack and re-Track around the trashcan macro, alas */ ! /* See explanation at end of function for full disclosure */ PyObject_GC_UnTrack(self); ++_PyTrash_delete_nesting; From jhylton@users.sourceforge.net Thu Feb 6 16:00:37 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:00:37 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.642,1.643 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv19916 Modified Files: NEWS Log Message: Add news item about __module__ attribute on functions. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.642 retrieving revision 1.643 diff -C2 -d -r1.642 -r1.643 *** NEWS 5 Feb 2003 18:29:34 -0000 1.642 --- NEWS 6 Feb 2003 16:00:15 -0000 1.643 *************** *** 31,34 **** --- 31,42 ---- See SF bug #676155. + - Function objects now have an __module__ attribute that is bound to + the name of the module in which the function was defined. This + attribute is used by pickle.whichmodule(), which changes the + behavior of whichmodule slightly. In Python 2.2 whichmodule() + returns "__main__" for functions that are not defined at the + top-level of a module (examples: methods, nested functions). Now + whichmodule() will return the proper module name. + Extension modules ----------------- From gvanrossum@users.sourceforge.net Thu Feb 6 16:16:53 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:16:53 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.643,1.644 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv29015 Modified Files: NEWS Log Message: Clarify that __module__ applies to various type of functions. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.643 retrieving revision 1.644 diff -C2 -d -r1.643 -r1.644 *** NEWS 6 Feb 2003 16:00:15 -0000 1.643 --- NEWS 6 Feb 2003 16:16:50 -0000 1.644 *************** *** 31,41 **** See SF bug #676155. ! - Function objects now have an __module__ attribute that is bound to the name of the module in which the function was defined. This ! attribute is used by pickle.whichmodule(), which changes the ! behavior of whichmodule slightly. In Python 2.2 whichmodule() ! returns "__main__" for functions that are not defined at the ! top-level of a module (examples: methods, nested functions). Now ! whichmodule() will return the proper module name. Extension modules --- 31,42 ---- See SF bug #676155. ! - Function objects now have a __module__ attribute that is bound to the name of the module in which the function was defined. This ! applies for C functions and methods as well as functions and methods ! defined in Python. This attribute is used by pickle.whichmodule(), ! which changes the behavior of whichmodule slightly. In Python 2.2 ! whichmodule() returns "__main__" for functions that are not defined ! at the top-level of a module (examples: methods, nested functions). ! Now whichmodule() will return the proper module name. Extension modules From jhylton@users.sourceforge.net Thu Feb 6 16:22:04 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:22:04 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.144,1.145 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv31570 Modified Files: pickle.py Log Message: Replace hasattr() + getattr() with single getattr() and default value. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.144 retrieving revision 1.145 diff -C2 -d -r1.144 -r1.145 *** pickle.py 4 Feb 2003 01:54:48 -0000 1.144 --- pickle.py 6 Feb 2003 16:22:01 -0000 1.145 *************** *** 944,949 **** continue # skip dummy package entries if name != '__main__' and \ ! hasattr(module, funcname) and \ ! getattr(module, funcname) is func: break else: --- 944,948 ---- continue # skip dummy package entries if name != '__main__' and \ ! getattr(module, funcname, None) is func: break else: From jhylton@users.sourceforge.net Thu Feb 6 16:23:03 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:23:03 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.145,1.146 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv32272 Modified Files: pickle.py Log Message: No need for a continuation line. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.145 retrieving revision 1.146 diff -C2 -d -r1.145 -r1.146 *** pickle.py 6 Feb 2003 16:22:01 -0000 1.145 --- pickle.py 6 Feb 2003 16:23:01 -0000 1.146 *************** *** 943,948 **** if module is None: continue # skip dummy package entries ! if name != '__main__' and \ ! getattr(module, funcname, None) is func: break else: --- 943,947 ---- if module is None: continue # skip dummy package entries ! if name != '__main__' and getattr(module, funcname, None) is func: break else: From tim_one@users.sourceforge.net Thu Feb 6 16:32:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:32:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_datetime.py,1.111,1.112 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4898 Modified Files: test_datetime.py Log Message: SF bug 680864: test_datetime fails for non-unix epoch Apparently MAC OS 9 doesn't have POSIX-conforming timestamps. A test fails as a result, but at least for this specific test it's easy enough to get the POSIX epoch out of it. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.111 retrieving revision 1.112 diff -C2 -d -r1.111 -r1.112 *** test_datetime.py 5 Feb 2003 22:29:00 -0000 1.111 --- test_datetime.py 6 Feb 2003 16:32:31 -0000 1.112 *************** *** 2258,2273 **** # Try to make sure tz= actually does some conversion. ! timestamp = 1000000000 # 2001-09-09 01:46:40 UTC, give or take ! utc = FixedOffset(0, "utc", 0) ! expected = datetime(2001, 9, 9, 1, 46, 40) ! got = datetime.utcfromtimestamp(timestamp) ! # We don't support leap seconds, but maybe the platfrom insists ! # on using them, so don't demand exact equality). ! self.failUnless(abs(got - expected) < timedelta(minutes=1)) ! ! est = FixedOffset(-5*60, "est", 0) ! expected -= timedelta(hours=5) ! got = datetime.fromtimestamp(timestamp, est).replace(tzinfo=None) ! self.failUnless(abs(got - expected) < timedelta(minutes=1)) def test_tzinfo_utcnow(self): --- 2258,2272 ---- # Try to make sure tz= actually does some conversion. ! timestamp = 1000000000 ! utcdatetime = datetime.utcfromtimestamp(timestamp) ! # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take. ! # But on some flavor of Mac, it's nowhere near that. So we can't have ! # any idea here what time that actually is, we can only test that ! # relative changes match. ! utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero ! tz = FixedOffset(utcoffset, "tz", 0) ! expected = utcdatetime + utcoffset ! got = datetime.fromtimestamp(timestamp, tz) ! self.assertEqual(expected, got.replace(tzinfo=None)) def test_tzinfo_utcnow(self): From tim_one@users.sourceforge.net Thu Feb 6 16:42:17 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 08:42:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.35,1.36 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv10637/python/Lib/test Modified Files: test_datetime.py Log Message: SF bug 680864: test_datetime fails for non-unix epoch Apparently MAC OS 9 doesn't have POSIX-conforming timestamps. A test fails as a result, but at least for this specific test it's easy enough to get the POSIX epoch out of it. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** test_datetime.py 5 Feb 2003 04:08:07 -0000 1.35 --- test_datetime.py 6 Feb 2003 16:42:14 -0000 1.36 *************** *** 2258,2273 **** # Try to make sure tz= actually does some conversion. ! timestamp = 1000000000 # 2001-09-09 01:46:40 UTC, give or take ! utc = FixedOffset(0, "utc", 0) ! expected = datetime(2001, 9, 9, 1, 46, 40) ! got = datetime.utcfromtimestamp(timestamp) ! # We don't support leap seconds, but maybe the platfrom insists ! # on using them, so don't demand exact equality). ! self.failUnless(abs(got - expected) < timedelta(minutes=1)) ! ! est = FixedOffset(-5*60, "est", 0) ! expected -= timedelta(hours=5) ! got = datetime.fromtimestamp(timestamp, est).replace(tzinfo=None) ! self.failUnless(abs(got - expected) < timedelta(minutes=1)) def test_tzinfo_utcnow(self): --- 2258,2272 ---- # Try to make sure tz= actually does some conversion. ! timestamp = 1000000000 ! utcdatetime = datetime.utcfromtimestamp(timestamp) ! # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take. ! # But on some flavor of Mac, it's nowhere near that. So we can't have ! # any idea here what time that actually is, we can only test that ! # relative changes match. ! utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero ! tz = FixedOffset(utcoffset, "tz", 0) ! expected = utcdatetime + utcoffset ! got = datetime.fromtimestamp(timestamp, tz) ! self.assertEqual(expected, got.replace(tzinfo=None)) def test_tzinfo_utcnow(self): From akuchling@users.sourceforge.net Thu Feb 6 17:42:47 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 09:42:47 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_filecmp.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv8315 Added Files: test_filecmp.py Log Message: Add test suite for filecmp.py, after some discussion on bug #680494. Right now the test cases create a files and a directory in the temp. directory. Raymond suggested checking files in to the test/ directory, simplifying the setup/teardown methods; is that worth doing? --- NEW FILE: test_filecmp.py --- import os, filecmp, shutil, tempfile import unittest from test import test_support class FileCompareTestCase(unittest.TestCase): def setUp(self): self.name = test_support.TESTFN self.name_same = test_support.TESTFN + '-same' self.name_diff = test_support.TESTFN + '-diff' data = 'Contents of file go here.\n' for name in [self.name, self.name_same, self.name_diff]: output = open(name, 'w') output.write(data) output.close() output = open(self.name_diff, 'a+') output.write('An extra line.\n') output.close() self.dir = tempfile.gettempdir() def tearDown(self): os.unlink(self.name) os.unlink(self.name_same) os.unlink(self.name_diff) def test_matching(self): self.failUnless(filecmp.cmp(self.name, self.name_same), "Comparing file to itself fails") self.failUnless(filecmp.cmp(self.name, self.name_same, shallow=False), "Comparing file to itself fails") self.failUnless(filecmp.cmp(self.name, self.name, shallow=False), "Comparing file to identical file fails") self.failUnless(filecmp.cmp(self.name, self.name), "Comparing file to identical file fails") def test_different(self): self.failIf(filecmp.cmp(self.name, self.name_diff), "Mismatched files compare as equal") self.failIf(filecmp.cmp(self.name, self.dir), "File and directory compare as equal") class DirCompareTestCase(unittest.TestCase): def setUp(self): tmpdir = tempfile.gettempdir() self.dir = os.path.join(tmpdir, 'dir') self.dir_same = os.path.join(tmpdir, 'dir-same') self.dir_diff = os.path.join(tmpdir, 'dir-diff') data = 'Contents of file go here.\n' for dir in [self.dir, self.dir_same, self.dir_diff]: os.mkdir(dir) output = open(os.path.join(dir, 'file'), 'w') output.write(data) output.close() output = open(os.path.join(self.dir_diff, 'file2'), 'w') output.write('An extra file.\n') output.close() def tearDown(self): shutil.rmtree(self.dir) shutil.rmtree(self.dir_same) shutil.rmtree(self.dir_diff) def test_cmpfiles(self): self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file']) == (['file'], [], []), "Comparing directory to itself fails") self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) == (['file'], [], []), "Comparing directory to same fails") # Try it with shallow=False self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file'], shallow=False) == (['file'], [], []), "Comparing directory to itself fails") self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file'], shallow=False), "Comparing directory to same fails") # Add different file2 output = open(os.path.join(self.dir, 'file2'), 'w') output.write('Different contents.\n') output.close() self.failIf(filecmp.cmpfiles(self.dir, self.dir_same, ['file', 'file2']) == (['file'], ['file2'], []), "Comparing mismatched directories fails") def test_dircmp(self): # Check attributes for comparison of two identical directories d = filecmp.dircmp(self.dir, self.dir_same) self.failUnless(d.left_list == d.right_list == ['file']) self.failUnless(d.common == ['file']) self.failUnless(d.left_only == d.right_only == []) self.failUnless(d.same_files == ['file']) self.failUnless(d.diff_files == []) # Check attributes for comparison of two different directories d = filecmp.dircmp(self.dir, self.dir_diff) self.failUnless(d.left_list == ['file']) self.failUnless(d.right_list == ['file', 'file2']) self.failUnless(d.common == ['file']) self.failUnless(d.left_only == []) self.failUnless(d.right_only == ['file2']) self.failUnless(d.same_files == ['file']) self.failUnless(d.diff_files == []) # Add different file2 output = open(os.path.join(self.dir, 'file2'), 'w') output.write('Different contents.\n') output.close() d = filecmp.dircmp(self.dir, self.dir_diff) self.failUnless(d.same_files == ['file']) self.failUnless(d.diff_files == ['file2']) def test_main(): suite = unittest.TestSuite() for cls in FileCompareTestCase, DirCompareTestCase: suite.addTest(unittest.makeSuite(cls)) test_support.run_suite(suite) if __name__ == "__main__": test_main() From akuchling@users.sourceforge.net Thu Feb 6 17:50:03 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 09:50:03 -0800 Subject: [Python-checkins] python/dist/src/Lib filecmp.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv12521 Modified Files: filecmp.py Log Message: [Bug #680494] filecmp.py uses obsolete statcache module. Simply replace all uses of statcache with os.stat. Should I add a DeprecationWarning triggered if the use_statcache argument is supplied, so we can remove it in 2.4? Index: filecmp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/filecmp.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** filecmp.py 2 Jun 2002 18:55:56 -0000 1.13 --- filecmp.py 6 Feb 2003 17:50:01 -0000 1.14 *************** *** 12,16 **** import os import stat - import statcache __all__ = ["cmp","dircmp","cmpfiles"] --- 12,15 ---- *************** *** 31,36 **** defaults to 1. ! use_statcache -- Do not stat() each file directly: go through ! the statcache module for more efficiency. Return value: --- 30,34 ---- defaults to 1. ! use_statcache -- obsolete argument. Return value: *************** *** 40,53 **** This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. - Of course, if 'use_statcache' is true, this mechanism is defeated, - and the cache will never grow stale. """ ! if use_statcache: ! stat_function = statcache.stat ! else: ! stat_function = os.stat ! s1 = _sig(stat_function(f1)) ! s2 = _sig(stat_function(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False --- 38,45 ---- This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. """ ! s1 = _sig(os.stat(f1)) ! s2 = _sig(os.stat(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False *************** *** 189,198 **** ok = 1 try: ! a_stat = statcache.stat(a_path) except os.error, why: # print 'Can\'t stat', a_path, ':', why[1] ok = 0 try: ! b_stat = statcache.stat(b_path) except os.error, why: # print 'Can\'t stat', b_path, ':', why[1] --- 181,190 ---- ok = 1 try: ! a_stat = os.stat(a_path) except os.error, why: # print 'Can\'t stat', a_path, ':', why[1] ok = 0 try: ! b_stat = os.stat(b_path) except os.error, why: # print 'Can\'t stat', b_path, ':', why[1] *************** *** 276,280 **** common -- list of file names found in both directories shallow -- if true, do comparison based solely on stat() information ! use_statcache -- if true, use statcache.stat() instead of os.stat() Returns a tuple of three lists: --- 268,272 ---- common -- list of file names found in both directories shallow -- if true, do comparison based solely on stat() information ! use_statcache -- obsolete argument Returns a tuple of three lists: *************** *** 288,292 **** ax = os.path.join(a, x) bx = os.path.join(b, x) ! res[_cmp(ax, bx, shallow, use_statcache)].append(x) return res --- 280,284 ---- ax = os.path.join(a, x) bx = os.path.join(b, x) ! res[_cmp(ax, bx, shallow)].append(x) return res *************** *** 298,304 **** # 2 for funny cases (can't stat, etc.) # ! def _cmp(a, b, sh, st): try: ! return not abs(cmp(a, b, sh, st)) except os.error: return 2 --- 290,296 ---- # 2 for funny cases (can't stat, etc.) # ! def _cmp(a, b, sh): try: ! return not abs(cmp(a, b, sh)) except os.error: return 2 From gvanrossum@users.sourceforge.net Thu Feb 6 17:52:17 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 09:52:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv14233 Added Files: test_copy.py Log Message: A test suite for the copy module. This should provide full code coverage. --- NEW FILE: test_copy.py --- """Unit tests for the copy module.""" import sys import copy import unittest from test import test_support class TestCopy(unittest.TestCase): # Attempt full line coverage of copy.py from top to bottom def test_exceptions(self): self.assert_(copy.Error is copy.error) self.assert_(issubclass(copy.Error, Exception)) # The copy() method def test_copy_basic(self): x = 42 y = copy.copy(x) self.assertEqual(x, y) def test_copy_copy(self): class C(object): def __init__(self, foo): self.foo = foo def __copy__(self): return C(self.foo) x = C(42) y = copy.copy(x) self.assertEqual(y.__class__, x.__class__) self.assertEqual(y.foo, x.foo) def test_copy_reduce(self): class C(object): def __reduce__(self): return "" x = C() y = copy.copy(x) self.assert_(y is x) def test_copy_cant(self): class C(object): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.copy, x) # Type-specific _copy_xxx() methods def test_copy_atomic(self): class Classic: pass class NewStyle(object): pass def f(): pass tests = [None, 42, 2L**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10), Classic] for x in tests: self.assert_(copy.copy(x) is x, `x`) def test_copy_list(self): x = [1, 2, 3] self.assertEqual(copy.copy(x), x) def test_copy_tuple(self): x = (1, 2, 3) self.assertEqual(copy.copy(x), x) def test_copy_dict(self): x = {"foo": 1, "bar": 2} self.assertEqual(copy.copy(x), x) def test_copy_inst_vanilla(self): class C: def __init__(self, foo): self.foo = foo def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_copy(self): class C: def __init__(self, foo): self.foo = foo def __copy__(self): return C(self.foo) def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getinitargs(self): class C: def __init__(self, foo): self.foo = foo def __getinitargs__(self): return (self.foo,) def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return {"foo": self.foo} def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_setstate(self): class C: def __init__(self, foo): self.foo = foo def __setstate__(self, state): self.foo = state["foo"] def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) def test_copy_inst_getstate_setstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return self.foo def __setstate__(self, state): self.foo = state def __cmp__(self, other): return cmp(self.foo, other.foo) x = C(42) self.assertEqual(copy.copy(x), x) # The deepcopy() method def test_deepcopy_basic(self): x = 42 y = copy.deepcopy(x) self.assertEqual(y, x) def test_deepcopy_memo(self): x = [] x.append(x) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y[0] is not x[0]) self.assert_(y is y[0]) def test_deepcopy_issubclass(self): # XXX Note: there's no way to test the TypeError coming out of # issubclass() -- this can only happen when an extension # module defines a "type" that doesn't formally inherit from # type. class Meta(type): pass class C: __metaclass__ = Meta self.assertEqual(copy.deepcopy(C), C) def test_deepcopy_deepcopy(self): class C(object): def __init__(self, foo): self.foo = foo def __deepcopy__(self, memo=None): return C(self.foo) x = C(42) y = copy.deepcopy(x) self.assertEqual(y.__class__, x.__class__) self.assertEqual(y.foo, x.foo) def test_deepcopy_reduce(self): class C(object): def __reduce__(self): return "" x = C() y = copy.deepcopy(x) self.assert_(y is x) def test_deepcopy_cant(self): class C(object): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.deepcopy, x) # Type-specific _deepcopy_xxx() methods def test_deepcopy_atomic(self): class Classic: pass class NewStyle(object): pass def f(): pass tests = [None, 42, 2L**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10)] for x in tests: self.assert_(copy.deepcopy(x) is x, `x`) def test_deepcopy_list(self): x = [[1, 2], 3] y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(x is not y) self.assert_(x[0] is not y[0]) def test_deepcopy_tuple(self): x = ([1, 2], 3) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(x is not y) self.assert_(x[0] is not y[0]) def test_deepcopy_dict(self): x = {"foo": [1, 2], "bar": 3} y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(x is not y) self.assert_(x["foo"] is not y["foo"]) def test_deepcopy_keepalive(self): memo = {} x = 42 y = copy.deepcopy(x, memo) self.assert_(memo[id(x)] is x) def test_deepcopy_inst_vanilla(self): class C: def __init__(self, foo): self.foo = foo def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y.foo is not x.foo) def test_deepcopy_inst_deepcopy(self): class C: def __init__(self, foo): self.foo = foo def __deepcopy__(self, memo): return C(copy.deepcopy(self.foo, memo)) def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y.foo is not x.foo) def test_deepcopy_inst_getinitargs(self): class C: def __init__(self, foo): self.foo = foo def __getinitargs__(self): return (self.foo,) def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y.foo is not x.foo) def test_deepcopy_inst_getstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return {"foo": self.foo} def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y.foo is not x.foo) def test_deepcopy_inst_setstate(self): class C: def __init__(self, foo): self.foo = foo def __setstate__(self, state): self.foo = state["foo"] def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y.foo is not x.foo) def test_deepcopy_inst_getstate_setstate(self): class C: def __init__(self, foo): self.foo = foo def __getstate__(self): return self.foo def __setstate__(self, state): self.foo = state def __cmp__(self, other): return cmp(self.foo, other.foo) x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y is not x) self.assert_(y.foo is not x.foo) # _reconstruct() def test_reconstruct_string(self): class C(object): def __reduce__(self): return "" x = C() y = copy.copy(x) self.assert_(y is x) y = copy.deepcopy(x) self.assert_(y is x) def test_reconstruct_nostate(self): class C(object): def __reduce__(self): return (C, ()) x = C() x.foo = 42 y = copy.copy(x) self.assert_(y.__class__ is x.__class__) y = copy.deepcopy(x) self.assert_(y.__class__ is x.__class__) def test_reconstruct_state(self): class C(object): def __reduce__(self): return (C, (), self.__dict__) def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) x = C() x.foo = [42] y = copy.copy(x) self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y.foo is not x.foo) def test_reconstruct_state_setstate(self): class C(object): def __reduce__(self): return (C, (), self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def __cmp__(self, other): return cmp(self.__dict__, other.__dict__) x = C() x.foo = [42] y = copy.copy(x) self.assertEqual(y, x) y = copy.deepcopy(x) self.assertEqual(y, x) self.assert_(y.foo is not x.foo) def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestCopy)) test_support.run_suite(suite) if __name__ == "__main__": test_main() From akuchling@users.sourceforge.net Thu Feb 6 17:57:17 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 09:57:17 -0800 Subject: [Python-checkins] python/nondist/peps pep-0042.txt,1.67,1.68 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv16637 Modified Files: pep-0042.txt Log Message: Add a wish Index: pep-0042.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0042.txt,v retrieving revision 1.67 retrieving revision 1.68 diff -C2 -d -r1.67 -r1.68 *** pep-0042.txt 5 Feb 2003 20:21:49 -0000 1.67 --- pep-0042.txt 6 Feb 2003 17:57:14 -0000 1.68 *************** *** 242,245 **** --- 242,249 ---- http://www.python.org/sf/405554 + - Distutils should deduce dependencies for .c and .h files. + + http://www.python.org/sf/472881 + C API wishes From akuchling@users.sourceforge.net Thu Feb 6 18:04:54 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 10:04:54 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libpopen2.tex,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv22317 Modified Files: libpopen2.tex Log Message: Typo fixes Index: libpopen2.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpopen2.tex,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** libpopen2.tex 6 Dec 2002 16:45:05 -0000 1.18 --- libpopen2.tex 6 Feb 2003 18:04:43 -0000 1.19 *************** *** 58,62 **** \function{popen3()} factory functions described above. ! If not using one off the helper functions to create \class{Popen3} objects, the parameter \var{cmd} is the shell command to execute in a sub-process. The \var{capturestderr} flag, if true, specifies that --- 58,62 ---- \function{popen3()} factory functions described above. ! If not using one of the helper functions to create \class{Popen3} objects, the parameter \var{cmd} is the shell command to execute in a sub-process. The \var{capturestderr} flag, if true, specifies that *************** *** 130,134 **** When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! out, a deadlock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in --- 130,134 ---- When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! output, a deadlock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in From gvanrossum@users.sourceforge.net Thu Feb 6 18:18:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 10:18:26 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.30,1.31 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv827 Modified Files: copy.py Log Message: Support __reduce__ returning a 4-tuple or 5-tuple. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** copy.py 16 Jan 2003 10:40:00 -0000 1.30 --- copy.py 6 Feb 2003 18:18:23 -0000 1.31 *************** *** 298,302 **** memo = {} n = len(info) ! assert n in (2, 3) callable, args = info[:2] if n > 2: --- 298,302 ---- memo = {} n = len(info) ! assert n in (2, 3, 4, 5) callable, args = info[:2] if n > 2: *************** *** 304,310 **** --- 304,329 ---- else: state = {} + if n > 3: + listiter = info[3] + else: + listiter = None + if n > 4: + dictiter = info[4] + else: + dictiter = None if deep: args = deepcopy(args, memo) y = callable(*args) + if listiter is not None: + for item in listiter: + if deep: + item = deepcopy(item, memo) + y.append(item) + if dictiter is not None: + for key, value in dictiter: + if deep: + key = deepcopy(key, memo) + value = deepcopy(value, memo) + y[key] = value if state: if deep: From gvanrossum@users.sourceforge.net Thu Feb 6 18:18:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 10:18:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv827/test Modified Files: test_copy.py Log Message: Support __reduce__ returning a 4-tuple or 5-tuple. Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_copy.py 6 Feb 2003 17:52:15 -0000 1.1 --- test_copy.py 6 Feb 2003 18:18:23 -0000 1.2 *************** *** 376,379 **** --- 376,415 ---- self.assert_(y.foo is not x.foo) + # Additions for Python 2.3 and pickle protocol 2 + + def test_reduce_4tuple(self): + class C(list): + def __reduce__(self): + return (C, (), self.__dict__, iter(self)) + def __cmp__(self, other): + return (cmp(list(self), list(other)) or + cmp(self.__dict__, other.__dict__)) + x = C([[1, 2], 3]) + y = copy.copy(x) + self.assertEqual(x, y) + self.assert_(x is not y) + self.assert_(x[0] is y[0]) + y = copy.deepcopy(x) + self.assertEqual(x, y) + self.assert_(x is not y) + self.assert_(x[0] is not y[0]) + + def test_reduce_5tuple(self): + class C(dict): + def __reduce__(self): + return (C, (), self.__dict__, None, self.iteritems()) + def __cmp__(self, other): + return (cmp(dict(self), list(dict)) or + cmp(self.__dict__, other.__dict__)) + x = C([("foo", [1, 2]), ("bar", 3)]) + y = copy.copy(x) + self.assertEqual(x, y) + self.assert_(x is not y) + self.assert_(x["foo"] is y["foo"]) + y = copy.deepcopy(x) + self.assertEqual(x, y) + self.assert_(x is not y) + self.assert_(x["foo"] is not y["foo"]) + def test_main(): suite = unittest.TestSuite() From mwh@users.sourceforge.net Thu Feb 6 18:37:14 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 06 Feb 2003 10:37:14 -0800 Subject: [Python-checkins] python/dist/src/Doc/api newtypes.tex,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv11136/api Modified Files: newtypes.tex Log Message: Correct lie about METH_NOARGS functions. Backport candidate. Index: newtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/newtypes.tex,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** newtypes.tex 31 Jan 2003 05:44:25 -0000 1.19 --- newtypes.tex 6 Feb 2003 18:37:11 -0000 1.20 *************** *** 245,249 **** (often called \var{args}) is a tuple object representing all arguments. This parameter is typically processed using ! \cfunction{PyArg_ParseTuple()}. \end{datadesc} --- 245,249 ---- (often called \var{args}) is a tuple object representing all arguments. This parameter is typically processed using ! \cfunction{PyArg_ParseTuple()} or \cfunction{PyArg_UnpackTuple}. \end{datadesc} *************** *** 260,267 **** Methods without parameters don't need to check whether arguments are given if they are listed with the \constant{METH_NOARGS} flag. They ! need to be of type \ctype{PyNoArgsFunction}: they expect a single ! single \ctype{PyObject*} as a parameter. When used with object ! methods, this parameter is typically named \code{self} and will hold ! a reference to the object instance. \end{datadesc} --- 260,267 ---- Methods without parameters don't need to check whether arguments are given if they are listed with the \constant{METH_NOARGS} flag. They ! need to be of type \ctype{PyCFunction}. When used with object ! methods, the first parameter is typically named \code{self} and will ! hold a reference to the object instance. In all cases the second ! parameter will be \NULL. \end{datadesc} From mwh@users.sourceforge.net Thu Feb 6 18:38:14 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 06 Feb 2003 10:38:14 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext extending.tex,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv11801/ext Modified Files: extending.tex Log Message: Remove another lie. Index: extending.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/extending.tex,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** extending.tex 19 Jul 2002 06:55:41 -0000 1.22 --- extending.tex 6 Feb 2003 18:38:11 -0000 1.23 *************** *** 819,826 **** this is done using the functions \cfunction{malloc()} and \cfunction{free()}. In \Cpp, the operators \keyword{new} and ! \keyword{delete} are used with essentially the same meaning; they are ! actually implemented using \cfunction{malloc()} and ! \cfunction{free()}, so we'll restrict the following discussion to the ! latter. Every block of memory allocated with \cfunction{malloc()} should --- 819,824 ---- this is done using the functions \cfunction{malloc()} and \cfunction{free()}. In \Cpp, the operators \keyword{new} and ! \keyword{delete} are used with essentially the same meaning and ! we'll restrict the following discussion to the latter. Every block of memory allocated with \cfunction{malloc()} should From gvanrossum@users.sourceforge.net Thu Feb 6 19:30:42 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:30:42 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.146,1.147 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv5442 Modified Files: pickle.py Log Message: Remove a debug print statement. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.146 retrieving revision 1.147 diff -C2 -d -r1.146 -r1.147 *** pickle.py 6 Feb 2003 16:23:01 -0000 1.146 --- pickle.py 6 Feb 2003 19:30:38 -0000 1.147 *************** *** 489,493 **** "without defining __getstate__ " "cannot be pickled"): - print repr(str(err)) raise # Not that specific exception getstate = None --- 489,492 ---- From akuchling@users.sourceforge.net Thu Feb 6 19:38:51 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:38:51 -0800 Subject: [Python-checkins] python/dist/src/Lib filecmp.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv9270 Modified Files: filecmp.py Log Message: Add DeprecationWarning when use_statcache argument is supplied Fix use of GetoptError, so demo() now works Index: filecmp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/filecmp.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** filecmp.py 6 Feb 2003 17:50:01 -0000 1.14 --- filecmp.py 6 Feb 2003 19:38:45 -0000 1.15 *************** *** 5,9 **** Functions: ! cmp(f1, f2, shallow=1, use_statcache=0) -> int cmpfiles(a, b, common) -> ([], [], []) --- 5,9 ---- Functions: ! cmp(f1, f2, shallow=1) -> int cmpfiles(a, b, common) -> ([], [], []) *************** *** 12,15 **** --- 12,16 ---- import os import stat + import warnings __all__ = ["cmp","dircmp","cmpfiles"] *************** *** 18,22 **** BUFSIZE=8*1024 ! def cmp(f1, f2, shallow=1, use_statcache=0): """Compare two files. --- 19,23 ---- BUFSIZE=8*1024 ! def cmp(f1, f2, shallow=1, use_statcache=None): """Compare two files. *************** *** 40,43 **** --- 41,48 ---- """ + if use_statcache is not None: + warnings.warn("use_statcache argument is deprecated", + DeprecationWarning) + s1 = _sig(os.stat(f1)) s2 = _sig(os.stat(f2)) *************** *** 262,266 **** ! def cmpfiles(a, b, common, shallow=1, use_statcache=0): """Compare common files in two directories. --- 267,271 ---- ! def cmpfiles(a, b, common, shallow=1, use_statcache=None): """Compare common files in two directories. *************** *** 276,279 **** --- 281,287 ---- """ + if use_statcache is not None: + warnings.warn("use_statcache argument is deprecated", + DeprecationWarning) res = ([], [], []) for x in common: *************** *** 313,317 **** options, args = getopt.getopt(sys.argv[1:], 'r') if len(args) != 2: ! raise getopt.error, 'need exactly two args' dd = dircmp(args[0], args[1]) if ('-r', '') in options: --- 321,325 ---- options, args = getopt.getopt(sys.argv[1:], 'r') if len(args) != 2: ! raise getopt.GetoptError('need exactly two args', None) dd = dircmp(args[0], args[1]) if ('-r', '') in options: From akuchling@users.sourceforge.net Thu Feb 6 19:52:59 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:52:59 -0800 Subject: [Python-checkins] python/dist/src/Lib getopt.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv15856 Modified Files: getopt.py Log Message: A few naughty external scripts do 'raise getopt.error, "blah"', and now crash because two arguments are expected. Add a default value to keep those scripts running. Index: getopt.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/getopt.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** getopt.py 4 Aug 2002 17:22:59 -0000 1.23 --- getopt.py 6 Feb 2003 19:52:56 -0000 1.24 *************** *** 40,44 **** opt = '' msg = '' ! def __init__(self, msg, opt): self.msg = msg self.opt = opt --- 40,44 ---- opt = '' msg = '' ! def __init__(self, msg, opt=''): self.msg = msg self.opt = opt From gvanrossum@users.sourceforge.net Thu Feb 6 19:53:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:53:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15843/test Modified Files: test_copy.py Log Message: Support all the new stuff supported by the new pickle code: - subclasses of list or dict - __reduce__ returning a 4-tuple or 5-tuple - slots Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_copy.py 6 Feb 2003 18:18:23 -0000 1.2 --- test_copy.py 6 Feb 2003 19:53:22 -0000 1.3 *************** *** 42,50 **** def test_copy_cant(self): ! class C(object): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.copy, x) --- 42,52 ---- def test_copy_cant(self): ! class Meta(type): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) + class C: + __metaclass__ = Meta x = C() self.assertRaises(copy.Error, copy.copy, x) *************** *** 190,198 **** def test_deepcopy_cant(self): ! class C(object): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.deepcopy, x) --- 192,202 ---- def test_deepcopy_cant(self): ! class Meta(type): def __getattribute__(self, name): if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) + class C: + __metaclass__ = Meta x = C() self.assertRaises(copy.Error, copy.deepcopy, x) *************** *** 411,414 **** --- 415,457 ---- self.assert_(x is not y) self.assert_(x["foo"] is not y["foo"]) + + def test_copy_slots(self): + class C(object): + __slots__ = ["foo"] + x = C() + x.foo = [42] + y = copy.copy(x) + self.assert_(x.foo is y.foo) + + def test_deepcopy_slots(self): + class C(object): + __slots__ = ["foo"] + x = C() + x.foo = [42] + y = copy.deepcopy(x) + self.assertEqual(x.foo, y.foo) + self.assert_(x.foo is not y.foo) + + def test_copy_list_subclass(self): + class C(list): + pass + x = C([[1, 2], 3]) + x.foo = [4, 5] + y = copy.copy(x) + self.assertEqual(list(x), list(y)) + self.assertEqual(x.foo, y.foo) + self.assert_(x[0] is y[0]) + self.assert_(x.foo is y.foo) + + def test_deepcopy_list_subclass(self): + class C(list): + pass + x = C([[1, 2], 3]) + x.foo = [4, 5] + y = copy.deepcopy(x) + self.assertEqual(list(x), list(y)) + self.assertEqual(x.foo, y.foo) + self.assert_(x[0] is not y[0]) + self.assert_(x.foo is not y.foo) def test_main(): From gvanrossum@users.sourceforge.net Thu Feb 6 19:53:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:53:24 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv15843 Modified Files: copy.py Log Message: Support all the new stuff supported by the new pickle code: - subclasses of list or dict - __reduce__ returning a 4-tuple or 5-tuple - slots Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** copy.py 6 Feb 2003 18:18:23 -0000 1.31 --- copy.py 6 Feb 2003 19:53:22 -0000 1.32 *************** *** 8,12 **** x = copy.deepcopy(y) # make a deep copy of y ! For module specific errors, copy.error is raised. The difference between shallow and deep copying is only relevant for --- 8,12 ---- x = copy.deepcopy(y) # make a deep copy of y ! For module specific errors, copy.Error is raised. The difference between shallow and deep copying is only relevant for *************** *** 52,55 **** --- 52,56 ---- import types + from pickle import _slotnames class Error(Exception): *************** *** 62,66 **** PyStringMap = None ! __all__ = ["Error", "error", "copy", "deepcopy"] def copy(x): --- 63,67 ---- PyStringMap = None ! __all__ = ["Error", "copy", "deepcopy"] def copy(x): *************** *** 77,86 **** except AttributeError: try: ! reductor = x.__reduce__ except AttributeError: ! raise error, \ ! "un(shallow)copyable object of type %s" % type(x) else: ! y = _reconstruct(x, reductor(), 0) else: y = copier() --- 78,88 ---- except AttributeError: try: ! reductor = x.__class__.__reduce__ ! if reductor == object.__reduce__: ! reductor = _better_reduce except AttributeError: ! raise Error("un(shallow)copyable object of type %s" % type(x)) else: ! y = _reconstruct(x, reductor(x), 0) else: y = copier() *************** *** 89,92 **** --- 91,135 ---- return y + def __newobj__(cls, *args): + return cls.__new__(cls, *args) + + def _better_reduce(obj): + cls = obj.__class__ + getnewargs = getattr(obj, "__getnewargs__", None) + if getnewargs: + args = getnewargs() + else: + args = () + getstate = getattr(obj, "__getstate__", None) + if getstate: + try: + state = getstate() + except TypeError, err: + # XXX Catch generic exception caused by __slots__ + if str(err) != ("a class that defines __slots__ " + "without defining __getstate__ " + "cannot be pickled"): + raise # Not that specific exception + getstate = None + if not getstate: + state = getattr(obj, "__dict__", None) + names = _slotnames(cls) + if names: + slots = {} + nil = [] + for name in names: + value = getattr(obj, name, nil) + if value is not nil: + slots[name] = value + if slots: + state = (state, slots) + listitems = dictitems = None + if isinstance(obj, list): + listitems = iter(obj) + elif isinstance(obj, dict): + dictitems = obj.iteritems() + return __newobj__, (cls, args), state, listitems, dictitems + + _copy_dispatch = d = {} *************** *** 176,185 **** except AttributeError: try: ! reductor = x.__reduce__ except AttributeError: ! raise error, \ ! "un-deep-copyable object of type %s" % type(x) else: ! y = _reconstruct(x, reductor(), 1, memo) else: y = copier(memo) --- 219,230 ---- except AttributeError: try: ! reductor = x.__class__.__reduce__ ! if reductor == object.__reduce__: ! reductor = _better_reduce except AttributeError: ! raise Error("un(shallow)copyable object of type %s" % ! type(x)) else: ! y = _reconstruct(x, reductor(x), 1, memo) else: y = copier(memo) *************** *** 332,336 **** y.__setstate__(state) else: ! y.__dict__.update(state) return y --- 377,389 ---- y.__setstate__(state) else: ! if isinstance(state, tuple) and len(state) == 2: ! state, slotstate = state ! else: ! slotstate = None ! if state is not None: ! y.__dict__.update(state) ! if slotstate is not None: ! for key, value in slotstate.iteritems(): ! setattr(y, key, value) return y From akuchling@users.sourceforge.net Thu Feb 6 19:55:37 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 06 Feb 2003 11:55:37 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts findlinksto.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv17760 Modified Files: findlinksto.py Log Message: Use new name for GetoptError, and pass it two arguments Use re module instead of regex Index: findlinksto.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/findlinksto.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** findlinksto.py 17 Jan 2001 08:48:39 -0000 1.8 --- findlinksto.py 6 Feb 2003 19:55:35 -0000 1.9 *************** *** 7,11 **** import os import sys ! import regex import getopt --- 7,11 ---- import os import sys ! import re import getopt *************** *** 14,19 **** opts, args = getopt.getopt(sys.argv[1:], '') if len(args) < 2: ! raise getopt.error, 'not enough arguments' ! except getopt.error, msg: sys.stdout = sys.stderr print msg --- 14,19 ---- opts, args = getopt.getopt(sys.argv[1:], '') if len(args) < 2: ! raise getopt.GetoptError('not enough arguments', None) ! except getopt.GetoptError, msg: sys.stdout = sys.stderr print msg *************** *** 21,25 **** sys.exit(2) pat, dirs = args[0], args[1:] ! prog = regex.compile(pat) for dirname in dirs: os.path.walk(dirname, visit, prog) --- 21,25 ---- sys.exit(2) pat, dirs = args[0], args[1:] ! prog = re.compile(pat) for dirname in dirs: os.path.walk(dirname, visit, prog) *************** *** 35,39 **** try: linkto = os.readlink(name) ! if prog.search(linkto) >= 0: print name, '->', linkto except os.error: --- 35,39 ---- try: linkto = os.readlink(name) ! if prog.search(linkto) is not None: print name, '->', linkto except os.error: From tim_one@users.sourceforge.net Thu Feb 6 20:29:24 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 12:29:24 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv3118 Modified Files: pep-0307.txt Log Message: Quick checkin to make sure I still have the mechanics straight in this directory. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** pep-0307.txt 4 Feb 2003 19:28:16 -0000 1.11 --- pep-0307.txt 6 Feb 2003 20:29:21 -0000 1.12 *************** *** 37,43 **** Pickling new-style objects causes serious pickle bloat. For ! example, the binary pickle for a classic object with one instance ! variable takes up 33 bytes; a new-style object with one instance ! variable takes up 86 bytes. This was measured as follows: class C(object): # Omit "(object)" for classic class --- 37,41 ---- Pickling new-style objects causes serious pickle bloat. For ! example, class C(object): # Omit "(object)" for classic class *************** *** 46,49 **** --- 44,50 ---- x.foo = 42 print len(pickle.dumps(x, 1)) + + The binary pickle for the classic object consumed 33 bytes, and for + the new-style object 86 bytes. The reasons for the bloat are complex, but are mostly caused by From tim_one@users.sourceforge.net Thu Feb 6 20:35:03 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 12:35:03 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv6890 Modified Files: pep-0307.txt Log Message: Minor edits to the "Protocol versions" section. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** pep-0307.txt 6 Feb 2003 20:29:21 -0000 1.12 --- pep-0307.txt 6 Feb 2003 20:35:00 -0000 1.13 *************** *** 60,86 **** Protocol versions ! Previously, pickling (but not unpickling) has distinguished ! between text mode and binary mode. By design, text mode is a ! subset of binary mode, and unpicklers don't need to know in advance whether an incoming pickle uses text mode or binary mode. The virtual machine used for unpickling is the same regardless of ! the mode; certain opcode simply aren't used in text mode. ! Retroactively, text mode is called protocol 0, and binary mode is ! called protocol 1. The new protocol is called protocol 2. In the tradition of pickling protocols, protocol 2 is a superset of protocol 1. But just so that future pickling protocols aren't required to be supersets of the oldest protocols, a new opcode is inserted at the start of a protocol 2 pickle indicating that it is ! using protocol 2. Several functions, methods and constructors used for pickling used to take a positional argument named 'bin' which was a flag, defaulting to 0, indicating binary mode. This argument is renamed ! to 'proto' and now gives the protocol number, defaulting to 0. It so happens that passing 2 for the 'bin' argument in previous Python versions had the same effect as passing 1. Nevertheless, a ! special case is added here: passing a negative number selects the highest protocol version supported by a particular implementation. This works in previous Python versions, too. --- 60,89 ---- Protocol versions ! Previously, pickling (but not unpickling) distinguished between ! text mode and binary mode. By design, binary mode is a ! superset of text mode, and unpicklers don't need to know in advance whether an incoming pickle uses text mode or binary mode. The virtual machine used for unpickling is the same regardless of ! the mode; certain opcodes simply aren't used in text mode. ! Retroactively, text mode is now called protocol 0, and binary mode ! protocol 1. The new protocol is called protocol 2. In the tradition of pickling protocols, protocol 2 is a superset of protocol 1. But just so that future pickling protocols aren't required to be supersets of the oldest protocols, a new opcode is inserted at the start of a protocol 2 pickle indicating that it is ! using protocol 2. To date, each release of Python has been able to ! read pickles written by all previous releases. Of course pickles ! written under protocol N can't be read by versions of Python ! earlier than the one that introduced protocol N. Several functions, methods and constructors used for pickling used to take a positional argument named 'bin' which was a flag, defaulting to 0, indicating binary mode. This argument is renamed ! to 'proto' and now gives the protocol number, still defaulting to 0. It so happens that passing 2 for the 'bin' argument in previous Python versions had the same effect as passing 1. Nevertheless, a ! special case is added here: passing a negative number selects the highest protocol version supported by a particular implementation. This works in previous Python versions, too. From tim_one@users.sourceforge.net Thu Feb 6 20:38:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 12:38:34 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv8818 Modified Files: pep-0307.txt Log Message: Intro: make explicit that the new protocol is to be introduced with 2.3. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** pep-0307.txt 6 Feb 2003 20:35:00 -0000 1.13 --- pep-0307.txt 6 Feb 2003 20:38:30 -0000 1.14 *************** *** 15,20 **** Pickling new-style objects in Python 2.2 is done somewhat clumsily and causes pickle size to bloat compared to classic class ! instances. This PEP documents a new pickle protocol that takes ! care of this and many other pickle issues. There are two sides to specifying a new pickle protocol: the byte --- 15,20 ---- Pickling new-style objects in Python 2.2 is done somewhat clumsily and causes pickle size to bloat compared to classic class ! instances. This PEP documents a new pickle protocol in Python 2.3 ! that takes care of this and many other pickle issues. There are two sides to specifying a new pickle protocol: the byte From neal@metaslash.com Thu Feb 6 21:21:13 2003 From: neal@metaslash.com (Neal Norwitz) Date: Thu, 06 Feb 2003 16:21:13 -0500 Subject: [Python-checkins] python/dist/src/Python ceval.c,2.347,2.348 compile.c,2.272,2.273 sysmodule.c,2.112,2.113 In-Reply-To: References: Message-ID: <20030206212113.GD23059@epoch.metaslash.com> > + #ifdef CALL_PROFILE > + #define PCALL_NUM 11 > + #define PCALL_POP 10 > + PyObject * > + PyEval_GetCallStats(PyObject *self) > + { > + return Py_BuildValue("iiiiiiiiii", > + pcall[0], pcall[1], pcall[2], pcall[3], > + pcall[4], pcall[5], pcall[6], pcall[7], > + pcall[8], pcall[9]); > + } Shouldn't there be another i and pcall[10]? sysmodule also documented 11 calls. Neal From gvanrossum@users.sourceforge.net Thu Feb 6 21:25:17 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 13:25:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv1908/test Modified Files: test_copy.py Log Message: Fix a bug in the way __getnewargs__ was handled. Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_copy.py 6 Feb 2003 19:53:22 -0000 1.3 --- test_copy.py 6 Feb 2003 21:25:12 -0000 1.4 *************** *** 455,458 **** --- 455,476 ---- self.assert_(x.foo is not y.foo) + def test_copy_tuple_subclass(self): + class C(tuple): + pass + x = C([1, 2, 3]) + self.assertEqual(tuple(x), (1, 2, 3)) + y = copy.copy(x) + self.assertEqual(tuple(y), (1, 2, 3)) + + def test_deepcopy_tuple_subclass(self): + class C(tuple): + pass + x = C([[1, 2], 3]) + self.assertEqual(tuple(x), ([1, 2], 3)) + y = copy.deepcopy(x) + self.assertEqual(tuple(y), ([1, 2], 3)) + self.assert_(x is not y) + self.assert_(x[0] is not y[0]) + def test_main(): suite = unittest.TestSuite() From gvanrossum@users.sourceforge.net Thu Feb 6 21:25:44 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 13:25:44 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv1908 Modified Files: copy.py Log Message: Fix a bug in the way __getnewargs__ was handled. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** copy.py 6 Feb 2003 19:53:22 -0000 1.32 --- copy.py 6 Feb 2003 21:25:08 -0000 1.33 *************** *** 129,133 **** elif isinstance(obj, dict): dictitems = obj.iteritems() ! return __newobj__, (cls, args), state, listitems, dictitems --- 129,133 ---- elif isinstance(obj, dict): dictitems = obj.iteritems() ! return __newobj__, (cls,) + args, state, listitems, dictitems From fdrake@users.sourceforge.net Thu Feb 6 22:11:04 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Thu, 06 Feb 2003 14:11:04 -0800 Subject: [Python-checkins] python/nondist/peps pep-0042.txt,1.68,1.69 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv29446 Modified Files: pep-0042.txt Log Message: Fix typo. Index: pep-0042.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0042.txt,v retrieving revision 1.68 retrieving revision 1.69 diff -C2 -d -r1.68 -r1.69 *** pep-0042.txt 6 Feb 2003 17:57:14 -0000 1.68 --- pep-0042.txt 6 Feb 2003 22:11:01 -0000 1.69 *************** *** 171,175 **** - urlparse should be updated to comply with RFC 2396, which ! defines optional parameters for each segment of the page. http://www.python.org/sf/210834 --- 171,175 ---- - urlparse should be updated to comply with RFC 2396, which ! defines optional parameters for each segment of the path. http://www.python.org/sf/210834 From jackjansen@users.sourceforge.net Thu Feb 6 22:32:41 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 06 Feb 2003 14:32:41 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE MacPrefs.py,1.5,1.6 ProfileBrowser.py,1.4,1.5 PyBrowser.py,1.21,1.22 PyConsole.py,1.14,1.15 PyDocSearch.py,1.10,1.11 PyEdit.py,1.34,1.35 PythonIDEMain.py,1.26,1.27 Wapplication.py,1.20,1.21 Wquicktime.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv8695 Modified Files: MacPrefs.py ProfileBrowser.py PyBrowser.py PyConsole.py PyDocSearch.py PyEdit.py PythonIDEMain.py Wapplication.py Wquicktime.py Log Message: Got rid of macfs and FSSpecs in general (pathnames or FSRefs are now used everywhere). Index: MacPrefs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/MacPrefs.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** MacPrefs.py 13 Dec 2002 23:32:51 -0000 1.5 --- MacPrefs.py 6 Feb 2003 22:32:35 -0000 1.6 *************** *** 1,7 **** - import macfs import marshal import types ! ! from MACFS import kOnSystemDisk class PrefObject: --- 1,6 ---- import marshal import types ! from Carbon import Folder ! from Carbon import Folders class PrefObject: *************** *** 72,77 **** marshal.dump(prefdict, open(self.__path, 'wb')) try: ! fss = macfs.FSSpec(macfs.FSRef(self.__path)) ! fss.SetCreatorType(self.__creator, 'pref') except: pass --- 71,75 ---- marshal.dump(prefdict, open(self.__path, 'wb')) try: ! MacOS.SetCreatorAndType(self.__path, self.__creator, 'pref') except: pass *************** *** 99,105 **** return _prefscache[prefname] # Find the preferences folder and our prefs file, create if needed. ! vrefnum, dirid = macfs.FindFolder(kOnSystemDisk, 'pref', 0) ! prefsfolder_fss = macfs.FSSpec((vrefnum, dirid, '')) ! prefsfolder = macfs.FSRef(prefsfolder_fss).as_fsspec().as_pathname() path = os.path.join(prefsfolder, prefname) head, tail = os.path.split(path) --- 97,102 ---- return _prefscache[prefname] # Find the preferences folder and our prefs file, create if needed. ! fsr = Folder.FSFindFolder(Folders.kOnSystemDisk, 'pref', 1) ! prefsfolder = fsr.as_pathname() path = os.path.join(prefsfolder, prefname) head, tail = os.path.split(path) Index: ProfileBrowser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/ProfileBrowser.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ProfileBrowser.py 26 Jan 2003 22:15:48 -0000 1.4 --- ProfileBrowser.py 6 Feb 2003 22:32:35 -0000 1.5 *************** *** 84,88 **** browser = ProfileBrowser(stats) else: - import macfs filename = EasyDialogs.AskFileForOpen(message='Profiler data') if not filename: sys.exit(0) --- 84,87 ---- Index: PyBrowser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyBrowser.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** PyBrowser.py 13 Dec 2002 15:14:22 -0000 1.21 --- PyBrowser.py 6 Feb 2003 22:32:35 -0000 1.22 *************** *** 323,329 **** return elif os.path.exists(value) and os.path.isfile(value): ! import macfs ! fss = macfs.FSSpec(value) ! if fss.GetCreatorType()[1] == 'TEXT': W.getapplication().openscript(value) --- 323,327 ---- return elif os.path.exists(value) and os.path.isfile(value): ! if MacOS.GetCreatorAndType(value)[1] in ('TEXT', '\0\0\0\0'): W.getapplication().openscript(value) Index: PyConsole.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyConsole.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** PyConsole.py 26 Jan 2003 22:15:48 -0000 1.14 --- PyConsole.py 6 Feb 2003 22:32:35 -0000 1.15 *************** *** 86,90 **** def domenu_save_as(self, *args): - import macfs filename = EasyDialogs.AskFileForSave(message='Save console text as:', savedFileName='console.txt') --- 86,89 ---- *************** *** 94,98 **** f.write(self.get()) f.close() ! fss.SetCreatorType(W._signature, 'TEXT') def write(self, text): --- 93,97 ---- f.write(self.get()) f.close() ! MacOS.SetCreatorAndType(filename, W._signature, 'TEXT') def write(self, text): *************** *** 243,247 **** def domenu_save_as(self, *args): title = self._parentwindow.gettitle() - import macfs filename = EasyDialogs.AskFileForSave(message='Save %s text as:' % title, savedFileName=title + '.txt') --- 242,245 ---- *************** *** 251,255 **** f.write(self.get()) f.close() ! fss.SetCreatorType(W._signature, 'TEXT') def domenu_cut(self, *args): --- 249,253 ---- f.write(self.get()) f.close() ! MacOS.SetCreatorAndType(filename, W._signature, 'TEXT') def domenu_cut(self, *args): Index: PyDocSearch.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyDocSearch.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** PyDocSearch.py 26 Jan 2003 22:15:48 -0000 1.10 --- PyDocSearch.py 6 Feb 2003 22:32:35 -0000 1.11 *************** *** 1,5 **** import re import W - import macfs import os import MacPrefs --- 1,4 ---- Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** PyEdit.py 26 Jan 2003 22:15:48 -0000 1.34 --- PyEdit.py 6 Feb 2003 22:32:35 -0000 1.35 *************** *** 5,10 **** from Wkeys import * - import macfs - import MACFS import MacOS import EasyDialogs --- 5,8 ---- *************** *** 13,16 **** --- 11,15 ---- from Carbon import Evt from Carbon import Qd + from Carbon import File import os import imp *************** *** 20,23 **** --- 19,24 ---- import re + smAllScripts = -3 + if hasattr(Win, "FrontNonFloatingWindow"): MyFrontWindow = Win.FrontNonFloatingWindow *************** *** 62,67 **** text = f.read() f.close() ! fss = macfs.FSSpec(path) ! self._creator, filetype = fss.GetCreatorType() else: raise IOError, "file '%s' does not exist" % path --- 63,67 ---- text = f.read() f.close() ! self._creator, filetype = MacOS.GetCreatorAndType(path) else: raise IOError, "file '%s' does not exist" % path *************** *** 135,139 **** resref = Res.FSpOpenResFile(self.path, 3) except Res.Error: ! Res.FSpCreateResFile(self.path, self._creator, 'TEXT', MACFS.smAllScripts) resref = Res.FSpOpenResFile(self.path, 3) try: --- 135,139 ---- resref = Res.FSpOpenResFile(self.path, 3) except Res.Error: ! Res.FSpCreateResFile(self.path, self._creator, 'TEXT', smAllScripts) resref = Res.FSpOpenResFile(self.path, 3) try: *************** *** 390,395 **** fp.write(data) fp.close() ! fss = macfs.FSSpec(self.path) ! fss.SetCreatorType(self._creator, 'TEXT') self.getsettings() self.writewindowsettings() --- 390,394 ---- fp.write(data) fp.close() ! MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT') self.getsettings() self.writewindowsettings() *************** *** 420,425 **** if hasattr(app, 'makescriptsmenu'): app = W.getapplication() ! fss, fss_changed = app.scriptsfolder.Resolve() ! path = fss.as_pathname() if path == self.path[:len(path)]: W.getapplication().makescriptsmenu() --- 419,424 ---- if hasattr(app, 'makescriptsmenu'): app = W.getapplication() ! fsr, changed = app.scriptsfolder.FSResolveAlias(None) ! path = fsr.as_pathname() if path == self.path[:len(path)]: W.getapplication().makescriptsmenu() *************** *** 547,558 **** file_path = self.path if not os.path.exists(interp_path): ! # This "can happen" if we are running IDE under MacPython. Try ! # the standard location. ! interp_path = "/Library/Frameworks/Python.framework/Versions/2.3/bin/python" ! try: ! fsr = macfs.FSRef(interp_path) ! except macfs.Error: ! raise W.AlertError, "Can't find command-line Python" ! file_path = macfs.FSRef(macfs.FSSpec(self.path)).as_pathname() cmd = '"%s" "%s" ; exit' % (interp_path, file_path) t = Terminal.Terminal() --- 546,551 ---- file_path = self.path if not os.path.exists(interp_path): ! # This "can happen" if we are running IDE under MacPython-OS9. ! raise W.AlertError, "Can't find command-line Python" cmd = '"%s" "%s" ; exit' % (interp_path, file_path) t = Terminal.Terminal() *************** *** 1369,1374 **** def resolvealiases(path): try: ! return macfs.ResolveAliasFile(path)[0].as_pathname() ! except (macfs.error, ValueError), (error, str): if error <> -120: raise --- 1362,1369 ---- def resolvealiases(path): try: ! fsr, d1, d2 = File.FSResolveAliasFile(path, 1) ! path = fsr.as_pathname() ! return path ! except (File.Error, ValueError), (error, str): if error <> -120: raise Index: PythonIDEMain.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PythonIDEMain.py,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** PythonIDEMain.py 5 Feb 2003 15:41:09 -0000 1.26 --- PythonIDEMain.py 6 Feb 2003 22:32:35 -0000 1.27 *************** *** 8,14 **** import os import sys - import macfs import MacOS import EasyDialogs if MacOS.runtimemodel == 'macho': --- 8,15 ---- import os import sys import MacOS import EasyDialogs + from Carbon import File + from Carbon import Files if MacOS.runtimemodel == 'macho': *************** *** 24,27 **** --- 25,32 ---- return not not value + def getmodtime(file): + file = File.FSRef(file) + catinfo, d1, d2, d3 = file.FSGetCatalogInfo(Files.kFSCatInfoContentMod) + return catinfo.contentModDate class PythonIDE(Wapplication.Application): *************** *** 126,133 **** prefs = self.getprefs() try: ! fss, fss_changed = macfs.RawAlias(prefs.scriptsfolder).Resolve() ! self.scriptsfolder = fss.NewAlias() except: ! path = os.path.join(os.getcwd(), ":Mac:IDE scripts") if not os.path.exists(path): path = os.path.join(os.getcwd(), "Scripts") --- 131,138 ---- prefs = self.getprefs() try: ! fsr, d = File.Alias(rawdata=prefs.scriptsfolder).FSResolveAlias(None) ! self.scriptsfolder = fsr.FSNewAliasMinimal() except: ! path = os.path.join(os.getcwd(), "Mac", "IDE scripts") if not os.path.exists(path): path = os.path.join(os.getcwd(), "Scripts") *************** *** 136,144 **** f = open(os.path.join(path, "Place your scripts here"+ELIPSES), "w") f.close() ! fss = macfs.FSSpec(path) ! self.scriptsfolder = fss.NewAlias() ! self.scriptsfoldermodtime = fss.GetDates()[1] else: ! self.scriptsfoldermodtime = fss.GetDates()[1] prefs.scriptsfolder = self.scriptsfolder.data self._scripts = {} --- 141,149 ---- f = open(os.path.join(path, "Place your scripts here"+ELIPSES), "w") f.close() ! fsr = File.FSRef(path) ! self.scriptsfolder = fsr.FSNewAliasMinimal() ! self.scriptsfoldermodtime = getmodtime(fsr) else: ! self.scriptsfoldermodtime = getmodtime(fsr) prefs.scriptsfolder = self.scriptsfolder.data self._scripts = {} *************** *** 154,160 **** def suspendresume(self, onoff): if onoff: ! fss, fss_changed = self.scriptsfolder.Resolve() ! modtime = fss.GetDates()[1] ! if self.scriptsfoldermodtime <> modtime or fss_changed: self.scriptsfoldermodtime = modtime W.SetCursor('watch') --- 159,165 ---- def suspendresume(self, onoff): if onoff: ! fsr, changed = self.scriptsfolder.FSResolveAlias(None) ! modtime = getmodtime(fsr) ! if self.scriptsfoldermodtime <> modtime or changed: self.scriptsfoldermodtime = modtime W.SetCursor('watch') *************** *** 172,181 **** docs = [docs] for doc in docs: ! fss, a = doc.Resolve() ! path = fss.as_pathname() self.opendoc(path) def opendoc(self, path): ! fcreator, ftype = macfs.FSSpec(path).GetCreatorType() if ftype == 'TEXT': self.openscript(path) --- 177,186 ---- docs = [docs] for doc in docs: ! fsr, a = doc.FSResolveAlias(None) ! path = fsr.as_pathname() self.opendoc(path) def opendoc(self, path): ! fcreator, ftype = MacOS.GetCreatorAndType(path) if ftype == 'TEXT': self.openscript(path) *************** *** 192,200 **** def do_setscriptsfolder(self, *args): ! fss = EasyDialogs.AskFolder(message="Select Scripts Folder", ! wanted=macfs.FSSpec) ! if fss: prefs = self.getprefs() ! alis = fss.NewAlias() prefs.scriptsfolder = alis.data self.scriptsfolder = alis --- 197,205 ---- def do_setscriptsfolder(self, *args): ! fsr = EasyDialogs.AskFolder(message="Select Scripts Folder", ! wanted=File.FSRef) ! if fsr: prefs = self.getprefs() ! alis = fsr.FSNewAliasMinimal() prefs.scriptsfolder = alis.data self.scriptsfolder = alis *************** *** 247,252 **** #FrameWork.MenuItem(self.scriptsmenu, "New script", None, self.domenu_new) #self.scriptsmenu.addseparator() ! fss, fss_changed = self.scriptsfolder.Resolve() ! self.scriptswalk(fss.as_pathname(), self.scriptsmenu) def makeopenwindowsmenu(self): --- 252,257 ---- #FrameWork.MenuItem(self.scriptsmenu, "New script", None, self.domenu_new) #self.scriptsmenu.addseparator() ! fsr, d1 = self.scriptsfolder.FSResolveAlias(None) ! self.scriptswalk(fsr.as_pathname(), self.scriptsmenu) def makeopenwindowsmenu(self): Index: Wapplication.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wapplication.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** Wapplication.py 9 Jan 2003 23:20:31 -0000 1.20 --- Wapplication.py 6 Feb 2003 22:32:35 -0000 1.21 *************** *** 9,12 **** --- 9,13 ---- from Carbon import Menu; MenuToolbox = Menu; del Menu import macresource + from Carbon import File if hasattr(Win, "FrontNonFloatingWindow"): *************** *** 274,278 **** return done[top] = 1 ! import os, macfs, string try: names = os.listdir(top) --- 275,279 ---- return done[top] = 1 ! import os, string try: names = os.listdir(top) *************** *** 286,294 **** continue try: ! fss, isdir, isalias = macfs.ResolveAliasFile(name) except: # maybe a broken alias continue ! path = fss.as_pathname() if done.has_key(path): continue --- 287,295 ---- continue try: ! fsr, isdir, isalias = File.FSResolveAliasFile(name, 1) except: # maybe a broken alias continue ! path = fsr.as_pathname() if done.has_key(path): continue *************** *** 302,306 **** self.scriptswalk(path, submenu, done) else: ! creator, type = fss.GetCreatorType() if type == 'TEXT': if name[-3:] == '.py': --- 303,307 ---- self.scriptswalk(path, submenu, done) else: ! creator, type = MacOS.GetCreatorAndType(path) if type == 'TEXT': if name[-3:] == '.py': Index: Wquicktime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wquicktime.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Wquicktime.py 25 Aug 2001 12:14:38 -0000 1.4 --- Wquicktime.py 6 Feb 2003 22:32:35 -0000 1.5 *************** *** 4,8 **** from Carbon import Qt, QuickTime import W ! import macfs from Carbon import Evt, Events --- 4,8 ---- from Carbon import Qt, QuickTime import W ! from Carbon import File from Carbon import Evt, Events *************** *** 34,45 **** #self.GetWindow().InvalWindowRect(self.movie.GetMovieBox()) Qd.PaintRect(self.movie.GetMovieBox()) ! if type(path_or_fss) == type(''): ! path = path_or_fss ! fss = macfs.FSSpec(path) ! else: ! path = path_or_fss.as_pathname() ! fss = path_or_fss self.movietitle = os.path.basename(path) ! movieResRef = Qt.OpenMovieFile(fss, 1) self.movie, dummy, dummy = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) self.moviebox = self.movie.GetMovieBox() --- 34,40 ---- #self.GetWindow().InvalWindowRect(self.movie.GetMovieBox()) Qd.PaintRect(self.movie.GetMovieBox()) ! path = File.pathname(path) self.movietitle = os.path.basename(path) ! movieResRef = Qt.OpenMovieFile(path_or_fss, 1) self.movie, dummy, dummy = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) self.moviebox = self.movie.GetMovieBox() From jackjansen@users.sourceforge.net Thu Feb 6 22:57:47 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 06 Feb 2003 14:57:47 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts mkestrres.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv21528 Modified Files: mkestrres.py Log Message: Got rid of FSSpecs. Index: mkestrres.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/mkestrres.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** mkestrres.py 22 Apr 2002 11:44:26 -0000 1.9 --- mkestrres.py 6 Feb 2003 22:57:44 -0000 1.10 *************** *** 2,6 **** import re - import macfs import string from Carbon import Res --- 2,5 ---- *************** *** 106,150 **** def main(): dict = {} ! fss, ok = macfs.PromptGetFile("Where is GUSI sys/errno.h?") ! if not ok: return ! fp = open(fss.as_pathname()) ! parse_errno_h(fp, dict) ! fp.close() ! fss, ok = macfs.PromptGetFile("Select cerrno (MSL) or cancel") ! if not ok: return ! fp = open(fss.as_pathname()) ! parse_errno_h(fp, dict) ! fp.close() ! fss, ok = macfs.PromptGetFile("Where is MacErrors.h?") ! if not ok: return ! fp = open(fss.as_pathname()) ! parse_errors_h(fp, dict) ! fp.close() ! fss, ok = macfs.PromptGetFile("Where is mkestrres-MacErrors.h?") ! if not ok: return ! fp = open(fss.as_pathname()) ! parse_errors_h(fp, dict) ! fp.close() if not dict: return ! fss, ok = macfs.StandardPutFile("Resource output file?", "errors.rsrc") ! if ok: writeestr(fss, dict) ! fss, ok = macfs.StandardPutFile("Python output file?", "macerrors.py") ! if ok: ! fp = open(fss.as_pathname(), "w") writepython(fp, dict) fp.close() fss.SetCreatorType('Pyth', 'TEXT') ! fss, ok = macfs.StandardPutFile("Text output file?", "errors.txt") ! if ok: ! fp = open(fss.as_pathname(), "w") k = dict.keys() --- 105,149 ---- def main(): dict = {} ! pathname = EasyDialogs.AskFileForOpen(message="Where is GUSI sys/errno.h?") ! if pathname: ! fp = open(pathname) ! parse_errno_h(fp, dict) ! fp.close() ! pathname = EasyDialogs.AskFileForOpen(message="Select cerrno (MSL) or cancel") ! if pathname: ! fp = open(pathname) ! parse_errno_h(fp, dict) ! fp.close() ! pathname = EasyDialogs.AskFileForOpen(message="Where is MacErrors.h?") ! if pathname: ! fp = open(pathname) ! parse_errors_h(fp, dict) ! fp.close() ! pathname = EasyDialogs.AskFileForOpen(message="Where is mkestrres-MacErrors.h?") ! if pathname: ! fp = open(pathname) ! parse_errors_h(fp, dict) ! fp.close() if not dict: return ! pathname = EasyDialogs.AskFileForSave(message="Resource output file?", savedFileName="errors.rsrc") ! if pathname: writeestr(fss, dict) ! pathname = EasyDialogs.AskFileForSave(message="Python output file?", savedFileName="macerrors.py") ! if pathname: ! fp = open(pathname, "w") writepython(fp, dict) fp.close() fss.SetCreatorType('Pyth', 'TEXT') ! pathname = EasyDialogs.AskFileForSave(message="Text output file?", savedFileName="errors.txt") ! if pathname: ! fp = open(pathname, "w") k = dict.keys() From gvanrossum@users.sourceforge.net Thu Feb 6 22:57:02 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 06 Feb 2003 14:57:02 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.33,1.34 copy_reg.py,1.16,1.17 pickle.py,1.147,1.148 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv20624 Modified Files: copy.py copy_reg.py pickle.py Log Message: Move _better_reduce from copy.py to copy_reg.py, and also use it in pickle.py, where it makes save_newobj() unnecessary. Tests pass. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** copy.py 6 Feb 2003 21:25:08 -0000 1.33 --- copy.py 6 Feb 2003 22:57:00 -0000 1.34 *************** *** 52,56 **** import types ! from pickle import _slotnames class Error(Exception): --- 52,56 ---- import types ! from copy_reg import _better_reduce class Error(Exception): *************** *** 90,133 **** y = copierfunction(x) return y - - def __newobj__(cls, *args): - return cls.__new__(cls, *args) - - def _better_reduce(obj): - cls = obj.__class__ - getnewargs = getattr(obj, "__getnewargs__", None) - if getnewargs: - args = getnewargs() - else: - args = () - getstate = getattr(obj, "__getstate__", None) - if getstate: - try: - state = getstate() - except TypeError, err: - # XXX Catch generic exception caused by __slots__ - if str(err) != ("a class that defines __slots__ " - "without defining __getstate__ " - "cannot be pickled"): - raise # Not that specific exception - getstate = None - if not getstate: - state = getattr(obj, "__dict__", None) - names = _slotnames(cls) - if names: - slots = {} - nil = [] - for name in names: - value = getattr(obj, name, nil) - if value is not nil: - slots[name] = value - if slots: - state = (state, slots) - listitems = dictitems = None - if isinstance(obj, list): - listitems = iter(obj) - elif isinstance(obj, dict): - dictitems = obj.iteritems() - return __newobj__, (cls,) + args, state, listitems, dictitems --- 90,93 ---- Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** copy_reg.py 4 Feb 2003 05:06:17 -0000 1.16 --- copy_reg.py 6 Feb 2003 22:57:00 -0000 1.17 *************** *** 70,73 **** --- 70,151 ---- return _reconstructor, args + # A better version of _reduce, used by copy and pickle protocol 2 + + def __newobj__(cls, *args): + return cls.__new__(cls, *args) + + def _better_reduce(obj): + cls = obj.__class__ + getnewargs = getattr(obj, "__getnewargs__", None) + if getnewargs: + args = getnewargs() + else: + args = () + getstate = getattr(obj, "__getstate__", None) + if getstate: + try: + state = getstate() + except TypeError, err: + # XXX Catch generic exception caused by __slots__ + if str(err) != ("a class that defines __slots__ " + "without defining __getstate__ " + "cannot be pickled"): + raise # Not that specific exception + getstate = None + if not getstate: + state = getattr(obj, "__dict__", None) + names = _slotnames(cls) + if names: + slots = {} + nil = [] + for name in names: + value = getattr(obj, name, nil) + if value is not nil: + slots[name] = value + if slots: + state = (state, slots) + listitems = dictitems = None + if isinstance(obj, list): + listitems = iter(obj) + elif isinstance(obj, dict): + dictitems = obj.iteritems() + return __newobj__, (cls,) + args, state, listitems, dictitems + + def _slotnames(cls): + """Return a list of slot names for a given class. + + This needs to find slots defined by the class and its bases, so we + can't simply return the __slots__ attribute. We must walk down + the Method Resolution Order and concatenate the __slots__ of each + class found there. (This assumes classes don't modify their + __slots__ attribute to misrepresent their slots after the class is + defined.) + """ + + # Get the value from a cache in the class if possible + names = cls.__dict__.get("__slotnames__") + if names is not None: + return names + + # Not cached -- calculate the value + names = [] + if not hasattr(cls, "__slots__"): + # This class has no slots + pass + else: + # Slots found -- gather slot names from all base classes + for c in cls.__mro__: + if "__slots__" in c.__dict__: + names += [name for name in c.__dict__["__slots__"] + if name not in ("__dict__", "__weakref__")] + + # Cache the outcome in the class if at all possible + try: + cls.__slotnames__ = names + except: + pass # But don't die if we can't + + return names + # A registry of extension codes. This is an ad-hoc compression # mechanism. Whenever a global reference to , is about Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.147 retrieving revision 1.148 diff -C2 -d -r1.147 -r1.148 *** pickle.py 6 Feb 2003 19:30:38 -0000 1.147 --- pickle.py 6 Feb 2003 22:57:00 -0000 1.148 *************** *** 28,32 **** from types import * ! from copy_reg import dispatch_table, _reconstructor from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal --- 28,32 ---- from types import * ! from copy_reg import dispatch_table, _reconstructor, _better_reduce from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal *************** *** 311,318 **** # Protocol 2 can do better than the default __reduce__ if reduce is object.__reduce__: ! reduce = None ! if not reduce: ! self.save_newobj(obj) ! return if not reduce: raise PicklingError("Can't pickle %r object: %r" % --- 311,315 ---- # Protocol 2 can do better than the default __reduce__ if reduce is object.__reduce__: ! reduce = _better_reduce if not reduce: raise PicklingError("Can't pickle %r object: %r" % *************** *** 434,517 **** write(BUILD) - def save_newobj(self, obj): - # Save a new-style class instance, using protocol 2. - assert self.proto >= 2 # This only works for protocol 2 - t = type(obj) - getnewargs = getattr(obj, "__getnewargs__", None) - if getnewargs: - args = getnewargs() # This better not reference obj - else: - args = () - - save = self.save - write = self.write - - self.save(t) - save(args) - write(NEWOBJ) - self.memoize(obj) - - if isinstance(obj, list): - self._batch_appends(iter(obj)) - elif isinstance(obj, dict): - self._batch_setitems(obj.iteritems()) - - getstate = getattr(obj, "__getstate__", None) - - if getstate: - # A class may define both __getstate__ and __getnewargs__. - # If they are the same function, we ignore __getstate__. - # This is for the benefit of protocols 0 and 1, which don't - # use __getnewargs__. Note that the only way to make them - # the same function is something like this: - # - # class C(object): - # def __getstate__(self): - # return ... - # __getnewargs__ = __getstate__ - # - # No tricks are needed to ignore __setstate__; it simply - # won't be called when we don't generate BUILD. - # Also note that when __getnewargs__ and __getstate__ are - # the same function, we don't do the default thing of - # looking for __dict__ and slots either -- it is assumed - # that __getnewargs__ returns all the state there is - # (which should be a safe assumption since __getstate__ - # returns the *same* state). - if getstate == getnewargs: - return - - try: - state = getstate() - except TypeError, err: - # XXX Catch generic exception caused by __slots__ - if str(err) != ("a class that defines __slots__ " - "without defining __getstate__ " - "cannot be pickled"): - raise # Not that specific exception - getstate = None - - if not getstate: - state = getattr(obj, "__dict__", None) - if not state: - state = None - # If there are slots, the state becomes a tuple of two - # items: the first item the regular __dict__ or None, and - # the second a dict mapping slot names to slot values - names = _slotnames(t) - if names: - slots = {} - nil = [] - for name in names: - value = getattr(obj, name, nil) - if value is not nil: - slots[name] = value - if slots: - state = (state, slots) - - if state is not None: - save(state) - write(BUILD) - # Methods below this point are dispatched through the dispatch table --- 431,434 ---- *************** *** 714,718 **** for i in r: try: ! tmp.append(items.next()) except StopIteration: items = None --- 631,636 ---- for i in r: try: ! x = items.next() ! tmp.append(x) except StopIteration: items = None *************** *** 865,904 **** # Pickling helpers - - def _slotnames(cls): - """Return a list of slot names for a given class. - - This needs to find slots defined by the class and its bases, so we - can't simply return the __slots__ attribute. We must walk down - the Method Resolution Order and concatenate the __slots__ of each - class found there. (This assumes classes don't modify their - __slots__ attribute to misrepresent their slots after the class is - defined.) - """ - - # Get the value from a cache in the class if possible - names = cls.__dict__.get("__slotnames__") - if names is not None: - return names - - # Not cached -- calculate the value - names = [] - if not hasattr(cls, "__slots__"): - # This class has no slots - pass - else: - # Slots found -- gather slot names from all base classes - for c in cls.__mro__: - if "__slots__" in c.__dict__: - names += [name for name in c.__dict__["__slots__"] - if name not in ("__dict__", "__weakref__")] - - # Cache the outcome in the class if at all possible - try: - cls.__slotnames__ = names - except: - pass # But don't die if we can't - - return names def _keep_alive(x, memo): --- 783,786 ---- From jackjansen@users.sourceforge.net Thu Feb 6 23:10:48 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 06 Feb 2003 15:10:48 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.644,1.645 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv28023 Modified Files: NEWS Log Message: Added a note about getting rid of macfs usage (MacPython). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.644 retrieving revision 1.645 diff -C2 -d -r1.644 -r1.645 *** NEWS 6 Feb 2003 16:16:50 -0000 1.644 --- NEWS 6 Feb 2003 23:10:45 -0000 1.645 *************** *** 272,275 **** --- 272,279 ---- - There are new dialogs EasyDialogs.AskFileForOpen, AskFileForSave and AskFolder. The old macfs.StandardGetFile and friends are deprecated. + + - Most of the standard library now uses pathnames or FSRefs in preference + of FSSpecs, and use the underlying Carbon.File and Carbon.Folder modules + in stead of macfs. macfs will probably be deprecated in the future. - Type Carbon.File.FSCatalogInfo and supporting methods have been implemented. From jackjansen@users.sourceforge.net Thu Feb 6 23:12:27 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 06 Feb 2003 15:12:27 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac Audio_mac.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv28870 Modified Files: Audio_mac.py Log Message: Got rid of macfs and FSSpecs. Index: Audio_mac.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/Audio_mac.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Audio_mac.py 30 Dec 2002 22:04:20 -0000 1.1 --- Audio_mac.py 6 Feb 2003 23:12:23 -0000 1.2 *************** *** 101,108 **** def test(): import aifc ! import macfs ! fss, ok = macfs.PromptGetFile("Select an AIFF soundfile", "AIFF") ! if not ok: return ! fn = fss.as_pathname() af = aifc.open(fn, 'r') print af.getparams() --- 101,107 ---- def test(): import aifc ! import EasyDialogs ! fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",)) ! if not fn: return af = aifc.open(fn, 'r') print af.getparams() From jackjansen@users.sourceforge.net Thu Feb 6 23:13:13 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 06 Feb 2003 15:13:13 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts fixfiletypes.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv29244 Modified Files: fixfiletypes.py Log Message: Got rid of macfs. Index: fixfiletypes.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/fixfiletypes.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** fixfiletypes.py 26 Jan 2003 21:40:00 -0000 1.7 --- fixfiletypes.py 6 Feb 2003 23:13:11 -0000 1.8 *************** *** 9,16 **** # import os - import macfs import EasyDialogs import sys import macostools list = [ --- 9,16 ---- # import os import EasyDialogs import sys import macostools + import MacOS list = [ *************** *** 31,39 **** for ext, cr, tp in list: if name[-len(ext):] == ext: ! fs = macfs.FSSpec(name) ! curcrtp = fs.GetCreatorType() if curcrtp <> (cr, tp): if change: ! fs.SetCreatorType(cr, tp) macostools.touched(fs) print 'Fixed ', name --- 31,38 ---- for ext, cr, tp in list: if name[-len(ext):] == ext: ! curcrtp = MacOS.GetCreatorAndType(name) if curcrtp <> (cr, tp): if change: ! MacOS.SetCreatorAndType(name, cr, tp) macostools.touched(fs) print 'Fixed ', name *************** *** 53,57 **** if __name__ == '__main__': ! run(1) --- 52,56 ---- if __name__ == '__main__': ! run(0) From nnorwitz@users.sourceforge.net Thu Feb 6 21:17:21 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 06 Feb 2003 13:17:21 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libfilecmp.tex,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv30719/Doc/lib Modified Files: libfilecmp.tex Log Message: Update doc to reflect code changes for obsoleting use_statcache parameter Index: libfilecmp.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libfilecmp.tex,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** libfilecmp.tex 5 Apr 2002 02:21:09 -0000 1.7 --- libfilecmp.tex 6 Feb 2003 21:17:17 -0000 1.8 *************** *** 17,30 **** Unless \var{shallow} is given and is false, files with identical ! \function{os.stat()} signatures are taken to be equal. If ! \var{use_statcache} is given and is true, ! \function{statcache.stat()} will be called rather then ! \function{os.stat()}; the default is to use \function{os.stat()}. Files that were compared using this function will not be compared again ! unless their \function{os.stat()} signature changes. Note that using ! \var{use_statcache} true will cause the cache invalidation mechanism to ! fail --- the stale stat value will be used from \refmodule{statcache}'s ! cache. Note that no external programs are called from this function, giving it --- 17,25 ---- Unless \var{shallow} is given and is false, files with identical ! \function{os.stat()} signatures are taken to be equal. ! \versionchanged[\var{use_statcache} is obsolete and ignored.]{2.3} Files that were compared using this function will not be compared again ! unless their \function{os.stat()} signature changes. Note that no external programs are called from this function, giving it From andrewmcnamara@users.sourceforge.net Fri Feb 7 01:27:23 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 17:27:23 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.16,1.17 csv.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv6805 Modified Files: _csv.c csv.py Log Message: Extensive re-write of C extension module - most of the code that was in csv.py has moved into the extension module. 16 tests now fail due to changed API and will need work. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** _csv.c 5 Feb 2003 10:30:06 -0000 1.16 --- _csv.c 7 Feb 2003 01:27:21 -0000 1.17 *************** *** 1,15 **** /* TODO: - + Add reader() and writer() functions which return CSV - reader/writer objects which implement the PEP interface: - - csvreader = csv.reader(file("blah.csv", "rb"), kwargs) - for row in csvreader: - process(row) - - csvwriter = csv.writer(file("some.csv", "wb"), kwargs) - for row in someiter: [...1621 lines suppressed...] if (v == NULL) return; ! res = PyModule_AddObject(module, style->name, v); if (res < 0) return; *************** *** 981,988 **** if (error_obj == NULL) return; ! ! PyDict_SetItemString(dict, "Error", error_obj); ! ! Py_XDECREF(rev); ! Py_XDECREF(error_obj); } --- 1201,1204 ---- if (error_obj == NULL) return; ! PyModule_AddObject(module, "Error", error_obj); } Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** csv.py 6 Feb 2003 04:49:29 -0000 1.23 --- csv.py 7 Feb 2003 01:27:21 -0000 1.24 *************** *** 1,5 **** ! import _csv ! from _csv import Error, __version__ ! from _csv import QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", --- 1,5 ---- ! from _csv import Error, __version__, writer, reader, register_dialect, \ ! unregister_dialect, get_dialect, list_dialects, \ ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", *************** *** 8,31 **** "unregister_dialect", "__version__" ] - _dialects = {} - - def register_dialect(name, dialect): - if not issubclass(dialect, Dialect): - raise TypeError, "dialect not a subclass of Dialect" - if dialect == Dialect: - raise ValueError, "Dialect is an abstract class" - d = dialect() - dialect._name = name - _dialects[name] = d - - def get_dialect(name): - return _dialects[name] - - def list_dialects(): - return _dialects.keys() - - def unregister_dialect(name): - del _dialects[name] - class Dialect: _name = "" --- 8,11 ---- *************** *** 75,156 **** delimiter = '\t' register_dialect("excel-tab", excel_tab) - - class _OCcsv: - def __init__(self, dialect, **options): - if isinstance(dialect, Dialect): - dialect_obj = dialect - else: - try: - dialect_obj = _dialects[dialect] - except KeyError: - raise Error('Unknown dialect') - parser_options = {} - for attr in dir(dialect_obj): - if attr.startswith('_'): - continue - parser_options[attr] = getattr(dialect_obj, attr) - parser_options.update(options) - self.parser = _csv.parser(**parser_options) - - class reader(_OCcsv): - def __init__(self, iterobj, dialect = 'excel', - fieldnames=None, restfield=None, - **options): - self.iterobj = iter(iterobj) - self.fieldnames = fieldnames - self.restfield = restfield - _OCcsv.__init__(self, dialect, **options) - - def __iter__(self): - return self - - def next(self): - while 1: - fields = self.parser.parse(self.iterobj.next()) - if fields: - if self.fieldnames is not None: - lf = len(self.fieldnames) - result = dict(zip(self.fieldnames, fields)) - if (lf < len(fields) and - self.restfield is not None): - result[self.restfield] = fields[lf:] - return result - return fields - - class writer(_OCcsv): - def __init__(self, fileobj, dialect='excel', fieldnames=None, **options): - self.fileobj = fileobj - self.fieldnames = fieldnames - _OCcsv.__init__(self, dialect, **options) - - def writerow(self, fields): - # if fields is a dict, we need a valid fieldnames list - # if self.fieldnames is None we'll get a TypeError in the for stmt - # if fields is not a dict we'll get an AttributeError on .get() - try: - flist = [] - for k in self.fieldnames: - flist.append(fields.get(k, "")) - fields = flist - except (TypeError, AttributeError): - pass - self.fileobj.write(self.parser.join(fields)) - - def writerows(self, lines): - for fields in lines: - self.writerow(fields) - - # An alternate way of populating the dialects dictionary... - #def _init_dialects(): - # global _dialects - # mod = sys.modules[__name__] - # for name in dir(mod): - # attr = getattr(mod, name) - # try: - # if issubclass(attr, Dialect) and attr is not Dialect: - # dialect = attr() - # _dialects[dialect.name] = dialect - # except TypeError: - # pass - # - #_init_dialects() --- 55,56 ---- From tim_one@users.sourceforge.net Fri Feb 7 01:53:50 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 06 Feb 2003 17:53:50 -0800 Subject: [Python-checkins] python/dist/src/Lib pydoc.py,1.74,1.75 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv20760/Lib Modified Files: pydoc.py Log Message: SF bug 666444: 'help' makes linefeed only under Win32. Reverting one of those irritating "security fixes". fdopen() opens files in binary mode. That makes pydoc skip the \r\n on Windows that's need to make the output readable in the shell. Screw it. Index: pydoc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pydoc.py,v retrieving revision 1.74 retrieving revision 1.75 diff -C2 -d -r1.74 -r1.75 *** pydoc.py 28 Dec 2002 09:23:08 -0000 1.74 --- pydoc.py 7 Feb 2003 01:53:46 -0000 1.75 *************** *** 1230,1235 **** """Page through text by invoking a program on a temporary file.""" import tempfile ! (fd, filename) = tempfile.mkstemp() ! file = os.fdopen(fd, 'w') file.write(text) file.close() --- 1230,1235 ---- """Page through text by invoking a program on a temporary file.""" import tempfile ! filename = tempfile.mktemp() ! file = open(filename, 'w') file.write(text) file.close() From fdrake@users.sourceforge.net Fri Feb 7 02:15:58 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Thu, 06 Feb 2003 18:15:58 -0800 Subject: [Python-checkins] python/dist/src/Modules/expat expat.h,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Modules/expat In directory sc8-pr-cvs1:/tmp/cvs-serv2387 Modified Files: expat.h Log Message: Integrate the patch from expat.h 1.51; needed for some C compilers. Closes SF bug #680797. Index: expat.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/expat/expat.h,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** expat.h 25 Jan 2003 22:41:29 -0000 1.4 --- expat.h 7 Feb 2003 02:15:56 -0000 1.5 *************** *** 58,61 **** --- 58,81 ---- #define XML_FALSE ((XML_Bool) 0) + /* The XML_Status enum gives the possible return values for several + API functions. The preprocessor #defines are included so this + stanza can be added to code that still needs to support older + versions of Expat 1.95.x: + + #ifndef XML_STATUS_OK + #define XML_STATUS_OK 1 + #define XML_STATUS_ERROR 0 + #endif + + Otherwise, the #define hackery is quite ugly and would have been + dropped. + */ + enum XML_Status { + XML_STATUS_ERROR = 0, + #define XML_STATUS_ERROR XML_STATUS_ERROR + XML_STATUS_OK = 1 + #define XML_STATUS_OK XML_STATUS_OK + }; + enum XML_Error { XML_ERROR_NONE, *************** *** 718,743 **** may be zero for this call (or any other). ! The XML_Status enum gives the possible return values for the ! XML_Parse and XML_ParseBuffer functions. Though the return values ! for these functions has always been described as a Boolean value, ! the implementation, at least for the 1.95.x series, has always ! returned exactly one of these values. The preprocessor #defines ! are included so this stanza can be added to code that still needs ! to support older versions of Expat 1.95.x: ! ! #ifndef XML_STATUS_OK ! #define XML_STATUS_OK 1 ! #define XML_STATUS_ERROR 0 ! #endif ! ! Otherwise, the #define hackery is quite ugly and would have been dropped. */ - enum XML_Status { - XML_STATUS_ERROR = 0, - #define XML_STATUS_ERROR XML_STATUS_ERROR - XML_STATUS_OK = 1 - #define XML_STATUS_OK XML_STATUS_OK - }; - XMLPARSEAPI(enum XML_Status) XML_Parse(XML_Parser parser, const char *s, int len, int isFinal); --- 738,746 ---- may be zero for this call (or any other). ! Though the return values for these functions has always been ! described as a Boolean value, the implementation, at least for the ! 1.95.x series, has always returned exactly one of the XML_Status ! values. */ XMLPARSEAPI(enum XML_Status) XML_Parse(XML_Parser parser, const char *s, int len, int isFinal); From nnorwitz@users.sourceforge.net Fri Feb 7 02:27:40 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 06 Feb 2003 18:27:40 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.110,1.111 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv8140/lib Modified Files: libos.tex Log Message: Fix SF bug #675259, os.environ leaks under FreeBSD and Mac OS X Even with the extra work to cleanup the env, *BSD still leaks. Add a note. Will backport. Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.110 retrieving revision 1.111 diff -C2 -d -r1.110 -r1.111 *** libos.tex 3 Feb 2003 15:36:26 -0000 1.110 --- libos.tex 7 Feb 2003 02:27:36 -0000 1.111 *************** *** 94,98 **** mapping may be used to modify the environment as well as query the environment. \function{putenv()} will be called automatically when ! the mapping is modified. If \function{putenv()} is not provided, this mapping may be passed to --- 94,100 ---- mapping may be used to modify the environment as well as query the environment. \function{putenv()} will be called automatically when ! the mapping is modified. \note{On some platforms, including ! FreeBSD and Mac OS X, setting \code{environ} may cause memory leaks. ! Refer to the system documentation for putenv.} If \function{putenv()} is not provided, this mapping may be passed to *************** *** 193,196 **** --- 195,202 ---- \function{fork()} and \function{execv()}. Availability: most flavors of \UNIX, Windows. + + \note{On some platforms, including FreeBSD and Mac OS X, + setting \code{environ} may cause memory leaks. + Refer to the system documentation for putenv.} When \function{putenv()} is From nnorwitz@users.sourceforge.net Fri Feb 7 02:29:03 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 06 Feb 2003 18:29:03 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.74.2.1.2.9,1.74.2.1.2.10 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv9178/Doc/lib Modified Files: Tag: release22-maint libos.tex Log Message: Fix SF bug #675259, os.environ leaks under FreeBSD and Mac OS X Even with the extra work to cleanup the env, *BSD still leaks. Add a note. Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.74.2.1.2.9 retrieving revision 1.74.2.1.2.10 diff -C2 -d -r1.74.2.1.2.9 -r1.74.2.1.2.10 *** libos.tex 6 Dec 2002 16:43:48 -0000 1.74.2.1.2.9 --- libos.tex 7 Feb 2003 02:29:01 -0000 1.74.2.1.2.10 *************** *** 94,98 **** mapping may be used to modify the environment as well as query the environment. \function{putenv()} will be called automatically when ! the mapping is modified. If \function{putenv()} is not provided, this mapping may be passed to --- 94,100 ---- mapping may be used to modify the environment as well as query the environment. \function{putenv()} will be called automatically when ! the mapping is modified. \note{On some platforms, including ! FreeBSD and Mac OS X, setting \code{environ} may cause memory leaks. ! Refer to the system documentation for putenv.} If \function{putenv()} is not provided, this mapping may be passed to *************** *** 182,185 **** --- 184,191 ---- \function{fork()} and \function{execv()}. Availability: most flavors of \UNIX, Windows. + + \note{On some platforms, including FreeBSD and Mac OS X, + setting \code{environ} may cause memory leaks. + Refer to the system documentation for putenv.} When \function{putenv()} is From andrewmcnamara@users.sourceforge.net Fri Feb 7 02:36:28 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 18:36:28 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.17,1.18 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv12758 Modified Files: _csv.c Log Message: Updated module docstring to match current API. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** _csv.c 7 Feb 2003 01:27:21 -0000 1.17 --- _csv.c 7 Feb 2003 02:36:25 -0000 1.18 *************** *** 1111,1155 **** */ - static struct PyMethodDef csv_methods[] = { - { "reader", (PyCFunction)csv_reader, METH_VARARGS | METH_KEYWORDS}, - { "writer", (PyCFunction)csv_writer, METH_VARARGS | METH_KEYWORDS}, - { "list_dialects", (PyCFunction)csv_list_dialects, METH_VARARGS}, - { "register_dialect", (PyCFunction)csv_register_dialect, METH_VARARGS}, - { "unregister_dialect", (PyCFunction)csv_unregister_dialect, METH_VARARGS}, - { "get_dialect", (PyCFunction)csv_get_dialect, METH_VARARGS}, - { NULL, NULL } - }; - PyDoc_STRVAR(csv_module_doc, ! "This module provides class for performing CSV parsing and writing.\n" "\n" ! "The CSV parser object (returned by the parser() function) supports the\n" ! "following methods:\n" ! " clear()\n" ! " Discards all fields parsed so far. If autoclear is set to\n" ! " zero. You should call this after a parser exception.\n" "\n" - " parse(string) -> list of strings\n" - " Extracts fields from the (partial) CSV record in string.\n" - " Trailing end of line characters are ignored, so you do not\n" - " need to strip the string before passing it to the parser. If\n" - " you pass more than a single line of text, a _csv.Error\n" - " exception will be raised.\n" "\n" ! " join(sequence) -> string\n" ! " Construct a CSV record from a sequence of fields. Non-string\n" ! " elements will be converted to string.\n" "\n" ! "Typical usage:\n" "\n" ! " import _csv\n" ! " p = _csv.parser()\n" ! " fp = open('afile.csv', 'U')\n" ! " for line in fp:\n" ! " fields = p.parse(line)\n" ! " if not fields:\n" ! " # multi-line record\n" ! " continue\n" ! " # process the fields\n"); PyMODINIT_FUNC --- 1111,1229 ---- */ PyDoc_STRVAR(csv_module_doc, ! "CSV parsing and writing.\n" "\n" ! "This module provides classes that assist in the reading and writing\n" ! "of Comma Separated Value (CSV) files, and implements the interface\n" ! "described by PEP 305. Although many CSV files are simple to parse,\n" ! "the format is not formally defined by a stable specification and\n" ! "is subtle enough that parsing lines of a CSV file with something\n" ! "like line.split(\",\") is bound to fail. The module supports three\n" ! "basic APIs: reading, writing, and registration of dialects.\n" "\n" "\n" ! "READING:\n" "\n" ! "The reader interface is provided by a factory function \"reader\":\n" "\n" ! " csv_reader = reader(iterable [, dialect='excel']\n" ! " [optional keyword args])\n" ! " for row in csv_reader:\n" ! " process(row)\n" ! "\n" ! "The \"iterable\" argument can be any object that returns a line\n" ! "of input for each iteration, such as a file object or a list. The\n" ! "optional \"dialect\" parameter is discussed below. The function\n" ! "also accepts optional keyword arguments which override settings\n" ! "provided by the dialect.\n" ! "\n" ! "The returned object is an iterator. Each iteration returns a row\n" ! "of the CSV file (which can span multiple input lines):\n" ! "\n" ! "\n" ! "WRITING:\n" ! "\n" ! "The writer interface is provided by a factory function \"writer\":\n" ! "\n" ! " csv_writer = csv.writer(fileobj [, dialect='excel']\n" ! " [optional keyword args])\n" ! " for row in csv_writer:\n" ! " csv_writer.writerow(row)\n" ! "\n" ! " [or]\n" ! "\n" ! " csv_writer = csv.writer(fileobj [, dialect='excel']\n" ! " [optional keyword args])\n" ! " csv_writer.writerows(rows)\n" ! "\n" ! "The \"fileobj\" argument can be any object that supports the file API.\n" ! "\n" ! "\n" ! "DIALECT REGISTRATION:\n" ! "\n" ! "Readers and writers support a dialect argument, which is a convient\n" ! "handle on a group of settings. When the dialect argument is a string,\n" ! "it identifies one of the dialects registered with the module. If it\n" ! "is a class or instance, the attributes of the argument are used as the\n" ! "settings for the reader or writer:\n" ! "\n" ! " class excel:\n" ! " delimiter = ','\n" ! " quotechar = '\"'\n" ! " escapechar = None\n" ! " doublequote = True\n" ! " skipinitialspace = False\n" ! " lineterminator = '\r\n'\n" ! " quoting = QUOTE_MINIMAL\n" ! "\n" ! "The dialect registry is supported by four functions:\n" ! "\n" ! " list_dialects()\n" ! " register_dialect(name, dialect)\n" ! " unregister_dialect(name)\n" ! " get_dialect(name)\n" ! "\n" ! "SETTINGS:\n" ! "\n" ! " * quotechar - specifies a one-character string to use as the \n" ! " quoting character. It defaults to '\"'.\n" ! " * delimiter - specifies a one-character string to use as the \n" ! " field separator. It defaults to ','.\n" ! " * escapechar - specifies a one-character string used to escape \n" ! " the delimiter when quoting is set to QUOTE_NONE.\n" ! " * skipinitialspace - specifies how to interpret whitespace which\n" ! " immediately follows a delimiter. It defaults to False, which\n" ! " means that whitespace immediately following a delimiter is part\n" ! " of the following field.\n" ! " * lineterminator - specifies the character sequence which should \n" ! " terminate rows.\n" ! " * quoting - controls when quotes should be generated by the writer.\n" ! " It can take on any of the following module constants:\n" ! "\n" ! " csv.QUOTE_MINIMAL means only when required, for example, when a\n" ! " field contains either the quotechar or the delimiter\n" ! " csv.QUOTE_ALL means that quotes are always placed around fields.\n" ! " csv.QUOTE_NONNUMERIC means that quotes are always placed around\n" ! " fields which contain characters other than [+-0-9.].\n" ! " csv.QUOTE_NONE means that quotes are never placed around fields.\n" ! " * doublequote - controls the handling of quotes inside fields. When\n" ! " True two consecutive quotes are interpreted as one during read,\n" ! " and when writing, each quote is written as two quotes\n"); ! ! static struct PyMethodDef csv_methods[] = { ! { "reader", (PyCFunction)csv_reader, ! METH_VARARGS | METH_KEYWORDS, csv_module_doc}, ! { "writer", (PyCFunction)csv_writer, ! METH_VARARGS | METH_KEYWORDS, csv_module_doc}, ! { "list_dialects", (PyCFunction)csv_list_dialects, ! METH_VARARGS, csv_module_doc}, ! { "register_dialect", (PyCFunction)csv_register_dialect, ! METH_VARARGS, csv_module_doc}, ! { "unregister_dialect", (PyCFunction)csv_unregister_dialect, ! METH_VARARGS, csv_module_doc}, ! { "get_dialect", (PyCFunction)csv_get_dialect, ! METH_VARARGS, csv_module_doc}, ! { NULL, NULL } ! }; PyMODINIT_FUNC From andrewmcnamara@users.sourceforge.net Fri Feb 7 04:46:27 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 20:46:27 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv14308 Modified Files: _csv.c Log Message: Commented out tests that were failing due to changed API, added tests for dialect registry, fixed bugs in dialect registry... 8-) Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** _csv.c 7 Feb 2003 02:36:25 -0000 1.18 --- _csv.c 7 Feb 2003 04:46:25 -0000 1.19 *************** *** 317,326 **** } static int ! parse_dialect_args(PyObject * self, PyObject * dia_inst, PyObject * kwargs) { PyObject * name_obj, * value_obj; ! Py_XINCREF(dia_inst); if (kwargs != NULL) { PyObject * key = PyString_FromString("dialect"); --- 317,339 ---- } + static PyObject * + get_dialect_from_registry(PyObject * name_obj) + { + PyObject *dialect_obj; + + dialect_obj = PyDict_GetItem(dialects, name_obj); + if (dialect_obj == NULL) + return PyErr_Format(error_obj, "unknown dialect '%s'", + PyString_AsString(name_obj)); + Py_INCREF(dialect_obj); + return dialect_obj; + } + static int ! parse_dialect_args(PyObject * self, PyObject * dialect, PyObject * kwargs) { PyObject * name_obj, * value_obj; ! Py_XINCREF(dialect); if (kwargs != NULL) { PyObject * key = PyString_FromString("dialect"); *************** *** 330,368 **** if (d) { Py_INCREF(d); ! Py_XDECREF(dia_inst); PyDict_DelItem(kwargs, key); ! dia_inst = d; } Py_DECREF(key); } ! if (dia_inst != NULL) { int i; PyObject * dir_list; /* If dialect is a string, look it up in our registry */ ! if (PyString_Check(dia_inst) || PyUnicode_Check(dia_inst)) { PyObject * new_dia; ! new_dia = PyDict_GetItem(dialects, dia_inst); ! Py_DECREF(dia_inst); if (new_dia == NULL) return 0; ! Py_INCREF(new_dia); ! dia_inst = new_dia; } /* A class rather than an instance? Instanciate */ ! if (PyObject_TypeCheck(dia_inst, &PyClass_Type)) { PyObject * new_dia; ! new_dia = PyObject_CallFunction(dia_inst, ""); ! Py_DECREF(dia_inst); if (new_dia == NULL) return 0; ! dia_inst = new_dia; } /* Make sure we finally have an instance */ ! if (!PyInstance_Check(dia_inst) || ! (dir_list = PyObject_Dir(dia_inst)) == NULL) { PyErr_SetString(PyExc_TypeError, "dialect must be an instance"); ! Py_DECREF(dia_inst); return 0; } --- 343,380 ---- if (d) { Py_INCREF(d); ! Py_XDECREF(dialect); PyDict_DelItem(kwargs, key); ! dialect = d; } Py_DECREF(key); } ! if (dialect != NULL) { int i; PyObject * dir_list; /* If dialect is a string, look it up in our registry */ ! if (PyString_Check(dialect) || PyUnicode_Check(dialect)) { PyObject * new_dia; ! new_dia = get_dialect_from_registry(dialect); ! Py_DECREF(dialect); if (new_dia == NULL) return 0; ! dialect = new_dia; } /* A class rather than an instance? Instanciate */ ! if (PyObject_TypeCheck(dialect, &PyClass_Type)) { PyObject * new_dia; ! new_dia = PyObject_CallFunction(dialect, ""); ! Py_DECREF(dialect); if (new_dia == NULL) return 0; ! dialect = new_dia; } /* Make sure we finally have an instance */ ! if (!PyInstance_Check(dialect) || ! (dir_list = PyObject_Dir(dialect)) == NULL) { PyErr_SetString(PyExc_TypeError, "dialect must be an instance"); ! Py_DECREF(dialect); return 0; } *************** *** 372,376 **** if (PyString_AsString(name_obj)[0] == '_') continue; ! value_obj = PyObject_GetAttr(dia_inst, name_obj); if (value_obj) { if (PyObject_SetAttr(self, name_obj, --- 384,388 ---- if (PyString_AsString(name_obj)[0] == '_') continue; ! value_obj = PyObject_GetAttr(dialect, name_obj); if (value_obj) { if (PyObject_SetAttr(self, name_obj, *************** *** 383,387 **** } Py_DECREF(dir_list); ! Py_DECREF(dia_inst); } if (kwargs != NULL) { --- 395,399 ---- } Py_DECREF(dir_list); ! Py_DECREF(dialect); } if (kwargs != NULL) { *************** *** 1090,1094 **** return NULL; if (PyDict_DelItem(dialects, name_obj) < 0) ! return NULL; Py_INCREF(Py_None); return Py_None; --- 1102,1107 ---- return NULL; if (PyDict_DelItem(dialects, name_obj) < 0) ! return PyErr_Format(error_obj, "unknown dialect '%s'", ! PyString_AsString(name_obj)); Py_INCREF(Py_None); return Py_None; *************** *** 1098,1108 **** csv_get_dialect(PyObject *module, PyObject *args) { ! PyObject *name_obj, *dialect_obj; if (!PyArg_ParseTuple(args, "O!", &PyBaseString_Type, &name_obj)) return NULL; ! dialect_obj = PyDict_GetItem(dialects, name_obj); ! Py_XINCREF(dialect_obj); ! return dialect_obj; } --- 1111,1119 ---- csv_get_dialect(PyObject *module, PyObject *args) { ! PyObject *name_obj; if (!PyArg_ParseTuple(args, "O!", &PyBaseString_Type, &name_obj)) return NULL; ! return get_dialect_from_registry(name_obj); } From andrewmcnamara@users.sourceforge.net Fri Feb 7 04:46:27 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 20:46:27 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv14308/test Modified Files: test_csv.py Log Message: Commented out tests that were failing due to changed API, added tests for dialect registry, fixed bugs in dialect registry... 8-) Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** test_csv.py 6 Feb 2003 04:51:47 -0000 1.20 --- test_csv.py 7 Feb 2003 04:46:25 -0000 1.21 *************** *** 8,12 **** import _csv ! class Test_Csv(unittest.TestCase): """ Test the underlying C csv parser in ways that are not appropriate --- 8,13 ---- import _csv ! # Disabled pending update to new API ! class xTest_Csv(unittest.TestCase): """ Test the underlying C csv parser in ways that are not appropriate *************** *** 241,245 **** self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']]) ! class TestDictFields(unittest.TestCase): def test_write_simple_dict(self): fileobj = StringIO() --- 242,247 ---- self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']]) ! # Disabled, pending support in csv.utils module ! class xTestDictFields(unittest.TestCase): def test_write_simple_dict(self): fileobj = StringIO() *************** *** 310,336 **** self.assertEqual(fileobj.getvalue(), expected) ! class TestDialects(unittest.TestCase): ! def test_register(self): ! class myexceltsv(csv.excel): ! delimiter = "\t" ! csv.register_dialect("myexceltsv", myexceltsv) ! self.assertEqual(isinstance(csv.get_dialect("myexceltsv"), ! myexceltsv), 1==1) ! csv.unregister_dialect("myexceltsv") ! ! def test_get(self): ! self.assertEqual(isinstance(csv.get_dialect("excel"), ! csv.excel), 1==1) ! ! def test_list(self): ! for dname in csv.list_dialects(): ! d = csv.get_dialect(dname) ! self.assertEqual(d._name, dname) ! def test_bad_register(self): ! class myexceltsv: delimiter = "\t" ! self.assertRaises(TypeError, csv.register_dialect, ! "myexceltsv", myexceltsv) def test_incomplete_dialect(self): --- 312,343 ---- self.assertEqual(fileobj.getvalue(), expected) ! class TestDialectRegistry(unittest.TestCase): ! def test_registry_badargs(self): ! self.assertRaises(TypeError, csv.list_dialects, None) ! self.assertRaises(TypeError, csv.get_dialect, None) ! self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") ! self.assertRaises(TypeError, csv.unregister_dialect, None) ! self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") ! self.assertRaises(TypeError, csv.register_dialect, None) ! self.assertRaises(TypeError, csv.register_dialect, "nonesuch", None) ! class bogus: ! def __init__(self): ! raise KeyError ! self.assertRaises(KeyError, csv.register_dialect, "nonesuch", bogus) ! def test_registry(self): ! class myexceltsv(csv.excel): delimiter = "\t" ! name = "myexceltsv" ! expected_dialects = csv.list_dialects() + [name] ! expected_dialects.sort() ! csv.register_dialect(name, myexceltsv) ! try: ! self.failUnless(isinstance(csv.get_dialect(name), myexceltsv)) ! got_dialects = csv.list_dialects() ! got_dialects.sort() ! self.assertEqual(expected_dialects, got_dialects) ! finally: ! csv.unregister_dialect(name) def test_incomplete_dialect(self): *************** *** 339,349 **** self.assertRaises(csv.Error, myexceltsv) ! def test_dialect_class(self): ! class myexceltsv(csv.excel): delimiter = "\t" ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect=myexceltsv()) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") --- 346,385 ---- self.assertRaises(csv.Error, myexceltsv) ! def test_dialect_apply(self): ! class testA(csv.excel): delimiter = "\t" ! class testB(csv.excel): ! delimiter = ":" ! class testC(csv.excel): ! delimiter = "|" ! ! csv.register_dialect('testC', testC) ! try: ! fileobj = StringIO() ! writer = csv.writer(fileobj) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1,2,3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, testA) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect=testB()) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1:2:3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect='testC') ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1|2|3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect=testA, delimiter=';') ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1;2;3\r\n") ! finally: ! csv.unregister_dialect('testC') From rhettinger@users.sourceforge.net Fri Feb 7 05:33:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 06 Feb 2003 21:33:00 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_itertools.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2842/Lib/test Modified Files: test_itertools.py Log Message: SF bug #681003: itertools issues * Fixed typo in exception message for times() * Filled in missing times_traverse() * Document reasons that imap() did not adopt a None fill-in feature * Document that count(sys.maxint) will wrap-around on overflow * Add overflow test to islice() * Check that starmap()'s argument returns a tuple * Verify that imap()'s tuple re-use is safe * Make a similar tuple re-use (with safety check) for izip() Index: test_itertools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_itertools.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_itertools.py 1 Feb 2003 02:33:45 -0000 1.2 --- test_itertools.py 7 Feb 2003 05:32:58 -0000 1.3 *************** *** 2,5 **** --- 2,6 ---- from test import test_support from itertools import * + import sys class TestBasicOps(unittest.TestCase): *************** *** 48,51 **** --- 49,53 ---- self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) + self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]])) def test_islice(self): *************** *** 72,75 **** --- 74,78 ---- self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) + self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1) def test_takewhile(self): From rhettinger@users.sourceforge.net Fri Feb 7 05:32:59 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 06 Feb 2003 21:32:59 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2842/Modules Modified Files: itertoolsmodule.c Log Message: SF bug #681003: itertools issues * Fixed typo in exception message for times() * Filled in missing times_traverse() * Document reasons that imap() did not adopt a None fill-in feature * Document that count(sys.maxint) will wrap-around on overflow * Add overflow test to islice() * Check that starmap()'s argument returns a tuple * Verify that imap()'s tuple re-use is safe * Make a similar tuple re-use (with safety check) for izip() Index: itertoolsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/itertoolsmodule.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** itertoolsmodule.c 1 Feb 2003 00:10:10 -0000 1.1 --- itertoolsmodule.c 7 Feb 2003 05:32:57 -0000 1.2 *************** *** 404,407 **** --- 404,408 ---- { PyObject *item; + long oldnext; while (lz->cnt < lz->next) { *************** *** 418,422 **** --- 419,426 ---- return NULL; lz->cnt++; + oldnext = lz->next; lz->next += lz->step; + if (lz->next < oldnext) /* Check for overflow */ + lz->next = lz->stop; return item; } *************** *** 559,562 **** --- 563,572 ---- if (args == NULL) return NULL; + if (!PyTuple_CheckExact(args)) { + Py_DECREF(args); + PyErr_SetString(PyExc_TypeError, + "iterator must return a tuple"); + return NULL; + } result = PyObject_Call(lz->func, args, NULL); Py_DECREF(args); *************** *** 720,723 **** --- 730,758 ---- } + /* + imap() is an iterator version of __builtins__.map() except that it does + not have the None fill-in feature. That was intentionally left out for + the following reasons: + + 1) Itertools are designed to be easily combined and chained together. + Having all tools stop with the shortest input is a unifying principle + that makes it easier to combine finite iterators (supplying data) with + infinite iterators like count() and repeat() (for supplying sequential + or constant arguments to a function). + + 2) In typical use cases for combining itertools, having one finite data + supplier run out before another is likely to be an error condition which + should not pass silently by automatically supplying None. + + 3) The use cases for automatic None fill-in are rare -- not many functions + do something useful when a parameter suddenly switches type and becomes + None. + + 4) If a need does arise, it can be met by __builtins__.map() or by + writing a generator. + + 5) Similar toolsets in Haskell and SML do not have automatic None fill-in. + */ + static PyObject * imap_next(imapobject *lz) *************** *** 743,746 **** --- 778,786 ---- return argtuple; } else { + if (argtuple->ob_refcnt > 1) { + argtuple = PyTuple_New(numargs); + if (argtuple == NULL) + return NULL; + } for (i=0 ; iiters, i)); *************** *** 838,842 **** if (cnt < 0) { PyErr_SetString(PyExc_ValueError, ! "count for imap() cannot be negative."); return NULL; } --- 878,882 ---- if (cnt < 0) { PyErr_SetString(PyExc_ValueError, ! "count for times() cannot be negative."); return NULL; } *************** *** 861,864 **** --- 901,912 ---- } + static int + times_traverse(timesobject *lz, visitproc visit, void *arg) + { + if (lz->obj) + return visit(lz->obj, arg); + return 0; + } + static PyObject * times_next(timesobject *lz) *************** *** 912,916 **** Py_TPFLAGS_BASETYPE, /* tp_flags */ times_doc, /* tp_doc */ ! 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ --- 960,964 ---- Py_TPFLAGS_BASETYPE, /* tp_flags */ times_doc, /* tp_doc */ ! (traverseproc)times_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ *************** *** 1192,1195 **** --- 1240,1244 ---- long tuplesize; PyObject *ittuple; /* tuple of iterators */ + PyObject *result; } izipobject; *************** *** 1202,1205 **** --- 1251,1255 ---- int i; PyObject *ittuple; /* tuple of iterators */ + PyObject *result; int tuplesize = PySequence_Length(args); *************** *** 1231,1242 **** --- 1281,1305 ---- } + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + /* create izipobject structure */ lz = (izipobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(ittuple); + Py_DECREF(result); return NULL; } lz->ittuple = ittuple; lz->tuplesize = tuplesize; + lz->result = result; return (PyObject *)lz; *************** *** 1248,1251 **** --- 1311,1315 ---- PyObject_GC_UnTrack(lz); Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); lz->ob_type->tp_free(lz); } *************** *** 1264,1274 **** int i; long tuplesize = lz->tuplesize; ! PyObject *result; PyObject *it; PyObject *item; ! result = PyTuple_New(tuplesize); ! if (result == NULL) ! return NULL; for (i=0 ; i < tuplesize ; i++) { --- 1328,1352 ---- int i; long tuplesize = lz->tuplesize; ! PyObject *result = lz->result; PyObject *it; PyObject *item; ! assert(result->ob_refcnt >= 1); ! if (result->ob_refcnt == 1) { ! for (i=0 ; i < tuplesize ; i++) { ! Py_DECREF(PyTuple_GET_ITEM(result, i)); ! PyTuple_SET_ITEM(result, i, NULL); ! } ! Py_INCREF(result); ! } else { ! Py_DECREF(result); ! result = PyTuple_New(tuplesize); ! if (result == NULL) ! return NULL; ! Py_INCREF(result); ! lz->result = result; ! } ! assert(lz->result == result); ! assert(result->ob_refcnt == 2); for (i=0 ; i < tuplesize ; i++) { From rhettinger@users.sourceforge.net Fri Feb 7 05:33:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 06 Feb 2003 21:33:00 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv2842/Doc/lib Modified Files: libitertools.tex Log Message: SF bug #681003: itertools issues * Fixed typo in exception message for times() * Filled in missing times_traverse() * Document reasons that imap() did not adopt a None fill-in feature * Document that count(sys.maxint) will wrap-around on overflow * Add overflow test to islice() * Check that starmap()'s argument returns a tuple * Verify that imap()'s tuple re-use is safe * Make a similar tuple re-use (with safety check) for izip() Index: libitertools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libitertools.tex,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** libitertools.tex 1 Feb 2003 00:10:09 -0000 1.1 --- libitertools.tex 7 Feb 2003 05:32:57 -0000 1.2 *************** *** 83,86 **** --- 83,90 ---- cnt += 1 \end{verbatim} + + Note, \function{count()} does not check for overflow and will return + negative numbers after exceeding \code{sys.maxint}. This behavior + may change in the future. \end{funcdesc} From andrewmcnamara@users.sourceforge.net Fri Feb 7 06:33:02 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 22:33:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv7551 Modified Files: _csv.c Log Message: Improved the way we call self->writeline in writerow, fixed bug handling errors raised by PyIter_Next in writerows. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** _csv.c 7 Feb 2003 04:46:25 -0000 1.19 --- _csv.c 7 Feb 2003 06:33:00 -0000 1.20 *************** *** 849,853 **** { int len, i; - PyObject *arglist, *result; if (!PySequence_Check(seq)) --- 849,852 ---- *************** *** 899,908 **** return 0; ! arglist = Py_BuildValue("(s#)", self->rec, self->rec_len); ! if (!arglist) ! return NULL; ! result = PyEval_CallObject(self->writeline, arglist); ! Py_DECREF(arglist); ! return result; } --- 898,903 ---- return 0; ! return PyEval_CallFunction(self->writeline, ! "(s#)", self->rec, self->rec_len); } *************** *** 929,932 **** --- 924,929 ---- } Py_DECREF(row_iter); + if (PyErr_Occurred()) + return NULL; Py_INCREF(Py_None); return Py_None; From andrewmcnamara@users.sourceforge.net Fri Feb 7 06:34:25 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 06 Feb 2003 22:34:25 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv8246/test Modified Files: test_csv.py Log Message: Reinstated most of the tests broken by API changes, added many tests - have about 92% coverage now. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** test_csv.py 7 Feb 2003 04:46:25 -0000 1.21 --- test_csv.py 7 Feb 2003 06:34:23 -0000 1.22 *************** *** 6,113 **** from StringIO import StringIO import csv - import _csv ! # Disabled pending update to new API ! class xTest_Csv(unittest.TestCase): """ Test the underlying C csv parser in ways that are not appropriate ! from the high level interface. """ ! def test_init(self): ! "test that the module returns a parser" ! parser = _csv.parser() ! self.failUnless(hasattr(parser, 'parse')) ! def test_parameter_validation(self): ! self.assertRaises(TypeError, _csv.parser, FlibbleWort = 0) ! self.assertRaises(ValueError, _csv.parser, quoting = -1) ! self.assertRaises(ValueError, _csv.parser, quoting = csv.QUOTE_NONE + 1) ! self.assertRaises(TypeError, _csv.parser, delimiter = None) ! self.assertRaises(TypeError, _csv.parser, skipinitialspace = None) ! def test_parameter(self): ! parser = _csv.parser(delimiter = "\t") ! self.assertEqual(parser.delimiter, "\t") ! parser = _csv.parser(quotechar = "'") ! self.assertEqual(parser.quotechar, "'") ! def test_attr_validation(self): ! parser = _csv.parser() ! self.assertRaises(AttributeError, delattr, parser, 'quoting') ! self.assertRaises(TypeError, setattr, parser, 'quoting', -1) ! self.assertRaises(TypeError, setattr, parser, 'quoting', ! csv.QUOTE_NONE + 1) ! self.assertRaises(TypeError, setattr, parser, 'quotechar', 0) ! self.assertRaises(TypeError, setattr, parser, 'escapechar', 0) ! self.assertRaises(TypeError, setattr, parser, 'lineterminator', None) ! def test_setattr(self): ! parser = _csv.parser() ! parser.delimiter = "\t" ! self.assertEqual(parser.delimiter, "\t") ! parser = _csv.parser() ! parser.quotechar = "'" ! self.assertEqual(parser.quotechar, "'") ! def test_join_bigfield(self): # This exercises the buffer realloc functionality - parser = _csv.parser() bigstring = 'X' * 50000 ! result = parser.join([bigstring,bigstring]) ! self.assertEqual(result, '%s,%s%s' % \ ! (bigstring, bigstring, parser.lineterminator)) ! def test_join_quoting(self): ! parser = _csv.parser() ! self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') ! parser = _csv.parser(quoting = csv.QUOTE_NONE) ! self.assertRaises(_csv.Error, parser.join, ['a','1','p,q']) ! parser = _csv.parser(quoting = csv.QUOTE_MINIMAL) ! self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') ! parser = _csv.parser(quoting = csv.QUOTE_NONNUMERIC) ! self.assertEqual(parser.join(['a','1','p,q']), '"a",1,"p,q"\r\n') ! parser = _csv.parser(quoting = csv.QUOTE_ALL) ! self.assertEqual(parser.join(['a','1','p,q']), '"a","1","p,q"\r\n') ! def test_join_escape(self): ! parser = _csv.parser(escapechar='\\') ! self.assertEqual(parser.join(['a','1','p,q']), 'a,1,"p,q"\r\n') ! parser.doublequote = 0 ! self.assertEqual(parser.join(['a','1','p,"q"']), 'a,1,"p,\\"q"\r\n') ! parser.quoting = csv.QUOTE_NONE ! self.assertEqual(parser.join(['a','1','p,q']), 'a,1,p\\,q\r\n') ! def test_parse(self): ! parser = _csv.parser() ! self.assertRaises(TypeError, parser.parse, None) ! self.assertEqual(parser.parse(''), []) ! def test_parse_eol(self): ! parser = _csv.parser() ! self.assertEqual(parser.parse('a,b'), ['a','b']) ! self.assertEqual(parser.parse('a,b\n'), ['a','b']) ! self.assertEqual(parser.parse('a,b\r\n'), ['a','b']) ! self.assertEqual(parser.parse('a,b\r'), ['a','b']) ! self.assertRaises(csv.Error, parser.parse, 'a,b\rc,d') ! self.assertRaises(csv.Error, parser.parse, 'a,b\nc,d') ! self.assertRaises(csv.Error, parser.parse, 'a,b\r\nc,d') ! def test_parse_escape(self): ! parser = _csv.parser(escapechar='\\') ! self.assertEqual(parser.parse('a,\\b,c'), ['a', '\\b', 'c']) ! self.assertEqual(parser.parse('a,b\\,c'), ['a', 'b,c']) ! self.assertEqual(parser.parse('a,"b\\,c"'), ['a', 'b,c']) ! self.assertEqual(parser.parse('a,"b,\\c"'), ['a', 'b,\\c']) ! self.assertEqual(parser.parse('a,"b,c\\""'), ['a', 'b,c"']) ! self.assertEqual(parser.parse('a,"b,c"\\'), ['a', 'b,c\\']) ! def test_parse_bigfield(self): # This exercises the buffer realloc functionality - parser = _csv.parser() bigstring = 'X' * 50000 ! bigline = '%s,%s%s' % (bigstring, bigstring, parser.lineterminator) ! self.assertEqual(parser.parse(bigline), [bigstring, bigstring]) class TestCsvBase(unittest.TestCase): --- 6,228 ---- from StringIO import StringIO import csv ! class Test_Csv(unittest.TestCase): """ Test the underlying C csv parser in ways that are not appropriate ! from the high level interface. Further tests of this nature are done ! in TestDialectRegistry. """ ! def test_reader_arg_valid(self): ! self.assertRaises(TypeError, csv.reader) ! self.assertRaises(TypeError, csv.reader, None) ! self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0) ! self.assertRaises(csv.Error, csv.reader, [], 'foo') ! class BadClass: ! def __init__(self): ! raise IOError ! self.assertRaises(IOError, csv.reader, [], BadClass) ! self.assertRaises(TypeError, csv.reader, [], None) ! class BadDialect: ! bad_attr = 0 ! self.assertRaises(AttributeError, csv.reader, [], BadDialect) ! def test_writer_arg_valid(self): ! self.assertRaises(TypeError, csv.writer) ! self.assertRaises(TypeError, csv.writer, None) ! self.assertRaises(AttributeError, csv.writer, StringIO(), bad_attr = 0) ! def _test_attrs(self, obj): ! self.assertEqual(obj.delimiter, ',') ! obj.delimiter = '\t' ! self.assertEqual(obj.delimiter, '\t') ! self.assertRaises(AttributeError, delattr, obj, 'delimiter') ! self.assertRaises(TypeError, setattr, obj, 'lineterminator', None) ! obj.escapechar = None ! self.assertEqual(obj.escapechar, None) ! def test_reader_attrs(self): ! self._test_attrs(csv.reader([])) ! def test_writer_attrs(self): ! self._test_attrs(csv.writer(StringIO())) ! def _write_test(self, fields, expect, **kwargs): ! fileobj = StringIO() ! writer = csv.writer(fileobj, **kwargs) ! writer.writerow(fields) ! self.assertEqual(fileobj.getvalue(), expect + writer.lineterminator) ! def test_write_arg_valid(self): ! self.assertRaises(csv.Error, self._write_test, None, '') ! self._write_test((), '') ! self._write_test([None], '""') ! self.assertRaises(csv.Error, self._write_test, ! [None], None, quoting = csv.QUOTE_NONE) ! # Check that exceptions are passed up the chain ! class BadList: ! def __len__(self): ! return 10; ! def __getitem__(self, i): ! if i > 2: ! raise IOError ! self.assertRaises(IOError, self._write_test, BadList(), '') ! class BadItem: ! def __str__(self): ! raise IOError ! self.assertRaises(IOError, self._write_test, [BadItem()], '') ! def test_write_bigfield(self): # This exercises the buffer realloc functionality bigstring = 'X' * 50000 ! self._write_test([bigstring,bigstring], '%s,%s' % \ ! (bigstring, bigstring)) ! def test_write_quoting(self): ! self._write_test(['a','1','p,q'], 'a,1,"p,q"') ! self.assertRaises(csv.Error, ! self._write_test, ! ['a','1','p,q'], 'a,1,"p,q"', ! quoting = csv.QUOTE_NONE) ! self._write_test(['a','1','p,q'], 'a,1,"p,q"', ! quoting = csv.QUOTE_MINIMAL) ! self._write_test(['a','1','p,q'], '"a",1,"p,q"', ! quoting = csv.QUOTE_NONNUMERIC) ! self._write_test(['a','1','p,q'], '"a","1","p,q"', ! quoting = csv.QUOTE_ALL) ! def test_write_escape(self): ! self._write_test(['a','1','p,q'], 'a,1,"p,q"', ! escapechar='\\') ! # FAILED - needs to be fixed [am]: ! # self._write_test(['a','1','p,"q"'], 'a,1,"p,\\"q\\"', ! # escapechar='\\', doublequote = 0) ! self._write_test(['a','1','p,q'], 'a,1,p\\,q', ! escapechar='\\', quoting = csv.QUOTE_NONE) ! def test_writerows(self): ! class BrokenFile: ! def write(self, buf): ! raise IOError ! writer = csv.writer(BrokenFile()) ! self.assertRaises(IOError, writer.writerows, [['a']]) ! fileobj = StringIO() ! writer = csv.writer(fileobj) ! self.assertRaises(TypeError, writer.writerows, None) ! writer.writerows([['a','b'],['c','d']]) ! self.assertEqual(fileobj.getvalue(), "a,b\r\nc,d\r\n") ! def _read_test(self, input, expect, **kwargs): ! reader = csv.reader(input, **kwargs) ! result = list(reader) ! self.assertEqual(result, expect) ! def test_read_oddinputs(self): ! self._read_test([], []) ! self._read_test([''], [[]]) ! self.assertRaises(csv.Error, self._read_test, ! ['"ab"c'], None, strict = 1) ! self._read_test(['"ab"c'], [['abc']], doublequote = 0) ! def test_read_eol(self): ! self._read_test(['a,b'], [['a','b']]) ! self._read_test(['a,b\n'], [['a','b']]) ! self._read_test(['a,b\r\n'], [['a','b']]) ! self._read_test(['a,b\r'], [['a','b']]) ! self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], []) ! self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], []) ! self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], []) ! ! def test_read_escape(self): ! self._read_test(['a,\\b,c'], [['a', '\\b', 'c']], escapechar='\\') ! self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\') ! self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\') ! self._read_test(['a,"b,\\c"'], [['a', 'b,\\c']], escapechar='\\') ! self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\') ! self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\') ! ! def test_read_bigfield(self): # This exercises the buffer realloc functionality bigstring = 'X' * 50000 ! bigline = '%s,%s' % (bigstring, bigstring) ! self._read_test([bigline], [[bigstring, bigstring]]) ! ! class TestDialectRegistry(unittest.TestCase): ! def test_registry_badargs(self): ! self.assertRaises(TypeError, csv.list_dialects, None) ! self.assertRaises(TypeError, csv.get_dialect, None) ! self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") ! self.assertRaises(TypeError, csv.unregister_dialect, None) ! self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") ! self.assertRaises(TypeError, csv.register_dialect, None) ! self.assertRaises(TypeError, csv.register_dialect, "nonesuch", None) ! class bogus: ! def __init__(self): ! raise KeyError ! self.assertRaises(KeyError, csv.register_dialect, "nonesuch", bogus) ! ! def test_registry(self): ! class myexceltsv(csv.excel): ! delimiter = "\t" ! name = "myexceltsv" ! expected_dialects = csv.list_dialects() + [name] ! expected_dialects.sort() ! csv.register_dialect(name, myexceltsv) ! try: ! self.failUnless(isinstance(csv.get_dialect(name), myexceltsv)) ! got_dialects = csv.list_dialects() ! got_dialects.sort() ! self.assertEqual(expected_dialects, got_dialects) ! finally: ! csv.unregister_dialect(name) ! ! def test_incomplete_dialect(self): ! class myexceltsv(csv.Dialect): ! delimiter = "\t" ! self.assertRaises(csv.Error, myexceltsv) ! ! def test_dialect_apply(self): ! class testA(csv.excel): ! delimiter = "\t" ! class testB(csv.excel): ! delimiter = ":" ! class testC(csv.excel): ! delimiter = "|" ! ! csv.register_dialect('testC', testC) ! try: ! fileobj = StringIO() ! writer = csv.writer(fileobj) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1,2,3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, testA) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect=testB()) ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1:2:3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect='testC') ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1|2|3\r\n") ! ! fileobj = StringIO() ! writer = csv.writer(fileobj, dialect=testA, delimiter=';') ! writer.writerow([1,2,3]) ! self.assertEqual(fileobj.getvalue(), "1;2;3\r\n") ! finally: ! csv.unregister_dialect('testC') ! ! def test_bad_dialect(self): ! # Unknown parameter ! self.assertRaises(AttributeError, csv.reader, [], bad_attr = 0) ! # Bad values ! self.assertRaises(TypeError, csv.reader, [], delimiter = None) ! self.assertRaises(TypeError, csv.reader, [], quoting = -1) ! self.assertRaises(TypeError, csv.reader, [], quoting = 100) class TestCsvBase(unittest.TestCase): *************** *** 312,387 **** self.assertEqual(fileobj.getvalue(), expected) - class TestDialectRegistry(unittest.TestCase): - def test_registry_badargs(self): - self.assertRaises(TypeError, csv.list_dialects, None) - self.assertRaises(TypeError, csv.get_dialect, None) - self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") - self.assertRaises(TypeError, csv.unregister_dialect, None) - self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") - self.assertRaises(TypeError, csv.register_dialect, None) - self.assertRaises(TypeError, csv.register_dialect, "nonesuch", None) - class bogus: - def __init__(self): - raise KeyError - self.assertRaises(KeyError, csv.register_dialect, "nonesuch", bogus) - - def test_registry(self): - class myexceltsv(csv.excel): - delimiter = "\t" - name = "myexceltsv" - expected_dialects = csv.list_dialects() + [name] - expected_dialects.sort() - csv.register_dialect(name, myexceltsv) - try: - self.failUnless(isinstance(csv.get_dialect(name), myexceltsv)) - got_dialects = csv.list_dialects() - got_dialects.sort() - self.assertEqual(expected_dialects, got_dialects) - finally: - csv.unregister_dialect(name) - - def test_incomplete_dialect(self): - class myexceltsv(csv.Dialect): - delimiter = "\t" - self.assertRaises(csv.Error, myexceltsv) - - def test_dialect_apply(self): - class testA(csv.excel): - delimiter = "\t" - class testB(csv.excel): - delimiter = ":" - class testC(csv.excel): - delimiter = "|" - - csv.register_dialect('testC', testC) - try: - fileobj = StringIO() - writer = csv.writer(fileobj) - writer.writerow([1,2,3]) - self.assertEqual(fileobj.getvalue(), "1,2,3\r\n") - - fileobj = StringIO() - writer = csv.writer(fileobj, testA) - writer.writerow([1,2,3]) - self.assertEqual(fileobj.getvalue(), "1\t2\t3\r\n") - - fileobj = StringIO() - writer = csv.writer(fileobj, dialect=testB()) - writer.writerow([1,2,3]) - self.assertEqual(fileobj.getvalue(), "1:2:3\r\n") - - fileobj = StringIO() - writer = csv.writer(fileobj, dialect='testC') - writer.writerow([1,2,3]) - self.assertEqual(fileobj.getvalue(), "1|2|3\r\n") - - fileobj = StringIO() - writer = csv.writer(fileobj, dialect=testA, delimiter=';') - writer.writerow([1,2,3]) - self.assertEqual(fileobj.getvalue(), "1;2;3\r\n") - finally: - csv.unregister_dialect('testC') - - def _testclasses(): mod = sys.modules[__name__] --- 427,430 ---- From rhettinger@users.sourceforge.net Fri Feb 7 07:26:27 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 06 Feb 2003 23:26:27 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv1779 Modified Files: itertoolsmodule.c Log Message: * Eliminated tuple re-use in imap(). Doing it correctly made the code too hard to read. * Simplified previous changes to izip() to make it easier to read. Index: itertoolsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/itertoolsmodule.c,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** itertoolsmodule.c 7 Feb 2003 05:32:57 -0000 1.2 --- itertoolsmodule.c 7 Feb 2003 07:26:25 -0000 1.3 *************** *** 638,642 **** PyObject_HEAD PyObject *iters; - PyObject *argtuple; PyObject *func; } imapobject; --- 638,641 ---- *************** *** 647,651 **** imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *it, *iters, *argtuple, *func; imapobject *lz; int numargs, i; --- 646,650 ---- imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *it, *iters, *func; imapobject *lz; int numargs, i; *************** *** 662,682 **** return NULL; - argtuple = PyTuple_New(numargs-1); - if (argtuple == NULL) { - Py_DECREF(iters); - return NULL; - } - for (i=1 ; itp_alloc(type, 0); if (lz == NULL) { - Py_DECREF(argtuple); Py_DECREF(iters); return NULL; } lz->iters = iters; - lz->argtuple = argtuple; func = PyTuple_GET_ITEM(args, 0); Py_INCREF(func); --- 674,681 ---- *************** *** 701,705 **** { PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->argtuple); Py_XDECREF(lz->iters); Py_XDECREF(lz->func); --- 689,692 ---- *************** *** 717,725 **** return err; } - if (lz->argtuple) { - err = visit(lz->argtuple, arg); - if (err) - return err; - } if (lz->func) { err = visit(lz->func, arg); --- 704,707 ---- *************** *** 759,795 **** { PyObject *val; ! PyObject *argtuple=lz->argtuple; int numargs, i; numargs = PyTuple_Size(lz->iters); ! if (lz->func == Py_None) { ! argtuple = PyTuple_New(numargs); ! if (argtuple == NULL) ! return NULL; ! for (i=0 ; iiters, i)); ! if (val == NULL) { ! Py_DECREF(argtuple); ! return NULL; ! } ! PyTuple_SET_ITEM(argtuple, i, val); ! } ! return argtuple; ! } else { ! if (argtuple->ob_refcnt > 1) { ! argtuple = PyTuple_New(numargs); ! if (argtuple == NULL) ! return NULL; ! } ! for (i=0 ; iiters, i)); ! if (val == NULL) ! return NULL; ! Py_DECREF(PyTuple_GET_ITEM(argtuple, i)); ! PyTuple_SET_ITEM(argtuple, i, val); } ! return PyObject_Call(lz->func, argtuple, NULL); } } --- 741,766 ---- { PyObject *val; ! PyObject *argtuple; ! PyObject *result; int numargs, i; numargs = PyTuple_Size(lz->iters); ! argtuple = PyTuple_New(numargs); ! if (argtuple == NULL) ! return NULL; ! for (i=0 ; iiters, i)); ! if (val == NULL) { ! Py_DECREF(argtuple); ! return NULL; } ! PyTuple_SET_ITEM(argtuple, i, val); } + if (lz->func == Py_None) + return argtuple; + result = PyObject_Call(lz->func, argtuple, NULL); + Py_DECREF(argtuple); + return result; } *************** *** 1332,1361 **** PyObject *item; - assert(result->ob_refcnt >= 1); if (result->ob_refcnt == 1) { for (i=0 ; i < tuplesize ; i++) { Py_DECREF(PyTuple_GET_ITEM(result, i)); ! PyTuple_SET_ITEM(result, i, NULL); } Py_INCREF(result); } else { - Py_DECREF(result); result = PyTuple_New(tuplesize); if (result == NULL) return NULL; ! Py_INCREF(result); ! lz->result = result; ! } ! assert(lz->result == result); ! assert(result->ob_refcnt == 2); ! ! for (i=0 ; i < tuplesize ; i++) { ! it = PyTuple_GET_ITEM(lz->ittuple, i); ! item = PyIter_Next(it); ! if (item == NULL) { ! Py_DECREF(result); ! return NULL; } - PyTuple_SET_ITEM(result, i, item); } return result; --- 1303,1329 ---- PyObject *item; if (result->ob_refcnt == 1) { for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = PyIter_Next(it); + if (item == NULL) + return NULL; Py_DECREF(PyTuple_GET_ITEM(result, i)); ! PyTuple_SET_ITEM(result, i, item); } Py_INCREF(result); } else { result = PyTuple_New(tuplesize); if (result == NULL) return NULL; ! for (i=0 ; i < tuplesize ; i++) { ! it = PyTuple_GET_ITEM(lz->ittuple, i); ! item = PyIter_Next(it); ! if (item == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyTuple_SET_ITEM(result, i, item); } } return result; From fdrake@users.sourceforge.net Fri Feb 7 14:52:23 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Fri, 07 Feb 2003 06:52:23 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.113,1.114 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv22034 Modified Files: whatsnew23.tex Log Message: - make some links into the reference documentation relative for off-line readers - fix some minor typos and markup errors Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.113 retrieving revision 1.114 diff -C2 -d -r1.113 -r1.114 *** whatsnew23.tex 6 Feb 2003 15:14:04 -0000 1.113 --- whatsnew23.tex 7 Feb 2003 14:52:18 -0000 1.114 *************** *** 1,3 **** --- 1,4 ---- \documentclass{howto} + \usepackage{distutils} % $Id$ *************** *** 25,35 **** the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.3, ! such as the ! \citetitle[http://www.python.org/doc/2.3/lib/lib.html]{Python Library ! Reference} and the ! \citetitle[http://www.python.org/doc/2.3/ref/ref.html]{Python ! Reference Manual}. If you want to understand the complete ! implementation and design rationale for a change, refer to the PEP for ! a particular new feature. --- 26,33 ---- the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.3, ! such as the \citetitle[../lib/lib.html]{Python Library Reference} and ! the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want ! to understand the complete implementation and design rationale for a ! change, refer to the PEP for a particular new feature. *************** *** 527,532 **** is only a partial overview of the \module{logging} package, so please see the \ulink{package's reference ! documentation}{http://www.python.org/dev/doc/devel/lib/module-logging.html} ! for all of the details. Reading \pep{282} will also be helpful. --- 525,530 ---- is only a partial overview of the \module{logging} package, so please see the \ulink{package's reference ! documentation}{../lib/module-logging.html} for all of the details. ! Reading \pep{282} will also be helpful. *************** *** 708,720 **** %====================================================================== ! \section{PEP 301: Package Index and Metadata for Distutils\label{section-pep301}} Support for the long-requested Python catalog makes its first appearance in 2.3. ! The core component is the new Distutil \samp{register} command. ! Running \code{python setup.py register} will collect up the metadata describing a package, such as its name, version, maintainer, ! description, \&c., and sends it to a central catalog server. Currently the catalog can be browsed at \url{http://www.amk.ca/cgi-bin/pypi.cgi}, but it will move to --- 706,719 ---- %====================================================================== ! \section{PEP 301: Package Index and Metadata for ! Distutils\label{section-pep301}} Support for the long-requested Python catalog makes its first appearance in 2.3. ! The core component is the new Distutils \command{register} command. ! Running \code{python setup.py register} will collect the metadata describing a package, such as its name, version, maintainer, ! description, \&c., and send it to a central catalog server. Currently the catalog can be browsed at \url{http://www.amk.ca/cgi-bin/pypi.cgi}, but it will move to *************** *** 723,729 **** To make the catalog a bit more useful, a new optional ! \samp{classifiers} keyword argument has been added to the Distutils \function{setup()} function. A list of ! \citetitle[http://www.tuxedo.org/\%7Eesr/trove/]{Trove}-style strings can be supplied to help classify the software. Here's an example \file{setup.py} with classifiers, written to be compatible --- 722,729 ---- To make the catalog a bit more useful, a new optional ! \var{classifiers} keyword argument has been added to the Distutils \function{setup()} function. A list of ! \ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style ! strings can be supplied to help classify the software. Here's an example \file{setup.py} with classifiers, written to be compatible *************** *** 732,749 **** \begin{verbatim} from distutils import core ! kw = ('name': "Quixote", 'version': "0.5.1", 'description': "A highly Pythonic Web application framework", ! ... ! ) ! if (hasattr(core, 'setup_keywords') and ! 'classifiers' in core.setup_keywords): ! kw['classifiers'] = \ ! ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', ! 'Environment :: No Input/Output (Daemon)', ! 'Intended Audience :: Developers'], ! core.setup (**kw) \end{verbatim} --- 732,749 ---- \begin{verbatim} from distutils import core ! kw = {'name': "Quixote", 'version': "0.5.1", 'description': "A highly Pythonic Web application framework", ! # ... ! } ! if ( hasattr(core, 'setup_keywords') and ! 'classifiers' in core.setup_keywords): ! kw['classifiers'] = \ ! ['Topic :: Internet :: WWW/HTTP :: Dynamic Content', ! 'Environment :: No Input/Output (Daemon)', ! 'Intended Audience :: Developers'], ! core.setup(**kw) \end{verbatim} *************** *** 753,757 **** \begin{seealso} ! \seepep{301}{Package Index and Metadata for Distutils}{Written and implemented by Richard Jones.} \end{seealso} --- 753,758 ---- \begin{seealso} ! \seepep{301}{Package Index and Metadata for Distutils}{Written and ! implemented by Richard Jones.} \end{seealso} *************** *** 1080,1084 **** To understand the motivation for this change, read Michele Simionato's article ! \ulink{``Python 2.3 Method Resolution Order''}{http://www.phyast.pitt.edu/~micheles/mro.html}, or read the thread on python-dev starting with the message at \url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}. --- 1081,1086 ---- To understand the motivation for this change, read Michele Simionato's article ! \ulink{``Python 2.3 Method Resolution Order''} ! {http://www.phyast.pitt.edu/\textasciitilde micheles/mro.html}, or read the thread on python-dev starting with the message at \url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}. *************** *** 1713,1717 **** For more information, refer to the \ulink{module's reference ! documentation}{http://www.python.org/dev/doc/devel/lib/module-datetime.html}. (Contributed by Tim Peters.) --- 1715,1719 ---- For more information, refer to the \ulink{module's reference ! documentation}{..//lib/module-datetime.html}. (Contributed by Tim Peters.) *************** *** 1787,1791 **** \begin{seealso} ! \seeurl{http://optik.sourceforge.net} {The Optik site has tutorial and reference documentation for \module{optparse}. --- 1789,1793 ---- \begin{seealso} ! \seeurl{http://optik.sourceforge.net/} {The Optik site has tutorial and reference documentation for \module{optparse}. *************** *** 1998,2002 **** Other new platforms now supported by Python include AtheOS ! (\url{http://www.atheos.cx}), GNU/Hurd, and OpenVMS. --- 2000,2004 ---- Other new platforms now supported by Python include AtheOS ! (\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS. From gvanrossum@users.sourceforge.net Fri Feb 7 14:59:17 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 06:59:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.177,1.178 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25256 Modified Files: test_descr.py Log Message: Add __getnewargs__ method to classes that need it. (Yes, this is an incompatibility. I'll document it in PEP 307.) Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.177 retrieving revision 1.178 diff -C2 -d -r1.177 -r1.178 *** test_descr.py 13 Jan 2003 20:13:09 -0000 1.177 --- test_descr.py 7 Feb 2003 14:59:13 -0000 1.178 *************** *** 2699,2702 **** --- 2699,2704 ---- def __new__(cls, a, b): return super(C1, cls).__new__(cls) + def __getnewargs__(self): + return (self.a, self.b) def __init__(self, a, b): self.a = a *************** *** 2709,2712 **** --- 2711,2716 ---- def __new__(cls, a, b, val=0): return super(C2, cls).__new__(cls, val) + def __getnewargs__(self): + return (self.a, self.b, int(self)) def __init__(self, a, b, val=0): self.a = a From jackjansen@users.sourceforge.net Fri Feb 7 15:45:44 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 07 Feb 2003 07:45:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac EasyDialogs.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv15762 Modified Files: EasyDialogs.py Log Message: Made AskFile* dialogs movable-modal by default, by providing a dummy eventProc (which simply drops all events on the floor). Also added a method SetDefaultEventProc through which frameworks can set a global event handler (which can still be overridden on a per-call basis with the eventProc argument). Index: EasyDialogs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/EasyDialogs.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** EasyDialogs.py 26 Jan 2003 20:22:18 -0000 1.7 --- EasyDialogs.py 7 Feb 2003 15:45:40 -0000 1.8 *************** *** 592,596 **** --- 592,612 ---- return args, tpwanted + def _dummy_Nav_eventproc(msg, data): + pass + + _default_Nav_eventproc = _dummy_Nav_eventproc + + def SetDefaultEventProc(proc): + global _default_Nav_eventproc + rv = _default_Nav_eventproc + if proc is None: + proc = _dummy_Nav_eventproc + _default_Nav_eventproc = proc + return rv + def AskFileForOpen( + message=None, + typeList=None, + # From here on the order is not documented version=None, defaultLocation=None, *************** *** 601,611 **** actionButtonLabel=None, cancelButtonLabel=None, - message=None, preferenceKey=None, popupExtension=None, ! eventProc=None, previewProc=None, filterProc=None, - typeList=None, wanted=None, multiple=None): --- 617,625 ---- actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, ! eventProc=_dummy_Nav_eventproc, previewProc=None, filterProc=None, wanted=None, multiple=None): *************** *** 643,646 **** --- 657,663 ---- def AskFileForSave( + message=None, + savedFileName=None, + # From here on the order is not documented version=None, defaultLocation=None, *************** *** 651,659 **** actionButtonLabel=None, cancelButtonLabel=None, - savedFileName=None, - message=None, preferenceKey=None, popupExtension=None, ! eventProc=None, fileType=None, fileCreator=None, --- 668,674 ---- actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, ! eventProc=_dummy_Nav_eventproc, fileType=None, fileCreator=None, *************** *** 672,677 **** actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, savedFileName=savedFileName,message=message,preferenceKey=preferenceKey, ! popupExtension=popupExtension,fileType=fileType,fileCreator=fileCreator, ! wanted=wanted,multiple=multiple) try: rr = Nav.NavPutFile(args) --- 687,692 ---- actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, savedFileName=savedFileName,message=message,preferenceKey=preferenceKey, ! popupExtension=popupExtension,eventProc=eventProc,fileType=fileType, ! fileCreator=fileCreator,wanted=wanted,multiple=multiple) try: rr = Nav.NavPutFile(args) *************** *** 704,707 **** --- 719,724 ---- def AskFolder( + message=None, + # From here on the order is not documented version=None, defaultLocation=None, *************** *** 712,719 **** actionButtonLabel=None, cancelButtonLabel=None, - message=None, preferenceKey=None, popupExtension=None, ! eventProc=None, filterProc=None, wanted=None, --- 729,735 ---- actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, ! eventProc=_dummy_Nav_eventproc, filterProc=None, wanted=None, From montanaro@users.sourceforge.net Fri Feb 7 15:55:00 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 07 Feb 2003 07:55:00 -0800 Subject: [Python-checkins] python/dist/src configure,1.279.6.16,1.279.6.17 configure.in,1.288.6.16,1.288.6.17 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv20387 Modified Files: Tag: release22-maint configure configure.in Log Message: backport of a tiny part of patch 557719 - just enough to allow the BUILDEXE Makefile variable to be set properly when doing out-of-tree builds. Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.279.6.16 retrieving revision 1.279.6.17 diff -C2 -d -r1.279.6.16 -r1.279.6.17 *** configure 10 Oct 2002 15:26:41 -0000 1.279.6.16 --- configure 7 Feb 2003 15:54:27 -0000 1.279.6.17 *************** *** 1341,1345 **** echo $ac_n "checking for case-insensitive build directory""... $ac_c" 1>&6 echo "configure:1343: checking for case-insensitive build directory" >&5 ! if test -d "python" then echo "$ac_t""yes" 1>&6 --- 1341,1345 ---- echo $ac_n "checking for case-insensitive build directory""... $ac_c" 1>&6 echo "configure:1343: checking for case-insensitive build directory" >&5 ! if test -d "${srcdir}/python" then echo "$ac_t""yes" 1>&6 Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.288.6.16 retrieving revision 1.288.6.17 diff -C2 -d -r1.288.6.16 -r1.288.6.17 *** configure.in 10 Oct 2002 15:26:46 -0000 1.288.6.16 --- configure.in 7 Feb 2003 15:54:52 -0000 1.288.6.17 *************** *** 210,214 **** AC_SUBST(BUILDEXEEXT) AC_MSG_CHECKING(for case-insensitive build directory) ! if test -d "python" then AC_MSG_RESULT(yes) --- 210,214 ---- AC_SUBST(BUILDEXEEXT) AC_MSG_CHECKING(for case-insensitive build directory) ! if test -d "${srcdir}/python" then AC_MSG_RESULT(yes) From gvanrossum@users.sourceforge.net Fri Feb 7 17:03:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 09:03:35 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,NONE,1.1 pep-0000.txt,1.227,1.228 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv30372 Modified Files: pep-0000.txt Added Files: pep-0308.txt Log Message: Add PEP 308: if-then-else expression proposal. --- NEW FILE: pep-0308.txt --- PEP: 308 Title: If-then-else expression Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/02/07 17:03:31 $ Author: Guido van Rossum Status: Active Type: Standards Track Content-Type: text/plain Created: 7-Feb-2003 Post-History: 7-Feb-2003 Introduction Requests for an if-then-else ("ternary") expression keep coming up on comp.lang.python. This PEP contains a concrete proposal of a fairly Pythonic syntax. This is the community's one chance: if this PEP is approved with a clear majority, it will be implemented in Python 2.4. If not, the PEP will be augmented with a summary of the reasons for rejection and the subject better not come up again. While I am the author of this PEP, I am neither in favor nor against this proposal; it is up to the community to decide. If the community can't decide, I'll reject the PEP. Proposal The proposed syntax is as follows: if else This is evaluated like this: - First, is evaluated. - If is true, is evaluated and is the result of the whole thing. - If is false, is evaluated and is the result of the whole thing. Note that at most one of and is evaluated. This is called a "shortcut expression"; it is similar to the way the second operand of 'and' / 'or' is only evaluated if the first operand is true / false. To disambiguate this in the context of other operators, the "if...else" part in the middle acts like a left-associative binary operator with a priority lower than that of "or", and higher than that of "lambda". Examples of how this works out: x if C else y if D else z <==> x if C else (y if D else z) x or y if C else z <==> (x or y) if C else z x if C else y or z <==> x if C else (y or z) lambda: x if C else y <==> lambda: (x if C else y) x if C else lambda: y <==> SyntaxError x if C else y, z <==> (x if C else y), z x, y if C else z <==> x, (y if C else z) Alternatives Many C-derived languages use this syntax: ? : I reject this for several reasons: the colon already has many uses in Python (even though it would actually not be ambiguous, because the question mark requires a matching colon); for people not used to C-derived language, it is hard to understand. Eric Raymond proposed a variant that doesn't have this problem: ? ! While cute, this suffers from the Perlish problem of using arbitrary punctuation with an arbitrary meaning; and it's no easier to understand than the ?: form. If we could live with adding a new keyword, we could use: if then else Apart from the problem of introducing a new keyword for a minor feature, this also suffers from ambiguity at the start of a statement; for example: if verbose then sys.stdout.write("hello\n") else None could be an syntactically correct expression statement, but starts with 'if', which makes the parser believe it is the start of an 'if' statement. To resolve this, the syntax would have to require parentheses, which makes it uglier. However, this form has the advantage of evaluating strictly from left to right (not that that is a requirement for being Pythonic -- list comprehensions don't). Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.227 retrieving revision 1.228 diff -C2 -d -r1.227 -r1.228 *** pep-0000.txt 31 Jan 2003 19:12:52 -0000 1.227 --- pep-0000.txt 7 Feb 2003 17:03:29 -0000 1.228 *************** *** 110,113 **** --- 110,114 ---- I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters + S 308 If-then-else expression GvR Finished PEPs (done, implemented in CVS) *************** *** 307,310 **** --- 308,312 ---- I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters + S 308 If-then-else expression GvR SR 666 Reject Foolish Indentation Creighton From montanaro@users.sourceforge.net Fri Feb 7 15:59:34 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 07 Feb 2003 07:59:34 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.57,1.337.2.4.2.58 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23979 Modified Files: Tag: release22-maint NEWS Log Message: BUILDEXE setting in out-of-tree builds Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.57 retrieving revision 1.337.2.4.2.58 diff -C2 -d -r1.337.2.4.2.57 -r1.337.2.4.2.58 *** NEWS 28 Jan 2003 19:40:15 -0000 1.337.2.4.2.57 --- NEWS 7 Feb 2003 15:59:28 -0000 1.337.2.4.2.58 *************** *** 66,69 **** --- 66,72 ---- - SF #667147, fix crash when printing str subclass. + - SF #557719, backported just the tiny fragment necessary to get BUILDEXE + set properly in out-of-tree builds. + What's New in Python 2.2.2 (final) ? Release date: 14-Oct-2002 From gvanrossum@users.sourceforge.net Fri Feb 7 17:30:22 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 09:30:22 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv11280 Modified Files: copy.py Log Message: Add support for copy_reg.dispatch_table. Rewrote copy() and deepcopy() without avoidable try/except statements; getattr(x, name, None) or dict.get() are much faster than try/except. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** copy.py 6 Feb 2003 22:57:00 -0000 1.34 --- copy.py 7 Feb 2003 17:30:16 -0000 1.35 *************** *** 49,56 **** """ - # XXX need to support copy_reg here too... - import types ! from copy_reg import _better_reduce class Error(Exception): --- 49,54 ---- """ import types ! from copy_reg import _better_reduce, dispatch_table class Error(Exception): *************** *** 71,93 **** """ ! try: ! copierfunction = _copy_dispatch[type(x)] ! except KeyError: ! try: ! copier = x.__copy__ ! except AttributeError: ! try: ! reductor = x.__class__.__reduce__ ! if reductor == object.__reduce__: ! reductor = _better_reduce ! except AttributeError: ! raise Error("un(shallow)copyable object of type %s" % type(x)) ! else: ! y = _reconstruct(x, reductor(x), 0) ! else: ! y = copier() ! else: ! y = copierfunction(x) ! return y --- 69,91 ---- """ ! cls = type(x) ! ! copier = _copy_dispatch.get(cls) ! if copier: ! return copier(x) ! ! copier = getattr(cls, "__copy__", None) ! if copier: ! return copier(x) ! ! reductor = dispatch_table.get(cls) ! if not reductor: ! reductor = getattr(cls, "__reduce__", None) ! if reductor == object.__reduce__: ! reductor = _better_reduce ! elif not reductor: ! raise Error("un(shallow)copyable object of type %s" % cls) ! ! return _reconstruct(x, reductor(x), 0) *************** *** 154,158 **** del d ! def deepcopy(x, memo = None): """Deep copy operation on arbitrary Python objects. --- 152,156 ---- del d ! def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. *************** *** 162,194 **** if memo is None: memo = {} d = id(x) ! if d in memo: ! return memo[d] ! try: ! copierfunction = _deepcopy_dispatch[type(x)] ! except KeyError: try: ! issc = issubclass(type(x), type) ! except TypeError: issc = 0 if issc: ! y = _deepcopy_dispatch[type](x, memo) else: ! try: ! copier = x.__deepcopy__ ! except AttributeError: ! try: ! reductor = x.__class__.__reduce__ ! if reductor == object.__reduce__: ! reductor = _better_reduce ! except AttributeError: ! raise Error("un(shallow)copyable object of type %s" % ! type(x)) ! else: ! y = _reconstruct(x, reductor(x), 1, memo) ! else: ! y = copier(memo) ! else: ! y = copierfunction(x, memo) memo[d] = y _keep_alive(x, memo) # Make sure x lives at least as long as d --- 160,196 ---- if memo is None: memo = {} + d = id(x) ! y = memo.get(d, _nil) ! if y is not _nil: ! return y ! ! cls = type(x) ! ! copier = _deepcopy_dispatch.get(cls) ! if copier: ! y = copier(x, memo) ! else: try: ! issc = issubclass(cls, type) ! except TypeError: # cls is not a class (old Boost; see SF #502085) issc = 0 if issc: ! copier = _deepcopy_atomic else: ! copier = getattr(cls, "__deepcopy__", None) ! ! if copier: ! y = copier(x, memo) ! else: ! reductor = dispatch_table.get(cls) ! if not reductor: ! reductor = getattr(cls, "__reduce__", None) ! if reductor == object.__reduce__: ! reductor = _better_reduce ! elif not reductor: ! raise Error("un(deep)copyable object of type %s" % cls) ! y = _reconstruct(x, reductor(x), 1, memo) ! memo[d] = y _keep_alive(x, memo) # Make sure x lives at least as long as d *************** *** 381,385 **** for key, value in state.iteritems(): setattr(self, key, value) ! def __deepcopy__(self, memo = None): new = self.__class__(deepcopy(self.arg, memo)) new.a = self.a --- 383,387 ---- for key, value in state.iteritems(): setattr(self, key, value) ! def __deepcopy__(self, memo=None): new = self.__class__(deepcopy(self.arg, memo)) new.a = self.a From gvanrossum@users.sourceforge.net Fri Feb 7 17:30:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 09:30:23 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv11280/test Modified Files: test_copy.py Log Message: Add support for copy_reg.dispatch_table. Rewrote copy() and deepcopy() without avoidable try/except statements; getattr(x, name, None) or dict.get() are much faster than try/except. Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_copy.py 6 Feb 2003 21:25:12 -0000 1.4 --- test_copy.py 7 Feb 2003 17:30:18 -0000 1.5 *************** *** 3,6 **** --- 3,7 ---- import sys import copy + import copy_reg import unittest *************** *** 33,36 **** --- 34,50 ---- self.assertEqual(y.foo, x.foo) + def test_copy_registry(self): + class C(object): + def __new__(cls, foo): + obj = object.__new__(cls) + obj.foo = foo + return obj + def pickle_C(obj): + return (C, (obj.foo,)) + x = C(42) + self.assertRaises(TypeError, copy.copy, x) + copy_reg.pickle(C, pickle_C, C) + y = copy.copy(x) + def test_copy_reduce(self): class C(object): *************** *** 182,185 **** --- 196,212 ---- self.assertEqual(y.__class__, x.__class__) self.assertEqual(y.foo, x.foo) + + def test_deepcopy_registry(self): + class C(object): + def __new__(cls, foo): + obj = object.__new__(cls) + obj.foo = foo + return obj + def pickle_C(obj): + return (C, (obj.foo,)) + x = C(42) + self.assertRaises(TypeError, copy.deepcopy, x) + copy_reg.pickle(C, pickle_C, C) + y = copy.deepcopy(x) def test_deepcopy_reduce(self): From gvanrossum@users.sourceforge.net Fri Feb 7 17:53:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 09:53:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv27206/test Modified Files: test_copy.py Log Message: Somehow, copy() of a classic class object was handled atomically, but deepcopy() didn't support this at all. I don't see any reason for this, so I'm adding ClassType to the set of types that are deep-copied atomically. Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_copy.py 7 Feb 2003 17:30:18 -0000 1.5 --- test_copy.py 7 Feb 2003 17:53:23 -0000 1.6 *************** *** 240,244 **** tests = [None, 42, 2L**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, ! NewStyle, xrange(10)] for x in tests: self.assert_(copy.deepcopy(x) is x, `x`) --- 240,244 ---- tests = [None, 42, 2L**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, ! NewStyle, xrange(10), Classic] for x in tests: self.assert_(copy.deepcopy(x) is x, `x`) From gvanrossum@users.sourceforge.net Fri Feb 7 17:53:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 09:53:26 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.35,1.36 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv27206 Modified Files: copy.py Log Message: Somehow, copy() of a classic class object was handled atomically, but deepcopy() didn't support this at all. I don't see any reason for this, so I'm adding ClassType to the set of types that are deep-copied atomically. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** copy.py 7 Feb 2003 17:30:16 -0000 1.35 --- copy.py 7 Feb 2003 17:53:20 -0000 1.36 *************** *** 221,224 **** --- 221,225 ---- d[types.TypeType] = _deepcopy_atomic d[types.XRangeType] = _deepcopy_atomic + d[types.ClassType] = _deepcopy_atomic def _deepcopy_list(x, memo): From gvanrossum@users.sourceforge.net Fri Feb 7 18:11:34 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 10:11:34 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv5765 Modified Files: pep-0307.txt Log Message: Add posting-date. Add note about the copy module. Remove TBD -- this PEP is complete AFAIAC. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** pep-0307.txt 6 Feb 2003 20:38:30 -0000 1.14 --- pep-0307.txt 7 Feb 2003 18:11:29 -0000 1.15 *************** *** 8,12 **** Content-Type: text/plain Created: 31-Jan-2003 ! Post-History: None --- 8,12 ---- Content-Type: text/plain Created: 31-Jan-2003 ! Post-History: 7-Feb-2003 *************** *** 600,606 **** ! TBD ! The rest of this PEP is still under construction! --- 600,646 ---- ! The copy module ! Traditionally, the copy module has supported an extended subset of ! the pickling APIs for customizing the copy() and deepcopy() ! operations. ! ! In particular, besides checking for a __copy__ or __deepcopy__ ! method, copy() and deepcopy() have always looked for __reduce__, ! and for classic classes, have looked for __getinitargs__, ! __getstate__ and __setstate__. ! ! In Python 2.2, the default __reduce__ inherited from 'object' made ! copying simple new-style classes possible, but slots and various ! other special cases were not covered. ! ! In Python 2.3, several changes are made to the copy module: ! ! - The four- and five-argument return values of __reduce__ are ! supported. ! ! - Before looking for a __reduce__ method, the ! copy_reg.dispatch_table is consulted, just like for pickling. ! ! - When the __reduce__ method is inherited from object, it is ! (unconditionally) replaced by a better one that uses the same ! APIs as pickle protocol 2: __getnewargs__, __getstate__, and ! __setstate__, handling list and dict subclasses, and handling ! slots. ! ! As a consequence of the latter change, certain new-style classes ! that were copyable under Python 2.2 are not copyable under Python ! 2.3. (These classes are also not picklable using pickle protocol ! 2.) A minimal example of such a class: ! ! class C(object): ! def __new__(cls, a): ! return object.__new__(cls) ! ! The problem only occurs when __new__ is overridden and has at ! least one mandatory argument in addition to the class argument. ! ! To fix this, a __getnewargs__ method should be added that returns ! the appropriate argument tuple (excluding the class). From gvanrossum@users.sourceforge.net Fri Feb 7 19:30:20 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 11:30:20 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv10902 Modified Files: pep-0307.txt Log Message: Typo found by Aahz. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** pep-0307.txt 7 Feb 2003 18:11:29 -0000 1.15 --- pep-0307.txt 7 Feb 2003 19:30:15 -0000 1.16 *************** *** 202,206 **** primarily used for dict subclasses, but may be used by other classes as long as they implement ! __settitem__. Note: in Python 2.2 and before, when using cPickle, state would be --- 202,206 ---- primarily used for dict subclasses, but may be used by other classes as long as they implement ! __setitem__. Note: in Python 2.2 and before, when using cPickle, state would be From nnorwitz@users.sourceforge.net Fri Feb 7 19:44:58 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 07 Feb 2003 11:44:58 -0800 Subject: [Python-checkins] python/dist/src/Modules mmapmodule.c,2.42,2.43 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv15924/Modules Modified Files: mmapmodule.c Log Message: SF patch #682514, mmapmodule.c write fix for LP64 executables Make length an int so we get the right value from PyArg_ParseTuple(args, "s#", &str, &length) Will backport. Index: mmapmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/mmapmodule.c,v retrieving revision 2.42 retrieving revision 2.43 diff -C2 -d -r2.42 -r2.43 *** mmapmodule.c 10 Jan 2003 20:52:15 -0000 2.42 --- mmapmodule.c 7 Feb 2003 19:44:56 -0000 2.43 *************** *** 293,297 **** PyObject *args) { ! long length; char *data; --- 293,297 ---- PyObject *args) { ! int length; char *data; From nnorwitz@users.sourceforge.net Fri Feb 7 19:46:47 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 07 Feb 2003 11:46:47 -0800 Subject: [Python-checkins] python/dist/src/Modules mmapmodule.c,2.35.6.4,2.35.6.5 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv17096/Modules Modified Files: Tag: release22-maint mmapmodule.c Log Message: SF patch #682514, mmapmodule.c write fix for LP64 executables Make length an int so we get the right value from PyArg_ParseTuple(args, "s#", &str, &length) Index: mmapmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/mmapmodule.c,v retrieving revision 2.35.6.4 retrieving revision 2.35.6.5 diff -C2 -d -r2.35.6.4 -r2.35.6.5 *** mmapmodule.c 10 Jan 2003 21:02:40 -0000 2.35.6.4 --- mmapmodule.c 7 Feb 2003 19:46:44 -0000 2.35.6.5 *************** *** 293,297 **** PyObject *args) { ! long length; char *data; --- 293,297 ---- PyObject *args) { ! int length; char *data; From akuchling@users.sourceforge.net Fri Feb 7 20:22:36 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:22:36 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.114,1.115 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv1669 Modified Files: whatsnew23.tex Log Message: Update URL Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.114 retrieving revision 1.115 diff -C2 -d -r1.114 -r1.115 *** whatsnew23.tex 7 Feb 2003 14:52:18 -0000 1.114 --- whatsnew23.tex 7 Feb 2003 20:22:33 -0000 1.115 *************** *** 1082,1086 **** read Michele Simionato's article \ulink{``Python 2.3 Method Resolution Order''} ! {http://www.phyast.pitt.edu/\textasciitilde micheles/mro.html}, or read the thread on python-dev starting with the message at \url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}. --- 1082,1086 ---- read Michele Simionato's article \ulink{``Python 2.3 Method Resolution Order''} ! {http://www.python.org/2.3/mro.html}, or read the thread on python-dev starting with the message at \url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}. From montanaro@users.sourceforge.net Fri Feb 7 20:18:50 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:18:50 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv31913 Modified Files: pep-0308.txt Log Message: explain why adding a new builtin won't work. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pep-0308.txt 7 Feb 2003 17:03:31 -0000 1.1 --- pep-0308.txt 7 Feb 2003 20:18:45 -0000 1.2 *************** *** 99,102 **** --- 99,111 ---- is a requirement for being Pythonic -- list comprehensions don't). + Many people suggest adding a new builtin instead of extending the + syntax of the language, e.g.: + + ifelse(condition, expression1, expression2) + + This won't work the way a syntax extension will because both + expression1 and expression2 must be evaluated before the function + is called. There's no way to short-circuit the expression + evaluation. Copyright From tim_one@users.sourceforge.net Fri Feb 7 20:48:05 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:48:05 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.157,1.158 test_datetime.py,1.112,1.113 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv10667 Modified Files: datetime.py test_datetime.py Log Message: Comparison for timedelta, time, date and datetime objects: rewrote to use rich comparisons. __eq__ and __ne__ no longer complain if they don't know how to compare to the other thing. If no meaningful way to compare is known, saying "not equal" is sensible. This allows things like if adatetime in some_sequence: and somedict[adatetime] = whatever to work as expected even if some_sequence contains non-datetime objects, or somedict non-datetime keys, because they only call __eq__. It still complains (raises TypeError) for mixed-type comparisons in contexts that require a total ordering, such as list.sort(), use as a key in a BTree-based data structure, and cmp(). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.157 retrieving revision 1.158 diff -C2 -d -r1.157 -r1.158 *** datetime.py 1 Feb 2003 03:02:33 -0000 1.157 --- datetime.py 7 Feb 2003 20:47:58 -0000 1.158 *************** *** 287,290 **** --- 287,318 ---- raise TypeError("tzinfo argument must be None or of a tzinfo subclass") + + # Notes on comparison: In general, datetime module comparison operators raise + # TypeError when they don't know how to do a comparison themself. If they + # returned NotImplemented instead, comparison could (silently) fall back to + # the default compare-objects-by-comparing-their-memory-addresses strategy, + # and that's not helpful. There are two exceptions: + # + # 1. For date and datetime, if the other object has a "timetuple" attr, + # NotImplemented is returned. This is a hook to allow other kinds of + # datetime-like objects a chance to intercept the comparison. + # + # 2. Else __eq__ and __ne__ return False and True, respectively. This is + # so opertaions like + # + # x == y + # x != y + # x in sequence + # x not in sequence + # dict[x] = y + # + # don't raise annoying TypeErrors just because a datetime object + # is part of a heterogeneous collection. If there's no known way to + # compare X to a datetime, saying they're not equal is reasonable. + + def _cmperror(x, y): + raise TypeError("can't compare '%s' to '%s'" % ( + type(x).__name__, type(y).__name__)) + # This is a start at a struct tm workalike. Goals: # *************** *** 597,604 **** __floordiv__ = __div__ ! def __cmp__(self, other): ! if not isinstance(other, timedelta): ! raise TypeError, ("can't compare timedelta to %s instance" % ! type(other).__name__) return cmp(self.__getstate(), other.__getstate()) --- 625,668 ---- __floordiv__ = __div__ ! # Comparisons. ! ! def __eq__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) == 0 ! else: ! return False ! ! def __ne__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) != 0 ! else: ! return True ! ! def __le__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) <= 0 ! else: ! _cmperror(self, other) ! ! def __lt__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) < 0 ! else: ! _cmperror(self, other) ! ! def __ge__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) >= 0 ! else: ! _cmperror(self, other) ! ! def __gt__(self, other): ! if isinstance(other, timedelta): ! return self.__cmp(other) > 0 ! else: ! _cmperror(self, other) ! ! def __cmp(self, other): ! assert isinstance(other, timedelta) return cmp(self.__getstate(), other.__getstate()) *************** *** 764,778 **** return date(year, month, day) ! def __cmp__(self, other): ! "Three-way comparison." if isinstance(other, date): ! y, m, d = self.__year, self.__month, self.__day ! y2, m2, d2 = other.__year, other.__month, other.__day ! return cmp((y, m, d), (y2, m2, d2)) elif hasattr(other, "timetuple"): return NotImplemented else: ! raise TypeError, ("can't compare date to %s instance" % ! type(other).__name__) def __hash__(self): --- 828,886 ---- return date(year, month, day) ! # Comparisons. ! ! def __eq__(self, other): if isinstance(other, date): ! return self.__cmp(other) == 0 elif hasattr(other, "timetuple"): return NotImplemented else: ! return False ! ! def __ne__(self, other): ! if isinstance(other, date): ! return self.__cmp(other) != 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! return True ! ! def __le__(self, other): ! if isinstance(other, date): ! return self.__cmp(other) <= 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __lt__(self, other): ! if isinstance(other, date): ! return self.__cmp(other) < 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __ge__(self, other): ! if isinstance(other, date): ! return self.__cmp(other) >= 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __gt__(self, other): ! if isinstance(other, date): ! return self.__cmp(other) > 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __cmp(self, other): ! assert isinstance(other, date) ! y, m, d = self.__year, self.__month, self.__day ! y2, m2, d2 = other.__year, other.__month, other.__day ! return cmp((y, m, d), (y2, m2, d2)) def __hash__(self): *************** *** 1004,1013 **** # Standard conversions, __hash__ (and helpers) ! def __cmp__(self, other): ! """Three-way comparison.""" ! if not isinstance(other, time): ! # XXX Buggy in 2.2.2. ! raise TypeError("can't compare '%s' to '%s'" % ( ! type(self).__name__, type(other).__name__)) mytz = self._tzinfo ottz = other._tzinfo --- 1112,1155 ---- # Standard conversions, __hash__ (and helpers) ! # Comparisons. ! ! def __eq__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) == 0 ! else: ! return False ! ! def __ne__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) != 0 ! else: ! return True ! ! def __le__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) <= 0 ! else: ! _cmperror(self, other) ! ! def __lt__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) < 0 ! else: ! _cmperror(self, other) ! ! def __ge__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) >= 0 ! else: ! _cmperror(self, other) ! ! def __gt__(self, other): ! if isinstance(other, time): ! return self.__cmp(other) > 0 ! else: ! _cmperror(self, other) ! ! def __cmp(self, other): ! assert isinstance(other, time) mytz = self._tzinfo ottz = other._tzinfo *************** *** 1478,1489 **** return offset ! def __cmp__(self, other): ! if not isinstance(other, datetime): ! if hasattr(other, "timetuple"): ! return NotImplemented ! else: ! # XXX Buggy in 2.2.2. ! raise TypeError("can't compare '%s' to '%s'" % ( ! type(self).__name__, type(other).__name__)) mytz = self._tzinfo ottz = other._tzinfo --- 1620,1675 ---- return offset ! # Comparisons. ! ! def __eq__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) == 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! return False ! ! def __ne__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) != 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! return True ! ! def __le__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) <= 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __lt__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) < 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __ge__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) >= 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __gt__(self, other): ! if isinstance(other, datetime): ! return self.__cmp(other) > 0 ! elif hasattr(other, "timetuple"): ! return NotImplemented ! else: ! _cmperror(self, other) ! ! def __cmp(self, other): ! assert isinstance(other, datetime) mytz = self._tzinfo ottz = other._tzinfo Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** test_datetime.py 6 Feb 2003 16:32:31 -0000 1.112 --- test_datetime.py 7 Feb 2003 20:47:59 -0000 1.113 *************** *** 135,141 **** ############################################################################# # timedelta tests ! class TestTimeDelta(unittest.TestCase): def test_constructor(self): --- 135,183 ---- ############################################################################# + # Base clase for testing a particular aspect of timedelta, time, date and + # datetime comparisons. + + class HarmlessMixedComparison(unittest.TestCase): + # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. + + # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a + # legit constructor. + + def test_harmless_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.failIf(me == ()) + self.failUnless(me != ()) + self.failIf(() == me) + self.failUnless(() != me) + + self.failUnless(me in [1, 20L, [], me]) + self.failIf(me not in [1, 20L, [], me]) + + self.failUnless([] in [me, 1, 20L, []]) + self.failIf([] not in [me, 1, 20L, []]) + + def test_harmful_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.assertRaises(TypeError, lambda: me < ()) + self.assertRaises(TypeError, lambda: me <= ()) + self.assertRaises(TypeError, lambda: me > ()) + self.assertRaises(TypeError, lambda: me >= ()) + + self.assertRaises(TypeError, lambda: () < me) + self.assertRaises(TypeError, lambda: () <= me) + self.assertRaises(TypeError, lambda: () > me) + self.assertRaises(TypeError, lambda: () >= me) + + self.assertRaises(TypeError, cmp, (), me) + self.assertRaises(TypeError, cmp, me, ()) + + ############################################################################# # timedelta tests ! class TestTimeDelta(HarmlessMixedComparison): ! ! theclass = timedelta def test_constructor(self): *************** *** 302,314 **** self.assertEqual(cmp(t2, t1), 1) ! for badarg in 10, 10L, 34.5, "abc", {}, [], (): ! self.assertRaises(TypeError, lambda: t1 == badarg) ! self.assertRaises(TypeError, lambda: t1 != badarg) self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 344,359 ---- self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: ! self.assertEqual(t1 == badarg, False) ! self.assertEqual(t1 != badarg, True) ! self.assertEqual(badarg == t1, False) ! self.assertEqual(badarg != t1, True) ! ! for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) *************** *** 447,451 **** self.assertEqual(dt2, dt - days) ! class TestDate(unittest.TestCase): # Tests here should pass for both dates and datetimes, except for a # few tests that TestDateTime overrides. --- 492,496 ---- self.assertEqual(dt2, dt - days) ! class TestDate(HarmlessMixedComparison): # Tests here should pass for both dates and datetimes, except for a # few tests that TestDateTime overrides. *************** *** 854,866 **** self.assertEqual(cmp(t2, t1), 1) ! for badarg in 10, 10L, 34.5, "abc", {}, [], (): ! self.assertRaises(TypeError, lambda: t1 == badarg) ! self.assertRaises(TypeError, lambda: t1 != badarg) ! self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 899,913 ---- self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: ! self.assertEqual(t1 == badarg, False) ! self.assertEqual(t1 != badarg, True) ! self.assertEqual(badarg == t1, False) ! self.assertEqual(badarg != t1, True) ! ! for badarg in badargs: self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) *************** *** 1354,1358 **** self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive ! class TestTime(unittest.TestCase): theclass = time --- 1401,1405 ---- self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive ! class TestTime(HarmlessMixedComparison): theclass = time *************** *** 1424,1436 **** if CMP_BUG_FIXED: badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) for badarg in badargs: - self.assertRaises(TypeError, lambda: t1 == badarg) - self.assertRaises(TypeError, lambda: t1 != badarg) self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 1471,1486 ---- if CMP_BUG_FIXED: badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) + + for badarg in badargs: + self.assertEqual(t1 == badarg, False) + self.assertEqual(t1 != badarg, True) + self.assertEqual(badarg == t1, False) + self.assertEqual(badarg != t1, True) + for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) From nnorwitz@users.sourceforge.net Fri Feb 7 20:49:44 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:49:44 -0800 Subject: [Python-checkins] python/dist/src/Lib pydoc.py,1.75,1.76 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv13234/Lib Modified Files: pydoc.py Log Message: Fix SF bug #642168, help() fails for some builtin topics Fix pydoc when doing help for: and, or, not, UNICODE. Will backport. Index: pydoc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pydoc.py,v retrieving revision 1.75 retrieving revision 1.76 diff -C2 -d -r1.75 -r1.76 *** pydoc.py 7 Feb 2003 01:53:46 -0000 1.75 --- pydoc.py 7 Feb 2003 20:49:40 -0000 1.76 *************** *** 1415,1419 **** 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'), ! 'UNICODE': ('ref/unicode', 'encodings unicode TYPES STRING'), 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('ref/integers', 'int range'), --- 1415,1419 ---- 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'), ! 'UNICODE': ('ref/strings', 'encodings unicode TYPES STRING'), 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('ref/integers', 'int range'), *************** *** 1475,1479 **** 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'), 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'), ! 'BOOLEAN': ('ref/lambda', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'), --- 1475,1479 ---- 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'), 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'), ! 'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'), From nnorwitz@users.sourceforge.net Fri Feb 7 20:51:24 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:51:24 -0800 Subject: [Python-checkins] python/dist/src/Lib pydoc.py,1.56.8.7,1.56.8.8 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv14257/Lib Modified Files: Tag: release22-maint pydoc.py Log Message: Fix SF bug #642168, help() fails for some builtin topics Fix pydoc when doing help for: and, or, not, UNICODE. Index: pydoc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pydoc.py,v retrieving revision 1.56.8.7 retrieving revision 1.56.8.8 diff -C2 -d -r1.56.8.7 -r1.56.8.8 *** pydoc.py 7 Nov 2002 00:28:54 -0000 1.56.8.7 --- pydoc.py 7 Feb 2003 20:51:20 -0000 1.56.8.8 *************** *** 1413,1417 **** 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'), ! 'UNICODE': ('ref/unicode', 'encodings unicode TYPES STRING'), 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('ref/integers', 'int range'), --- 1413,1417 ---- 'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'), ! 'UNICODE': ('ref/strings', 'encodings unicode TYPES STRING'), 'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('ref/integers', 'int range'), *************** *** 1473,1477 **** 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'), 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'), ! 'BOOLEAN': ('ref/lambda', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'), --- 1473,1477 ---- 'BITWISE': ('ref/bitwise', 'EXPRESSIONS'), 'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'), ! 'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'), From gvanrossum@users.sourceforge.net Fri Feb 7 20:56:43 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:56:43 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv18939 Modified Files: copy_reg.py Log Message: Reserve a range for Zope, not specifically for Zope 3. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** copy_reg.py 6 Feb 2003 22:57:00 -0000 1.17 --- copy_reg.py 7 Feb 2003 20:56:38 -0000 1.18 *************** *** 202,206 **** # First Last Count Purpose # 1 127 127 Reserved for Python standard library ! # 128 191 64 Reserved for Zope 3 # 192 239 48 Reserved for 3rd parties # 240 255 16 Reserved for private use (will never be assigned) --- 202,206 ---- # First Last Count Purpose # 1 127 127 Reserved for Python standard library ! # 128 191 64 Reserved for Zope # 192 239 48 Reserved for 3rd parties # 240 255 16 Reserved for private use (will never be assigned) From gvanrossum@users.sourceforge.net Fri Feb 7 20:57:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 12:57:56 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv19481 Modified Files: pep-0307.txt Log Message: Reserve a range for Zope, not specifically for Zope 3. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** pep-0307.txt 7 Feb 2003 19:30:15 -0000 1.16 --- pep-0307.txt 7 Feb 2003 20:57:23 -0000 1.17 *************** *** 558,562 **** 0 0 1 Reserved -- will never be used 1 127 127 Reserved for Python standard library ! 128 191 64 Reserved for Zope 3 192 239 48 Reserved for 3rd parties 240 255 16 Reserved for private use (will never be assigned) --- 558,562 ---- 0 0 1 Reserved -- will never be used 1 127 127 Reserved for Python standard library ! 128 191 64 Reserved for Zope 192 239 48 Reserved for 3rd parties 240 255 16 Reserved for private use (will never be assigned) From gvanrossum@users.sourceforge.net Fri Feb 7 21:40:40 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 13:40:40 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.158,1.159 test_datetime.py,1.113,1.114 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv9646 Modified Files: datetime.py test_datetime.py Log Message: Tres discovered a weird bug when a datetime is pickled, caused by the shadowing of __year, __month, __day and the use of proxies. Here's a quick fix and a quick unit test. I don't quite understand why this wasn't caught by the pickling unit tests. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.158 retrieving revision 1.159 diff -C2 -d -r1.158 -r1.159 *** datetime.py 7 Feb 2003 20:47:58 -0000 1.158 --- datetime.py 7 Feb 2003 21:40:34 -0000 1.159 *************** *** 1360,1364 **** if isinstance(year, str): # Pickle support ! self = date.__new__(cls, 1, 1, 1) self.__setstate((year, month)) return self --- 1360,1364 ---- if isinstance(year, str): # Pickle support ! self = date.__new__(cls, year[:4]) self.__setstate((year, month)) return self Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.113 retrieving revision 1.114 diff -C2 -d -r1.113 -r1.114 *** test_datetime.py 7 Feb 2003 20:47:59 -0000 1.113 --- test_datetime.py 7 Feb 2003 21:40:36 -0000 1.114 *************** *** 1224,1227 **** --- 1224,1235 ---- self.assertEqual(orig, derived) + def test_more_pickling(self): + a = self.theclass(2003, 2, 7, 16, 48, 37, 444116) + s = pickle.dumps(a) + b = pickle.loads(s) + self.assertEqual(b.year, 2003) + self.assertEqual(b.month, 2) + self.assertEqual(b.day, 7) + def test_more_compare(self): # The test_compare() inherited from TestDate covers the error cases. From gvanrossum@users.sourceforge.net Fri Feb 7 22:13:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:13:56 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28169 Modified Files: pep-0308.txt Log Message: Credit where credit is due. Also add an extra blank line before the section on ifelse(). Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** pep-0308.txt 7 Feb 2003 20:18:45 -0000 1.2 --- pep-0308.txt 7 Feb 2003 22:13:53 -0000 1.3 *************** *** 73,77 **** ! Eric Raymond proposed a variant that doesn't have this problem: ? ! --- 73,78 ---- ! David Ascher proposed, and Eric Raymond even implemented, a ! variant that doesn't have this problem: ? ! *************** *** 98,101 **** --- 99,103 ---- advantage of evaluating strictly from left to right (not that that is a requirement for being Pythonic -- list comprehensions don't). + Many people suggest adding a new builtin instead of extending the From gvanrossum@users.sourceforge.net Fri Feb 7 22:29:41 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:29:41 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv4190 Modified Files: pep-0308.txt Log Message: Explain that "e if C" (without the "else" part) is a bad idea. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** pep-0308.txt 7 Feb 2003 22:13:53 -0000 1.3 --- pep-0308.txt 7 Feb 2003 22:29:39 -0000 1.4 *************** *** 111,114 **** --- 111,126 ---- evaluation. + + Variations + + It has been proposed to make the 'else' part optional. This would + be a really bad idea. I showed: + + x = e if C + + to several people and they all thought that if C was false, it + would leave x unchanged. So don't even think about this one! + + Copyright From gvanrossum@users.sourceforge.net Fri Feb 7 22:34:58 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:34:58 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv6424 Modified Files: pep-0308.txt Log Message: Add if C : e1 else e2. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** pep-0308.txt 7 Feb 2003 22:29:39 -0000 1.4 --- pep-0308.txt 7 Feb 2003 22:34:54 -0000 1.5 *************** *** 72,75 **** --- 72,76 ---- to C-derived language, it is hard to understand. + --- David Ascher proposed, and Eric Raymond even implemented, a *************** *** 82,85 **** --- 83,87 ---- easier to understand than the ?: form. + --- If we could live with adding a new keyword, we could use: *************** *** 100,103 **** --- 102,126 ---- is a requirement for being Pythonic -- list comprehensions don't). + --- + + To deal with the problem of adding a new keyword, this variant has + been proposed: + + if : else + + This has the same ambiguity problem as the previous one (I would + even say more so), and lacks symmetry. It also begs the question + why there isn't a colon after the 'else'. But this: + + if : else: + + is even more confusing because it resembles the if statement so + much. (A solution that *doesn't* resemble the if statement is + better IMO since it should be obvious at first glance whether + we're dealing with an if expression or with an if statement. + Placing the 'if' in the middle somehow satisfies this + requirement.) + + --- Many people suggest adding a new builtin instead of extending the From tim_one@users.sourceforge.net Fri Feb 7 22:50:28 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:50:28 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libdatetime.tex,1.43,1.44 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv12260/python/Doc/lib Modified Files: libdatetime.tex Log Message: Comparison for timedelta, time, date and datetime objects: __eq__ and __ne__ no longer complain if they don't know how to compare to the other thing. If no meaningful way to compare is known, saying "not equal" is sensible. This allows things like if adatetime in some_sequence: and somedict[adatetime] = whatever to work as expected even if some_sequence contains non-datetime objects, or somedict non-datetime keys, because they only call __eq__. It still complains (raises TypeError) for mixed-type comparisons in contexts that require a total ordering, such as list.sort(), use as a key in a BTree-based data structure, and cmp(). Index: libdatetime.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libdatetime.tex,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** libdatetime.tex 5 Feb 2003 21:15:38 -0000 1.43 --- libdatetime.tex 7 Feb 2003 22:50:26 -0000 1.44 *************** *** 258,261 **** --- 258,266 ---- \class{timedelta} object representing the smaller duration considered to be the smaller timedelta. + In order to stop mixed-type comparisons from falling back to the + default comparison by object address, when a \class{timedelta} object is + compared to an object of a different type, \exception{TypeError} is + raised unless the comparison is \code{==} or \code{!=}. The latter + cases return \constant{False} or \constant{True}, respectively. \class{timedelta} objects are hashable (usable as dictionary keys), *************** *** 403,406 **** --- 408,415 ---- \method{timetuple} attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. + If not, when a \class{date} object is + compared to an object of a different type, \exception{TypeError} is + raised unless the comparison is \code{==} or \code{!=}. The latter + cases return \constant{False} or \constant{True}, respectively. \end{description} *************** *** 744,748 **** has a \method{timetuple} attribute. This hook gives other kinds of date objects a chance at implementing mixed-type ! comparison.} \end{description} --- 753,761 ---- has a \method{timetuple} attribute. This hook gives other kinds of date objects a chance at implementing mixed-type ! comparison. If not, when a \class{datetime} object is ! compared to an object of a different type, \exception{TypeError} ! is raised unless the comparison is \code{==} or \code{!=}. The ! latter cases return \constant{False} or \constant{True}, ! respectively.} \end{description} *************** *** 1024,1027 **** --- 1037,1045 ---- the comparands are first adjusted by subtracting their UTC offsets (obtained from \code{self.utcoffset()}). + In order to stop mixed-type comparisons from falling back to the + default comparison by object address, when a \class{time} object is + compared to an object of a different type, \exception{TypeError} is + raised unless the comparison is \code{==} or \code{!=}. The latter + cases return \constant{False} or \constant{True}, respectively. \item From tim_one@users.sourceforge.net Fri Feb 7 22:50:29 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:50:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12260/python/Lib/test Modified Files: test_datetime.py Log Message: Comparison for timedelta, time, date and datetime objects: __eq__ and __ne__ no longer complain if they don't know how to compare to the other thing. If no meaningful way to compare is known, saying "not equal" is sensible. This allows things like if adatetime in some_sequence: and somedict[adatetime] = whatever to work as expected even if some_sequence contains non-datetime objects, or somedict non-datetime keys, because they only call __eq__. It still complains (raises TypeError) for mixed-type comparisons in contexts that require a total ordering, such as list.sort(), use as a key in a BTree-based data structure, and cmp(). Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** test_datetime.py 7 Feb 2003 21:49:01 -0000 1.37 --- test_datetime.py 7 Feb 2003 22:50:26 -0000 1.38 *************** *** 135,141 **** ############################################################################# # timedelta tests ! class TestTimeDelta(unittest.TestCase): def test_constructor(self): --- 135,183 ---- ############################################################################# + # Base clase for testing a particular aspect of timedelta, time, date and + # datetime comparisons. + + class HarmlessMixedComparison(unittest.TestCase): + # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. + + # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a + # legit constructor. + + def test_harmless_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.failIf(me == ()) + self.failUnless(me != ()) + self.failIf(() == me) + self.failUnless(() != me) + + self.failUnless(me in [1, 20L, [], me]) + self.failIf(me not in [1, 20L, [], me]) + + self.failUnless([] in [me, 1, 20L, []]) + self.failIf([] not in [me, 1, 20L, []]) + + def test_harmful_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.assertRaises(TypeError, lambda: me < ()) + self.assertRaises(TypeError, lambda: me <= ()) + self.assertRaises(TypeError, lambda: me > ()) + self.assertRaises(TypeError, lambda: me >= ()) + + self.assertRaises(TypeError, lambda: () < me) + self.assertRaises(TypeError, lambda: () <= me) + self.assertRaises(TypeError, lambda: () > me) + self.assertRaises(TypeError, lambda: () >= me) + + self.assertRaises(TypeError, cmp, (), me) + self.assertRaises(TypeError, cmp, me, ()) + + ############################################################################# # timedelta tests ! class TestTimeDelta(HarmlessMixedComparison): ! ! theclass = timedelta def test_constructor(self): *************** *** 302,314 **** self.assertEqual(cmp(t2, t1), 1) ! for badarg in 10, 10L, 34.5, "abc", {}, [], (): ! self.assertRaises(TypeError, lambda: t1 == badarg) ! self.assertRaises(TypeError, lambda: t1 != badarg) self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 344,359 ---- self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: ! self.assertEqual(t1 == badarg, False) ! self.assertEqual(t1 != badarg, True) ! self.assertEqual(badarg == t1, False) ! self.assertEqual(badarg != t1, True) ! ! for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) *************** *** 447,451 **** self.assertEqual(dt2, dt - days) ! class TestDate(unittest.TestCase): # Tests here should pass for both dates and datetimes, except for a # few tests that TestDateTime overrides. --- 492,496 ---- self.assertEqual(dt2, dt - days) ! class TestDate(HarmlessMixedComparison): # Tests here should pass for both dates and datetimes, except for a # few tests that TestDateTime overrides. *************** *** 854,866 **** self.assertEqual(cmp(t2, t1), 1) ! for badarg in 10, 10L, 34.5, "abc", {}, [], (): ! self.assertRaises(TypeError, lambda: t1 == badarg) ! self.assertRaises(TypeError, lambda: t1 != badarg) ! self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 899,913 ---- self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: ! self.assertEqual(t1 == badarg, False) ! self.assertEqual(t1 != badarg, True) ! self.assertEqual(badarg == t1, False) ! self.assertEqual(badarg != t1, True) ! ! for badarg in badargs: self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) *************** *** 1362,1366 **** self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive ! class TestTime(unittest.TestCase): theclass = time --- 1409,1413 ---- self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive ! class TestTime(HarmlessMixedComparison): theclass = time *************** *** 1432,1444 **** if CMP_BUG_FIXED: badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) for badarg in badargs: - self.assertRaises(TypeError, lambda: t1 == badarg) - self.assertRaises(TypeError, lambda: t1 != badarg) self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) - self.assertRaises(TypeError, lambda: badarg == t1) - self.assertRaises(TypeError, lambda: badarg != t1) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) --- 1479,1494 ---- if CMP_BUG_FIXED: badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) + + for badarg in badargs: + self.assertEqual(t1 == badarg, False) + self.assertEqual(t1 != badarg, True) + self.assertEqual(badarg == t1, False) + self.assertEqual(badarg != t1, True) + for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) self.assertRaises(TypeError, lambda: t1 >= badarg) self.assertRaises(TypeError, lambda: badarg <= t1) self.assertRaises(TypeError, lambda: badarg < t1) From tim_one@users.sourceforge.net Fri Feb 7 22:50:30 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:50:30 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.645,1.646 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv12260/python/Misc Modified Files: NEWS Log Message: Comparison for timedelta, time, date and datetime objects: __eq__ and __ne__ no longer complain if they don't know how to compare to the other thing. If no meaningful way to compare is known, saying "not equal" is sensible. This allows things like if adatetime in some_sequence: and somedict[adatetime] = whatever to work as expected even if some_sequence contains non-datetime objects, or somedict non-datetime keys, because they only call __eq__. It still complains (raises TypeError) for mixed-type comparisons in contexts that require a total ordering, such as list.sort(), use as a key in a BTree-based data structure, and cmp(). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.645 retrieving revision 1.646 diff -C2 -d -r1.645 -r1.646 *** NEWS 6 Feb 2003 23:10:45 -0000 1.645 --- NEWS 7 Feb 2003 22:50:27 -0000 1.646 *************** *** 141,144 **** --- 141,159 ---- comparison. + date, time, datetime and timedelta comparison: When the exception + for mixed-type comparisons in the last paragraph doesn't apply, if + the comparison is == then False is returned, and if the comparison is + != then True is returned. Because dict lookup and the "in" operator + only invoke __eq__, this allows, for example, + + if some_datetime in some_sequence: + and + some_dict[some_timedelta] = whatever + + to work as expected, without raising TypeError just because the + sequence is heterogeneous, or the dict has mixed-type keys. [This + seems like a good idea to implement for all mixed-type comparisons + that don't want to allow falling back to address comparison.] + The constructors building a datetime from a timestamp could raise ValueError if the platform C localtime()/gmtime() inserted "leap *************** *** 272,276 **** - There are new dialogs EasyDialogs.AskFileForOpen, AskFileForSave and AskFolder. The old macfs.StandardGetFile and friends are deprecated. ! - Most of the standard library now uses pathnames or FSRefs in preference of FSSpecs, and use the underlying Carbon.File and Carbon.Folder modules --- 287,291 ---- - There are new dialogs EasyDialogs.AskFileForOpen, AskFileForSave and AskFolder. The old macfs.StandardGetFile and friends are deprecated. ! - Most of the standard library now uses pathnames or FSRefs in preference of FSSpecs, and use the underlying Carbon.File and Carbon.Folder modules From tim_one@users.sourceforge.net Fri Feb 7 22:50:30 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 14:50:30 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.57,1.58 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv12260/python/Modules Modified Files: datetimemodule.c Log Message: Comparison for timedelta, time, date and datetime objects: __eq__ and __ne__ no longer complain if they don't know how to compare to the other thing. If no meaningful way to compare is known, saying "not equal" is sensible. This allows things like if adatetime in some_sequence: and somedict[adatetime] = whatever to work as expected even if some_sequence contains non-datetime objects, or somedict non-datetime keys, because they only call __eq__. It still complains (raises TypeError) for mixed-type comparisons in contexts that require a total ordering, such as list.sort(), use as a key in a BTree-based data structure, and cmp(). Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** datetimemodule.c 4 Feb 2003 20:45:17 -0000 1.57 --- datetimemodule.c 7 Feb 2003 22:50:28 -0000 1.58 *************** *** 1225,1228 **** --- 1225,1238 ---- } + /* Raises a "can't compare" TypeError and returns NULL. */ + static PyObject * + cmperror(PyObject *a, PyObject *b) + { + PyErr_Format(PyExc_TypeError, + "can't compare %s to %s", + a->ob_type->tp_name, b->ob_type->tp_name); + return NULL; + } + /* --------------------------------------------------------------------------- * Basic object allocation. These allocate Python objects of the right *************** *** 1655,1673 **** delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op) { ! int diff; ! if (! PyDelta_CheckExact(other)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare %s to %s instance", ! self->ob_type->tp_name, other->ob_type->tp_name); ! return NULL; ! } ! diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); ! if (diff == 0) { ! diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); ! if (diff == 0) ! diff = GET_TD_MICROSECONDS(self) - ! GET_TD_MICROSECONDS(other); } return diff_to_bool(diff, op); } --- 1665,1685 ---- delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op) { ! int diff = 42; /* nonsense */ ! if (PyDelta_CheckExact(other)) { ! diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); ! if (diff == 0) { ! diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); ! if (diff == 0) ! diff = GET_TD_MICROSECONDS(self) - ! GET_TD_MICROSECONDS(other); ! } } + else if (op == Py_EQ || op == Py_NE) + diff = 1; /* any non-zero value will do */ + + else /* stop this from falling back to address comparison */ + return cmperror((PyObject *)self, other); + return diff_to_bool(diff, op); } *************** *** 2444,2464 **** date_richcompare(PyDateTime_Date *self, PyObject *other, int op) { ! int diff; ! if (! PyDate_Check(other)) { ! if (PyObject_HasAttrString(other, "timetuple")) { ! /* A hook for other kinds of date objects. */ ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! /* Stop this from falling back to address comparison. */ ! PyErr_Format(PyExc_TypeError, ! "can't compare '%s' to '%s'", ! self->ob_type->tp_name, ! other->ob_type->tp_name); ! return NULL; } ! diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, ! _PyDateTime_DATE_DATASIZE); return diff_to_bool(diff, op); } --- 2456,2476 ---- date_richcompare(PyDateTime_Date *self, PyObject *other, int op) { ! int diff = 42; /* nonsense */ ! if (PyDate_Check(other)) ! diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, ! _PyDateTime_DATE_DATASIZE); ! ! else if (PyObject_HasAttrString(other, "timetuple")) { ! /* A hook for other kinds of date objects. */ ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } ! else if (op == Py_EQ || op == Py_NE) ! diff = 1; /* any non-zero value will do */ ! ! else /* stop this from falling back to address comparison */ ! return cmperror((PyObject *)self, other); ! return diff_to_bool(diff, op); } *************** *** 3174,3183 **** if (! PyTime_Check(other)) { /* Stop this from falling back to address comparison. */ ! PyErr_Format(PyExc_TypeError, ! "can't compare '%s' to '%s'", ! self->ob_type->tp_name, ! other->ob_type->tp_name); ! return NULL; } if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None, --- 3186,3196 ---- if (! PyTime_Check(other)) { + if (op == Py_EQ || op == Py_NE) { + PyObject *result = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(result); + return result; + } /* Stop this from falling back to address comparison. */ ! return cmperror((PyObject *)self, other); } if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None, *************** *** 4012,4021 **** return Py_NotImplemented; } /* Stop this from falling back to address comparison. */ ! PyErr_Format(PyExc_TypeError, ! "can't compare '%s' to '%s'", ! self->ob_type->tp_name, ! other->ob_type->tp_name); ! return NULL; } --- 4025,4035 ---- return Py_NotImplemented; } + if (op == Py_EQ || op == Py_NE) { + PyObject *result = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(result); + return result; + } /* Stop this from falling back to address comparison. */ ! return cmperror((PyObject *)self, other); } From gvanrossum@users.sourceforge.net Fri Feb 7 21:49:04 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 13:49:04 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.36,1.37 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv14281 Modified Files: test_datetime.py Log Message: Merge the test part of the below checkin to the sandbox and Zope3, so the tests will remain in sync: """ Tres discovered a weird bug when a datetime is pickled, caused by the shadowing of __year, __month, __day and the use of proxies. Here's a quick fix and a quick unit test. I don't quite understand why this wasn't caught by the pickling unit tests. """ Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** test_datetime.py 6 Feb 2003 16:42:14 -0000 1.36 --- test_datetime.py 7 Feb 2003 21:49:01 -0000 1.37 *************** *** 1177,1180 **** --- 1177,1188 ---- self.assertEqual(orig, derived) + def test_more_pickling(self): + a = self.theclass(2003, 2, 7, 16, 48, 37, 444116) + s = pickle.dumps(a) + b = pickle.loads(s) + self.assertEqual(b.year, 2003) + self.assertEqual(b.month, 2) + self.assertEqual(b.day, 7) + def test_more_compare(self): # The test_compare() inherited from TestDate covers the error cases. From gvanrossum@users.sourceforge.net Sat Feb 8 00:56:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 16:56:15 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv27931 Modified Files: pep-0308.txt Log Message: Add and/or alternative and why it doesn't always work. Correct origin of ?: and ?! again. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** pep-0308.txt 7 Feb 2003 22:34:54 -0000 1.5 --- pep-0308.txt 8 Feb 2003 00:56:13 -0000 1.6 *************** *** 60,63 **** --- 60,72 ---- x, y if C else z <==> x, (y if C else z) + Note: a common way to emulate an if-then-else expression is: + + and or + + However, this doesn't work the same way: it returns + when is false! See FAQ 4.16 for alternatives that + work -- however, they are pretty ugly and require much more + effort to understand. + Alternatives *************** *** 67,79 **** ? : ! I reject this for several reasons: the colon already has many uses ! in Python (even though it would actually not be ambiguous, because ! the question mark requires a matching colon); for people not used ! to C-derived language, it is hard to understand. --- ! David Ascher proposed, and Eric Raymond even implemented, a ! variant that doesn't have this problem: ? ! --- 76,88 ---- ? : ! Eric Raymond even implemented this. I reject this for several ! reasons: the colon already has many uses in Python (even though it ! would actually not be ambiguous, because the question mark ! requires a matching colon); for people not used to C-derived ! language, it is hard to understand. --- ! David Ascher proposed a variant that doesn't have this problem: ? ! *************** *** 142,147 **** x = e if C ! to several people and they all thought that if C was false, it ! would leave x unchanged. So don't even think about this one! --- 151,156 ---- x = e if C ! to several people. They all thought that if C was false, it would ! leave x unchanged. So don't even think about this one! From gvanrossum@users.sourceforge.net Sat Feb 8 02:12:45 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 07 Feb 2003 18:12:45 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv18277 Modified Files: pep-0308.txt Log Message: Add 'when' variant. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** pep-0308.txt 8 Feb 2003 00:56:13 -0000 1.6 --- pep-0308.txt 8 Feb 2003 02:12:43 -0000 1.7 *************** *** 154,157 **** --- 154,169 ---- leave x unchanged. So don't even think about this one! + --- + + Another variant proposes to use 'when' instead of 'if': + + when else + + I don't see the advantage of 'when' over 'if'; it adds a new + keyword which is a major extra hurdle to introduce this. I think + that using a different keyword suggests that the semantics are + different than those of an 'if' statement; but they really aren't + (only the syntax is different). + Copyright From bwarsaw@users.sourceforge.net Sat Feb 8 03:18:36 2003 From: bwarsaw@users.sourceforge.net (bwarsaw@users.sourceforge.net) Date: Fri, 07 Feb 2003 19:18:36 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb dbobj.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb In directory sc8-pr-cvs1:/tmp/cvs-serv6623 Modified Files: dbobj.py Log Message: Fix compatibility for earlier versions of Python (than 2.3), which doesn't have UserDict.DictMixin. Index: dbobj.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbobj.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** dbobj.py 5 Feb 2003 04:12:41 -0000 1.4 --- dbobj.py 8 Feb 2003 03:18:33 -0000 1.5 *************** *** 17,21 **** import db ! from UserDict import DictMixin class DBEnv: --- 17,26 ---- import db ! ! try: ! from UserDict import DictMixin ! except ImportError: ! # DictMixin is new in Python 2.3 ! class DictMixin: pass class DBEnv: From bwarsaw@users.sourceforge.net Sat Feb 8 03:19:00 2003 From: bwarsaw@users.sourceforge.net (bwarsaw@users.sourceforge.net) Date: Fri, 07 Feb 2003 19:19:00 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb dbshelve.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb In directory sc8-pr-cvs1:/tmp/cvs-serv6708 Modified Files: dbshelve.py Log Message: Fix compatibility for earlier versions of Python (than 2.3), which doesn't have UserDict.DictMixin. Index: dbshelve.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbshelve.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** dbshelve.py 5 Feb 2003 04:12:41 -0000 1.6 --- dbshelve.py 8 Feb 2003 03:18:58 -0000 1.7 *************** *** 31,35 **** import cPickle ! from UserDict import DictMixin try: # For Python 2.3 --- 31,39 ---- import cPickle ! try: ! from UserDict import DictMixin ! except ImportError: ! # DictMixin is new in Python 2.3 ! class DictMixin: pass try: # For Python 2.3 *************** *** 78,83 **** class DBShelf(DictMixin): ! """ ! A shelf to hold pickled objects, built upon a bsddb DB object. It automatically pickles/unpickles data objects going to/from the DB. """ --- 82,86 ---- class DBShelf(DictMixin): ! """A shelf to hold pickled objects, built upon a bsddb DB object. It automatically pickles/unpickles data objects going to/from the DB. """ *************** *** 92,96 **** def __getattr__(self, name): ! """Many methods we can just pass through to the DB object. (See below)""" return getattr(self.db, name) --- 95,101 ---- def __getattr__(self, name): ! """Many methods we can just pass through to the DB object. ! (See below) ! """ return getattr(self.db, name) From tim_one@users.sourceforge.net Sat Feb 8 03:29:03 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 19:29:03 -0800 Subject: [Python-checkins] python/dist/src/Modules datetimemodule.c,1.58,1.59 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9039/Modules Modified Files: datetimemodule.c Log Message: timedelta comparison and datetime addition: as the Python implementation of datetime does, accept instances of subclasses too. Index: datetimemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v retrieving revision 1.58 retrieving revision 1.59 diff -C2 -d -r1.58 -r1.59 *** datetimemodule.c 7 Feb 2003 22:50:28 -0000 1.58 --- datetimemodule.c 8 Feb 2003 03:28:59 -0000 1.59 *************** *** 1667,1671 **** int diff = 42; /* nonsense */ ! if (PyDelta_CheckExact(other)) { diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); if (diff == 0) { --- 1667,1671 ---- int diff = 42; /* nonsense */ ! if (PyDelta_Check(other)) { diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); if (diff == 0) { *************** *** 2300,2304 **** return Py_NotImplemented; } ! if (PyDate_CheckExact(left)) { /* date + ??? */ if (PyDelta_Check(right)) --- 2300,2304 ---- return Py_NotImplemented; } ! if (PyDate_Check(left)) { /* date + ??? */ if (PyDelta_Check(right)) *************** *** 2329,2334 **** return Py_NotImplemented; } ! if (PyDate_CheckExact(left)) { ! if (PyDate_CheckExact(right)) { /* date - date */ int left_ord = ymd_to_ord(GET_YEAR(left), --- 2329,2334 ---- return Py_NotImplemented; } ! if (PyDate_Check(left)) { ! if (PyDate_Check(right)) { /* date - date */ int left_ord = ymd_to_ord(GET_YEAR(left), From tim_one@users.sourceforge.net Sat Feb 8 03:36:44 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 19:36:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_datetime.py,1.114,1.115 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv11022 Modified Files: test_datetime.py Log Message: Now that all comparisons use piles of richcmps instead of __cmp__, this module no longer tickles the Python 2.2.2 __cmp__ bug it uncovered before. Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.114 retrieving revision 1.115 diff -C2 -d -r1.114 -r1.115 *** test_datetime.py 7 Feb 2003 21:40:36 -0000 1.114 --- test_datetime.py 8 Feb 2003 03:36:42 -0000 1.115 *************** *** 22,39 **** assert len(pickle_choices) == 2*2*3 ! ! # XXX The test suite uncovered a bug in Python 2.2.2: if x and y are ! # XXX instances of new-style classes (like date and time) that both ! # XXX define __cmp__, and x is compared to y, and one of the __cmp__ ! # XXX implementations raises an exception, the exception can get dropped ! # XXX on the floor when it occurs, and pop up again at some "random" time ! # XXX later (it depends on when the next opcode gets executed that ! # XXX bothers to check). There isn't a workaround for this, so instead ! # XXX we disable the parts of the tests that trigger it unless ! # XXX CMP_BUG_FIXED is true. The bug is still there, we simply avoid ! # XXX provoking it here. ! # XXX Guido checked into a fix that will go into 2.2.3. The bug was ! # XXX already fixed in 2.3 CVS via a different means. ! CMP_BUG_FIXED = sys.version_info >= (2, 2, 3) --- 22,28 ---- assert len(pickle_choices) == 2*2*3 ! # An arbitrary collection of objects of non-datetime types, for testing ! # mixed-type comparisons. ! OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) *************** *** 344,349 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 333,337 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 351,355 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) --- 339,342 ---- *************** *** 899,904 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 886,890 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 906,910 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) --- 892,895 ---- *************** *** 1476,1484 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = (10, 10L, 34.5, "abc", {}, [], ()) ! if CMP_BUG_FIXED: ! badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) ! ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 1461,1465 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 1486,1490 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) --- 1467,1470 ---- *************** *** 2008,2014 **** t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! if CMP_BUG_FIXED: ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In time w/ identical tzinfo objects, utcoffset is ignored. --- 1988,1993 ---- t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In time w/ identical tzinfo objects, utcoffset is ignored. *************** *** 2592,2598 **** t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! if CMP_BUG_FIXED: ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In datetime w/ identical tzinfo objects, utcoffset is ignored. --- 2571,2576 ---- t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In datetime w/ identical tzinfo objects, utcoffset is ignored. From tim_one@users.sourceforge.net Sat Feb 8 03:46:33 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 07 Feb 2003 19:46:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_datetime.py,1.38,1.39 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv13463/Lib/test Modified Files: test_datetime.py Log Message: The Python implementation of datetime was changed in ways that no longer tickle the 2.2.2 __cmp__ bug test_datetime used to tickle, so the workarounds for that bug no longer make sense in the test suite (which I'm still trying to keep as closely in synch as possible with Zope3's version). Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** test_datetime.py 7 Feb 2003 22:50:26 -0000 1.38 --- test_datetime.py 8 Feb 2003 03:46:31 -0000 1.39 *************** *** 23,39 **** assert len(pickle_choices) == 2*2*3 ! # XXX The test suite uncovered a bug in Python 2.2.2: if x and y are ! # XXX instances of new-style classes (like date and time) that both ! # XXX define __cmp__, and x is compared to y, and one of the __cmp__ ! # XXX implementations raises an exception, the exception can get dropped ! # XXX on the floor when it occurs, and pop up again at some "random" time ! # XXX later (it depends on when the next opcode gets executed that ! # XXX bothers to check). There isn't a workaround for this, so instead ! # XXX we disable the parts of the tests that trigger it unless ! # XXX CMP_BUG_FIXED is true. The bug is still there, we simply avoid ! # XXX provoking it here. ! # XXX Guido checked into a fix that will go into 2.2.3. The bug was ! # XXX already fixed in 2.3 CVS via a different means. ! CMP_BUG_FIXED = sys.version_info >= (2, 2, 3) --- 23,29 ---- assert len(pickle_choices) == 2*2*3 ! # An arbitrary collection of objects of non-datetime types, for testing ! # mixed-type comparisons. ! OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) *************** *** 344,349 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 334,338 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 351,355 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) --- 340,343 ---- *************** *** 899,904 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = 10, 10L, 34.5, "abc", {}, [], () ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 887,891 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 906,910 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 < badarg) self.assertRaises(TypeError, lambda: t1 > badarg) --- 893,896 ---- *************** *** 1476,1484 **** self.assertEqual(cmp(t2, t1), 1) ! badargs = (10, 10L, 34.5, "abc", {}, [], ()) ! if CMP_BUG_FIXED: ! badargs += (date(1, 1, 1), datetime(1, 1, 1, 1, 1), timedelta(9)) ! ! for badarg in badargs: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) --- 1462,1466 ---- self.assertEqual(cmp(t2, t1), 1) ! for badarg in OTHERSTUFF: self.assertEqual(t1 == badarg, False) self.assertEqual(t1 != badarg, True) *************** *** 1486,1490 **** self.assertEqual(badarg != t1, True) - for badarg in badargs: self.assertRaises(TypeError, lambda: t1 <= badarg) self.assertRaises(TypeError, lambda: t1 < badarg) --- 1468,1471 ---- *************** *** 2008,2014 **** t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! if CMP_BUG_FIXED: ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In time w/ identical tzinfo objects, utcoffset is ignored. --- 1989,1994 ---- t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In time w/ identical tzinfo objects, utcoffset is ignored. *************** *** 2592,2598 **** t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! if CMP_BUG_FIXED: ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In datetime w/ identical tzinfo objects, utcoffset is ignored. --- 2572,2577 ---- t2 = t2.replace(tzinfo=FixedOffset(None, "")) self.assertEqual(t1, t2) ! t2 = t2.replace(tzinfo=FixedOffset(0, "")) ! self.assertRaises(TypeError, lambda: t1 == t2) # In datetime w/ identical tzinfo objects, utcoffset is ignored. From montanaro@users.sourceforge.net Sat Feb 8 05:04:08 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 07 Feb 2003 21:04:08 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test unicode_test.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv5100 Added Files: unicode_test.py Log Message: Basic unicode test - causes a bus error so checking it in separately for now. --- NEW FILE: unicode_test.py --- # -*- coding: latin-1 -*- import unittest from StringIO import StringIO import csv class TestUnicode(unittest.TestCase): def test_unicode_read(self): import codecs f = codecs.EncodedFile(StringIO("Martin von Löwis," "Marc André Lemburg," "Guido van Rossum," "François Pinard\r\n"), data_encoding='iso-8859-1') reader = csv.reader(f) self.assertEqual(list(reader), [[u"Martin von Löwis", u"Marc André Lemburg", u"Guido van Rossum", u"François Pinardn"]]) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestUnicode)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') From mal@lemburg.com Sat Feb 8 13:25:42 2003 From: mal@lemburg.com (M.-A. Lemburg) Date: Sat, 08 Feb 2003 14:25:42 +0100 Subject: [Python-checkins] python/nondist/sandbox/csv/test unicode_test.py,NONE,1.1 In-Reply-To: References: Message-ID: <3E450556.7060102@lemburg.com> I don't understand: have you moved the existing test from test_codecs.py to a new file or this a new bug ? montanaro@users.sourceforge.net wrote: > Update of /cvsroot/python/python/nondist/sandbox/csv/test > In directory sc8-pr-cvs1:/tmp/cvs-serv5100 >=20 > Added Files: > unicode_test.py=20 > Log Message: > Basic unicode test - causes a bus error so checking it in separately fo= r > now. >=20 >=20 > --- NEW FILE: unicode_test.py --- > # -*- coding: latin-1 -*- > import unittest > from StringIO import StringIO > import csv >=20 > class TestUnicode(unittest.TestCase): > def test_unicode_read(self): > import codecs > f =3D codecs.EncodedFile(StringIO("Martin von L=F6wis," > "Marc Andr=E9 Lemburg," > "Guido van Rossum," > "Fran=E7ois Pinard\r\n"), > data_encoding=3D'iso-8859-1') > reader =3D csv.reader(f) > self.assertEqual(list(reader), [[u"Martin von L=F6wis", > u"Marc Andr=E9 Lemburg", > u"Guido van Rossum", > u"Fran=E7ois Pinardn"]]) >=20 > def suite(): > suite =3D unittest.TestSuite() > suite.addTest(unittest.makeSuite(TestUnicode)) > return suite >=20 > if __name__ =3D=3D '__main__': > unittest.main(defaultTest=3D'suite') >=20 >=20 >=20 > _______________________________________________ > Python-checkins mailing list > Python-checkins@python.org > http://mail.python.org/mailman/listinfo/python-checkins --=20 Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From gvanrossum@users.sourceforge.net Sat Feb 8 13:40:54 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sat, 08 Feb 2003 05:40:54 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv8375 Modified Files: pep-0308.txt Log Message: It is *right* associative! (The example was right. :-) Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** pep-0308.txt 8 Feb 2003 02:12:43 -0000 1.7 --- pep-0308.txt 8 Feb 2003 13:40:52 -0000 1.8 *************** *** 46,52 **** To disambiguate this in the context of other operators, the ! "if...else" part in the middle acts like a left-associative binary ! operator with a priority lower than that of "or", and higher than ! that of "lambda". Examples of how this works out: --- 46,52 ---- To disambiguate this in the context of other operators, the ! "if...else" part in the middle acts like a right-associative ! binary operator with a priority lower than that of "or", and ! higher than that of "lambda". Examples of how this works out: From montanaro@users.sourceforge.net Sat Feb 8 15:22:32 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sat, 08 Feb 2003 07:22:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv6531 Modified Files: _csv.c Log Message: Split module docstring up into pieces and give each exposed object its own docstring. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** _csv.c 7 Feb 2003 06:33:00 -0000 1.20 --- _csv.c 8 Feb 2003 15:22:28 -0000 1.21 *************** *** 1124,1128 **** "This module provides classes that assist in the reading and writing\n" "of Comma Separated Value (CSV) files, and implements the interface\n" ! "described by PEP 305. Although many CSV files are simple to parse,\n" "the format is not formally defined by a stable specification and\n" "is subtle enough that parsing lines of a CSV file with something\n" --- 1124,1128 ---- "This module provides classes that assist in the reading and writing\n" "of Comma Separated Value (CSV) files, and implements the interface\n" ! "described by PEP 305. Although many CSV files are simple to parse,\n" "the format is not formally defined by a stable specification and\n" "is subtle enough that parsing lines of a CSV file with something\n" *************** *** 1131,1178 **** "\n" "\n" - "READING:\n" - "\n" - "The reader interface is provided by a factory function \"reader\":\n" - "\n" - " csv_reader = reader(iterable [, dialect='excel']\n" - " [optional keyword args])\n" - " for row in csv_reader:\n" - " process(row)\n" - "\n" - "The \"iterable\" argument can be any object that returns a line\n" - "of input for each iteration, such as a file object or a list. The\n" - "optional \"dialect\" parameter is discussed below. The function\n" - "also accepts optional keyword arguments which override settings\n" - "provided by the dialect.\n" - "\n" - "The returned object is an iterator. Each iteration returns a row\n" - "of the CSV file (which can span multiple input lines):\n" - "\n" - "\n" - "WRITING:\n" - "\n" - "The writer interface is provided by a factory function \"writer\":\n" - "\n" - " csv_writer = csv.writer(fileobj [, dialect='excel']\n" - " [optional keyword args])\n" - " for row in csv_writer:\n" - " csv_writer.writerow(row)\n" - "\n" - " [or]\n" - "\n" - " csv_writer = csv.writer(fileobj [, dialect='excel']\n" - " [optional keyword args])\n" - " csv_writer.writerows(rows)\n" - "\n" - "The \"fileobj\" argument can be any object that supports the file API.\n" - "\n" - "\n" "DIALECT REGISTRATION:\n" "\n" ! "Readers and writers support a dialect argument, which is a convient\n" ! "handle on a group of settings. When the dialect argument is a string,\n" ! "it identifies one of the dialects registered with the module. If it\n" ! "is a class or instance, the attributes of the argument are used as the\n" ! "settings for the reader or writer:\n" "\n" " class excel:\n" --- 1131,1141 ---- "\n" "\n" "DIALECT REGISTRATION:\n" "\n" ! "Readers and writers support a dialect argument, which is a convenient\n" ! "handle on a group of settings. When the dialect argument is a string,\n" ! "it identifies one of the dialects previously registered with the module.\n" ! "If it is a class or instance, the attributes of the argument are used as\n" ! "the settings for the reader or writer:\n" "\n" " class excel:\n" *************** *** 1185,1205 **** " quoting = QUOTE_MINIMAL\n" "\n" - "The dialect registry is supported by four functions:\n" - "\n" - " list_dialects()\n" - " register_dialect(name, dialect)\n" - " unregister_dialect(name)\n" - " get_dialect(name)\n" - "\n" "SETTINGS:\n" "\n" " * quotechar - specifies a one-character string to use as the \n" ! " quoting character. It defaults to '\"'.\n" " * delimiter - specifies a one-character string to use as the \n" ! " field separator. It defaults to ','.\n" ! " * escapechar - specifies a one-character string used to escape \n" ! " the delimiter when quoting is set to QUOTE_NONE.\n" " * skipinitialspace - specifies how to interpret whitespace which\n" ! " immediately follows a delimiter. It defaults to False, which\n" " means that whitespace immediately following a delimiter is part\n" " of the following field.\n" --- 1148,1159 ---- " quoting = QUOTE_MINIMAL\n" "\n" "SETTINGS:\n" "\n" " * quotechar - specifies a one-character string to use as the \n" ! " quoting character. It defaults to '\"'.\n" " * delimiter - specifies a one-character string to use as the \n" ! " field separator. It defaults to ','.\n" " * skipinitialspace - specifies how to interpret whitespace which\n" ! " immediately follows a delimiter. It defaults to False, which\n" " means that whitespace immediately following a delimiter is part\n" " of the following field.\n" *************** *** 1215,1235 **** " fields which contain characters other than [+-0-9.].\n" " csv.QUOTE_NONE means that quotes are never placed around fields.\n" ! " * doublequote - controls the handling of quotes inside fields. When\n" ! " True two consecutive quotes are interpreted as one during read,\n" ! " and when writing, each quote is written as two quotes\n"); static struct PyMethodDef csv_methods[] = { { "reader", (PyCFunction)csv_reader, ! METH_VARARGS | METH_KEYWORDS, csv_module_doc}, { "writer", (PyCFunction)csv_writer, ! METH_VARARGS | METH_KEYWORDS, csv_module_doc}, { "list_dialects", (PyCFunction)csv_list_dialects, ! METH_VARARGS, csv_module_doc}, { "register_dialect", (PyCFunction)csv_register_dialect, ! METH_VARARGS, csv_module_doc}, { "unregister_dialect", (PyCFunction)csv_unregister_dialect, ! METH_VARARGS, csv_module_doc}, { "get_dialect", (PyCFunction)csv_get_dialect, ! METH_VARARGS, csv_module_doc}, { NULL, NULL } }; --- 1169,1233 ---- " fields which contain characters other than [+-0-9.].\n" " csv.QUOTE_NONE means that quotes are never placed around fields.\n" ! " * escapechar - specifies a one-character string used to escape \n" ! " the delimiter when quoting is set to QUOTE_NONE.\n" ! " * doublequote - controls the handling of quotes inside fields. When\n" ! " True, two consecutive quotes are interpreted as one during read,\n" ! " and when writing, each quote character embedded in the data is\n" ! " written as two quotes\n"); ! ! PyDoc_STRVAR(csv_reader_doc, ! " csv_reader = reader(iterable [, dialect='excel']\n" ! " [optional keyword args])\n" ! " for row in csv_reader:\n" ! " process(row)\n" ! "\n" ! "The \"iterable\" argument can be any object that returns a line\n" ! "of input for each iteration, such as a file object or a list. The\n" ! "optional \"dialect\" parameter is discussed below. The function\n" ! "also accepts optional keyword arguments which override settings\n" ! "provided by the dialect.\n" ! "\n" ! "The returned object is an iterator. Each iteration returns a row\n" ! "of the CSV file (which can span multiple input lines):\n"); ! ! PyDoc_STRVAR(csv_writer_doc, ! " csv_writer = csv.writer(fileobj [, dialect='excel']\n" ! " [optional keyword args])\n" ! " for row in csv_writer:\n" ! " csv_writer.writerow(row)\n" ! "\n" ! " [or]\n" ! "\n" ! " csv_writer = csv.writer(fileobj [, dialect='excel']\n" ! " [optional keyword args])\n" ! " csv_writer.writerows(rows)\n" ! "\n" ! "The \"fileobj\" argument can be any object that supports the file API.\n"); ! ! PyDoc_STRVAR(csv_list_dialects_doc, ! " names = csv.list_dialects()"); ! ! PyDoc_STRVAR(csv_get_dialect_doc, ! " dialect = csv.get_dialects(name)"); ! ! PyDoc_STRVAR(csv_register_dialect_doc, ! " dialect = csv.register_dialect(name, dialect)"); ! ! PyDoc_STRVAR(csv_unregister_dialect_doc, ! " csv.unregister_dialect(name)"); static struct PyMethodDef csv_methods[] = { { "reader", (PyCFunction)csv_reader, ! METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, { "writer", (PyCFunction)csv_writer, ! METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, { "list_dialects", (PyCFunction)csv_list_dialects, ! METH_VARARGS, csv_list_dialects_doc}, { "register_dialect", (PyCFunction)csv_register_dialect, ! METH_VARARGS, csv_register_dialect_doc}, { "unregister_dialect", (PyCFunction)csv_unregister_dialect, ! METH_VARARGS, csv_unregister_dialect_doc}, { "get_dialect", (PyCFunction)csv_get_dialect, ! METH_VARARGS, csv_get_dialect_doc}, { NULL, NULL } }; From montanaro@users.sourceforge.net Sat Feb 8 15:22:57 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sat, 08 Feb 2003 07:22:57 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv6654 Modified Files: csv.py Log Message: import __doc__ from _csv Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** csv.py 7 Feb 2003 01:27:21 -0000 1.24 --- csv.py 8 Feb 2003 15:22:55 -0000 1.25 *************** *** 1,5 **** from _csv import Error, __version__, writer, reader, register_dialect, \ unregister_dialect, get_dialect, list_dialects, \ ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", --- 1,6 ---- from _csv import Error, __version__, writer, reader, register_dialect, \ unregister_dialect, get_dialect, list_dialects, \ ! QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \ ! __doc__ __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", From skip@pobox.com Sat Feb 8 15:25:58 2003 From: skip@pobox.com (Skip Montanaro) Date: Sat, 8 Feb 2003 09:25:58 -0600 Subject: [Python-checkins] python/nondist/sandbox/csv/test unicode_test.py,NONE,1.1 Message-ID: <15941.8582.901618.823053@montanaro.dyndns.org> mal> I don't understand: have you moved the existing test from mal> test_codecs.py to a new file or this a new bug ? No, note that this is a test in the csv sandbox: mal> montanaro@users.sourceforge.net wrote: >> Update of /cvsroot/python/python/nondist/sandbox/csv/test ... It has nothing to do with the codecs module other than using its EncodedFile class to wrap a StringIO object. What's being tested is the csv module's current lack of Unicode support. See http://mail.python.org/pipermail/python-list/2003-February/145151.html for motivation. (Feel free to respond to that note. ;-) Skip From mal@lemburg.com Sat Feb 8 17:24:22 2003 From: mal@lemburg.com (M.-A. Lemburg) Date: Sat, 08 Feb 2003 18:24:22 +0100 Subject: [Python-checkins] python/nondist/sandbox/csv/test unicode_test.py,NONE,1.1 In-Reply-To: <15941.8582.901618.823053@montanaro.dyndns.org> References: <15941.8582.901618.823053@montanaro.dyndns.org> Message-ID: <3E453D46.7080307@lemburg.com> Skip Montanaro wrote: > > mal> I don't understand: have you moved the existing test from > mal> test_codecs.py to a new file or this a new bug ? > > No, note that this is a test in the csv sandbox: > > mal> montanaro@users.sourceforge.net wrote: > >> Update of /cvsroot/python/python/nondist/sandbox/csv/test > ... > > It has nothing to do with the codecs module other than using its EncodedFile > class to wrap a StringIO object. What's being tested is the csv module's > current lack of Unicode support. Oh, ok. > See > > http://mail.python.org/pipermail/python-list/2003-February/145151.html > > for motivation. (Feel free to respond to that note. ;-) Why not convert the input data to UTF-8 and take it from there ? Are you sure that Unicode objects will be lower in processing ? (Is there a standard for encodings in CSV files ?) -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From mwh@users.sourceforge.net Sat Feb 8 18:05:15 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Sat, 08 Feb 2003 10:05:15 -0800 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.75,2.76 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv6131 Modified Files: parsermodule.c Log Message: Apply logistix's patch from [ 678518 ] Another parsermodule validation error Index: parsermodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/parsermodule.c,v retrieving revision 2.75 retrieving revision 2.76 diff -C2 -d -r2.75 -r2.76 *** parsermodule.c 29 Jan 2003 14:20:22 -0000 2.75 --- parsermodule.c 8 Feb 2003 18:05:10 -0000 2.76 *************** *** 550,554 **** static int validate_expr_tree(node *tree); static int validate_file_input(node *tree); ! /* PyObject* parser_tuple2st(PyObject* self, PyObject* args) --- 550,554 ---- static int validate_expr_tree(node *tree); static int validate_file_input(node *tree); ! static int validate_encoding_decl(node *tree); /* PyObject* parser_tuple2st(PyObject* self, PyObject* args) *************** *** 603,606 **** --- 603,613 ---- PyNode_Free(tree); } + else if (start_sym == encoding_decl) { + /* This looks like an encoding_decl so far. */ + if (validate_encoding_decl(tree)) + st = parser_newstobject(tree, PyST_SUITE); + else + PyNode_Free(tree); + } else { /* This is a fragment, at best. */ *************** *** 765,769 **** --- 772,783 ---- */ int line_num = 0; + PyObject *encoding = NULL; + PyObject *tmpTuple = NULL; + if (num == encoding_decl) { + encoding = PySequence_GetItem(tuple, 2); + /* tuple isn't borrowed anymore here, need to DECREF */ + tuple = PySequence_GetSlice(tuple, 0, 2); + } res = PyNode_New(num); if (res != NULL) { *************** *** 772,775 **** --- 786,798 ---- res = NULL; } + if (res && encoding) { + int len; + len = PyString_GET_SIZE(encoding) + 1; + res->n_str = (char *)PyMem_MALLOC(len); + if (res->n_str != NULL) + (void) memcpy(res->n_str, PyString_AS_STRING(encoding), len); + Py_DECREF(encoding); + Py_DECREF(tuple); + } } } *************** *** 1695,1698 **** --- 1718,1727 ---- && is_even(nch) && (nch >= 2)); + if (!res && !PyErr_Occurred()) + err_string("illegal global statement"); + + if (!res && !PyErr_Occurred()) + err_string("illegal global statement"); + if (res) res = (validate_name(CHILD(tree, 0), "global") *************** *** 1742,1747 **** int res = (validate_ntype(tree, assert_stmt) && ((nch == 2) || (nch == 4)) ! && (validate_name(CHILD(tree, 0), "__assert__") || ! validate_name(CHILD(tree, 0), "assert")) && validate_test(CHILD(tree, 1))); --- 1771,1775 ---- int res = (validate_ntype(tree, assert_stmt) && ((nch == 2) || (nch == 4)) ! && (validate_name(CHILD(tree, 0), "assert")) && validate_test(CHILD(tree, 1))); *************** *** 2776,2779 **** --- 2804,2819 ---- } + static int + validate_encoding_decl(node *tree) + { + int nch = NCH(tree); + int res = ((nch == 1) + && validate_file_input(CHILD(tree, 0))); + + if (!res && !PyErr_Occurred()) + err_string("Error Parsing encoding_decl"); + + return res; + } static PyObject* From neal@metaslash.com Sat Feb 8 18:28:20 2003 From: neal@metaslash.com (Neal Norwitz) Date: Sat, 08 Feb 2003 13:28:20 -0500 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.75,2.76 In-Reply-To: References: Message-ID: <20030208182820.GK23059@epoch.metaslash.com> > *************** > *** 1695,1698 **** > --- 1718,1727 ---- > + if (!res && !PyErr_Occurred()) > + err_string("illegal global statement"); > + > + if (!res && !PyErr_Occurred()) > + err_string("illegal global statement"); Isn't only one of these is required? Neal From goodger@users.sourceforge.net Sat Feb 8 22:23:45 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Sat, 08 Feb 2003 14:23:45 -0800 Subject: [Python-checkins] python/nondist/peps docutils.conf,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv6422 Modified Files: docutils.conf Log Message: new stylesheet entry Index: docutils.conf =================================================================== RCS file: /cvsroot/python/python/nondist/peps/docutils.conf,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** docutils.conf 30 Aug 2002 03:12:36 -0000 1.2 --- docutils.conf 8 Feb 2003 22:23:42 -0000 1.3 *************** *** 12,13 **** --- 12,16 ---- pep-template: pep-html-template pep-stylesheet: pep.css + + # Standalone HTML: + stylesheet: ../docutils.css From goodger@users.sourceforge.net Sat Feb 8 22:35:32 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Sat, 08 Feb 2003 14:35:32 -0800 Subject: [Python-checkins] python/nondist/peps README.txt,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv10512 Modified Files: README.txt Log Message: updated; Docutils install no longer required Index: README.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/README.txt,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** README.txt 30 Aug 2002 03:13:40 -0000 1.2 --- README.txt 8 Feb 2003 22:35:29 -0000 1.3 *************** *** 4,34 **** Original PEP source may be written using two standard formats, a mildly idiomatic plaintext format and the reStructuredText format ! (also, technically plaintext). These two formats are described in ! PEP 9 and PEP 12 respectively. The pep2html.py processing and installation script knows how to produce the HTML for either PEP ! format, however in order to process reStructuredText PEPs, you must ! install the Docutils package. If this package is not installed, ! pep2html.py will simply skip any reStructuredText PEPs. ! ! ! Installing Docutils for reStructuredText PEPs ! --------------------------------------------- ! ! 1. Get the latest Docutils software (CVS snapshot): ! ! http://docutils.sourceforge.net/docutils-snapshot.tgz ! ! 2. Unpack and install the tarball:: ! ! tar -xzf docutils-snapshot.tgz ! cd docutils ! python setup.py install ! ! 3. Run the pep2html.py script from the updated nondist/peps directory ! as usual:: ! ! cd /nondist/peps ! cvs update ! pep2html.py ... Please report any problems or questions to --- 4,12 ---- Original PEP source may be written using two standard formats, a mildly idiomatic plaintext format and the reStructuredText format ! (also, technically plaintext). These two formats are described in PEP ! 9 and PEP 12 respectively. The pep2html.py processing and installation script knows how to produce the HTML for either PEP ! format. A local copy of the Docutils package is included for ! processing reStructuredText PEPs. Please report any problems or questions to From davecole@users.sourceforge.net Sun Feb 9 00:59:59 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sat, 08 Feb 2003 16:59:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv1562 Modified Files: _csv.c Log Message: Reverse the sequence of leading spaces and delimiter as start of field. This allows fields to be delimited by one or more spaces. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** _csv.c 8 Feb 2003 15:22:28 -0000 1.21 --- _csv.c 9 Feb 2003 00:59:56 -0000 1.22 *************** *** 182,192 **** self->state = ESCAPED_CHAR; } else if (c == self->dialect.delimiter) { /* save empty field */ parse_save_field(self); } - else if (c == ' ' && self->dialect.skipinitialspace) - /* ignore space at start of field */ - ; else { /* begin new unquoted field */ --- 182,192 ---- self->state = ESCAPED_CHAR; } + else if (c == ' ' && self->dialect.skipinitialspace) + /* ignore space at start of field */ + ; else if (c == self->dialect.delimiter) { /* save empty field */ parse_save_field(self); } else { /* begin new unquoted field */ From nnorwitz@users.sourceforge.net Sun Feb 9 01:10:05 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sat, 08 Feb 2003 17:10:05 -0800 Subject: [Python-checkins] python/dist/src/Objects fileobject.c,2.175,2.176 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv8171/Objects Modified Files: fileobject.c Log Message: SF patch #683187, fix universal newline problems on error Index: fileobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/fileobject.c,v retrieving revision 2.175 retrieving revision 2.176 diff -C2 -d -r2.175 -r2.176 *** fileobject.c 3 Jan 2003 19:16:14 -0000 2.175 --- fileobject.c 9 Feb 2003 01:10:02 -0000 2.176 *************** *** 2279,2283 **** if (!fobj || !PyFile_Check(fobj)) { errno = ENXIO; /* What can you do... */ ! return -1; } if (!f->f_univ_newline) --- 2279,2283 ---- if (!fobj || !PyFile_Check(fobj)) { errno = ENXIO; /* What can you do... */ ! return 0; } if (!f->f_univ_newline) *************** *** 2295,2298 **** --- 2295,2301 ---- nread = fread(dst, 1, n, stream); assert(nread <= n); + if (nread == 0) + break; + n -= nread; /* assuming 1 byte out for each in; will adjust */ shortread = n != 0; /* true iff EOF or error */ From goodger@users.sourceforge.net Sun Feb 9 05:12:56 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Sat, 08 Feb 2003 21:12:56 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.17,1.18 pep-0308.txt,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv657a Modified Files: pep-0307.txt pep-0308.txt Log Message: fixed status Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** pep-0307.txt 7 Feb 2003 20:57:23 -0000 1.17 --- pep-0307.txt 9 Feb 2003 05:12:54 -0000 1.18 *************** *** 4,8 **** Last-Modified: $Date$ Author: Guido van Rossum, Tim Peters ! Status: Active Type: Standards Track Content-Type: text/plain --- 4,8 ---- Last-Modified: $Date$ Author: Guido van Rossum, Tim Peters ! Status: Draft Type: Standards Track Content-Type: text/plain Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** pep-0308.txt 8 Feb 2003 13:40:52 -0000 1.8 --- pep-0308.txt 9 Feb 2003 05:12:54 -0000 1.9 *************** *** 4,8 **** Last-Modified: $Date$ Author: Guido van Rossum ! Status: Active Type: Standards Track Content-Type: text/plain --- 4,8 ---- Last-Modified: $Date$ Author: Guido van Rossum ! Status: Draft Type: Standards Track Content-Type: text/plain From rhettinger@users.sourceforge.net Sun Feb 9 06:41:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 08 Feb 2003 22:41:00 -0800 Subject: [Python-checkins] python/dist/src/Lib sets.py,1.40,1.41 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv7878/Lib Modified Files: sets.py Log Message: C Code: * Removed the ifilter flag wart by splitting it into two simpler functions. * Fixed comment tabbing in C code. * Factored module start-up code into a loop. Documentation: * Re-wrote introduction. * Addede examples for quantifiers. * Simplified python equivalent for islice(). * Documented split of ifilter(). Sets.py: * Replace old ifilter() usage with new. Index: sets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sets.py,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** sets.py 4 Feb 2003 00:38:20 -0000 1.40 --- sets.py 9 Feb 2003 06:40:57 -0000 1.41 *************** *** 58,62 **** __all__ = ['BaseSet', 'Set', 'ImmutableSet'] ! from itertools import ifilter class BaseSet(object): --- 58,62 ---- __all__ = ['BaseSet', 'Set', 'ImmutableSet'] ! from itertools import ifilter, ifilterfalse class BaseSet(object): *************** *** 205,211 **** selfdata = self._data otherdata = other._data ! for elt in ifilter(otherdata.has_key, selfdata, True): data[elt] = value ! for elt in ifilter(selfdata.has_key, otherdata, True): data[elt] = value return result --- 205,211 ---- selfdata = self._data otherdata = other._data ! for elt in ifilterfalse(otherdata.has_key, selfdata): data[elt] = value ! for elt in ifilterfalse(selfdata.has_key, otherdata): data[elt] = value return result *************** *** 228,232 **** data = result._data value = True ! for elt in ifilter(other._data.has_key, self, True): data[elt] = value return result --- 228,232 ---- data = result._data value = True ! for elt in ifilterfalse(other._data.has_key, self): data[elt] = value return result *************** *** 261,265 **** if len(self) > len(other): # Fast check for obvious cases return False ! for elt in ifilter(other._data.has_key, self, True): return False return True --- 261,265 ---- if len(self) > len(other): # Fast check for obvious cases return False ! for elt in ifilterfalse(other._data.has_key, self): return False return True *************** *** 270,274 **** if len(self) < len(other): # Fast check for obvious cases return False ! for elt in ifilter(self._data.has_key, other, True): return False return True --- 270,274 ---- if len(self) < len(other): # Fast check for obvious cases return False ! for elt in ifilterfalse(self._data.has_key, other): return False return True From rhettinger@users.sourceforge.net Sun Feb 9 06:41:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 08 Feb 2003 22:41:00 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv7878/Doc/lib Modified Files: libitertools.tex Log Message: C Code: * Removed the ifilter flag wart by splitting it into two simpler functions. * Fixed comment tabbing in C code. * Factored module start-up code into a loop. Documentation: * Re-wrote introduction. * Addede examples for quantifiers. * Simplified python equivalent for islice(). * Documented split of ifilter(). Sets.py: * Replace old ifilter() usage with new. Index: libitertools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libitertools.tex,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** libitertools.tex 7 Feb 2003 05:32:57 -0000 1.2 --- libitertools.tex 9 Feb 2003 06:40:57 -0000 1.3 *************** *** 13,55 **** has been recast in a form suitable for Python. ! With the advent of iterators and generators in Python 2.3, each of ! these tools can be expressed easily and succinctly in pure python. ! Rather duplicating what can already be done, this module emphasizes ! providing value in other ways: ! ! \begin{itemize} ! ! \item Instead of constructing an over-specialized toolset, this module ! provides basic building blocks that can be readily combined. ! For instance, SML provides a tabulation tool: \code{tabulate(\var{f})} ! which produces a sequence \code{f(0), f(1), ...}. This toolbox ! takes a different approach of providing \function{imap()} and ! \function{count()} which can be combined to form ! \code{imap(\var{f}, count())} and produce an equivalent result. ! \item Some tools were dropped because they offer no advantage over their ! pure python counterparts or because their behavior was too ! surprising. ! For instance, SML provides a tool: \code{cycle(\var{seq})} which ! loops over the sequence elements and then starts again when the ! sequence is exhausted. The surprising behavior is the need for ! significant auxiliary storage (unusual for iterators). Also, it ! is trivially implemented in python with almost no performance ! penalty. ! \item Another source of value comes from standardizing a core set of tools ! to avoid the readability and reliability problems that arise when many ! different individuals create their own slightly varying implementations ! each with their own quirks and naming conventions. ! \item Whether cast in pure python form or C code, tools that use iterators ! are more memory efficient (and faster) than their list based counterparts. ! Adopting the principles of just-in-time manufacturing, they create ! data when and where needed instead of consuming memory with the ! computer equivalent of ``inventory''. ! \end{itemize} \begin{seealso} --- 13,53 ---- has been recast in a form suitable for Python. ! The module standardizes a core set of fast, memory efficient tools ! that are useful by themselves or in combination. Standardization helps ! avoid the readability and reliability problems which arise when many ! different individuals create their own slightly varying implementations, ! each with their own quirks and naming conventions. ! The tools are designed to combine readily with each another. This makes ! it easy to construct more specialized tools succinctly and efficiently ! in pure Python. ! For instance, SML provides a tabulation tool: \code{tabulate(\var{f})} ! which produces a sequence \code{f(0), f(1), ...}. This toolbox ! provides \function{imap()} and \function{count()} which can be combined ! to form \code{imap(\var{f}, count())} and produce an equivalent result. ! Whether cast in pure python form or C code, tools that use iterators ! are more memory efficient (and faster) than their list based counterparts. ! Adopting the principles of just-in-time manufacturing, they create ! data when and where needed instead of consuming memory with the ! computer equivalent of ``inventory''. ! Some tools were omitted from the module because they offered no ! advantage over their pure python counterparts or because their behavior ! was too surprising. ! For instance, SML provides a tool: \code{cycle(\var{seq})} which ! loops over the sequence elements and then starts again when the ! sequence is exhausted. The surprising behavior is the need for ! significant auxiliary storage (which is unusual for an iterator). ! If needed, the tool is readily constructible using pure Python. ! Other tools are being considered for inclusion in future versions of the ! module. For instance, the function ! \function{chain(\var{it0}, \var{it1}, ...})} would return elements from ! the first iterator until it was exhausted and then move on to each ! successive iterator. The module author welcomes suggestions for other ! basic building blocks. \begin{seealso} *************** *** 108,129 **** \end{funcdesc} ! \begin{funcdesc}{ifilter}{predicate, iterable \optional{, invert}} Make an iterator that filters elements from iterable returning only ! those for which the predicate is \code{True}. If ! \var{invert} is \code{True}, then reverse the process and pass through ! only those elements for which the predicate is \code{False}. ! If \var{predicate} is \code{None}, return the items that are true ! (or false if \var{invert} has been set). Equivalent to: \begin{verbatim} ! def ifilter(predicate, iterable, invert=False): ! iterable = iter(iterable) ! while True: ! x = iterable.next() ! if predicate is None: ! b = bool(x) ! else: ! b = bool(predicate(x)) ! if not invert and b or invert and not b: yield x \end{verbatim} --- 106,139 ---- \end{funcdesc} ! \begin{funcdesc}{ifilter}{predicate, iterable} Make an iterator that filters elements from iterable returning only ! those for which the predicate is \code{True}. ! If \var{predicate} is \code{None}, return the items that are true. ! Equivalent to: \begin{verbatim} ! def ifilter(predicate, iterable): ! if predicate is None: ! def predicate(x): ! return x ! for x in iterable: ! if predicate(x): ! yield x ! \end{verbatim} ! \end{funcdesc} ! ! \begin{funcdesc}{ifilterfalse}{predicate, iterable} ! Make an iterator that filters elements from iterable returning only ! those for which the predicate is \code{False}. ! If \var{predicate} is \code{None}, return the items that are false. ! Equivalent to: ! ! \begin{verbatim} ! def ifilterfalse(predicate, iterable): ! if predicate is None: ! def predicate(x): ! return x ! for x in iterable: ! if not predicate(x): yield x \end{verbatim} *************** *** 170,188 **** \begin{verbatim} def islice(iterable, *args): - iterable = iter(iterable) s = slice(*args) next = s.start or 0 stop = s.stop step = s.step or 1 ! cnt = 0 ! while True: ! while cnt < next: ! dummy = iterable.next() ! cnt += 1 ! if cnt >= stop: ! break ! yield iterable.next() ! cnt += 1 ! next += step \end{verbatim} \end{funcdesc} --- 180,194 ---- \begin{verbatim} def islice(iterable, *args): s = slice(*args) next = s.start or 0 stop = s.stop step = s.step or 1 ! for cnt, element in enumerate(iterable): ! if cnt < next: ! continue ! if cnt >= stop: ! break ! yield element ! next += step \end{verbatim} \end{funcdesc} *************** *** 325,329 **** >>> def nth(iterable, n): ... "Returns the nth item" ! ... return islice(iterable, n, n+1).next() \end{verbatim} --- 331,347 ---- >>> def nth(iterable, n): ... "Returns the nth item" ! ... return list(islice(iterable, n, n+1)) ! ! >>> def all(pred, seq): ! ... "Returns True if pred(x) is True for every element in the iterable" ! ... return not nth(ifilterfalse(pred, seq), 0) ! ! >>> def some(pred, seq): ! ... "Returns True if pred(x) is True at least one element in the iterable" ! ... return bool(nth(ifilter(pred, seq), 0)) ! ! >>> def no(pred, seq): ! ... "Returns True if pred(x) is False for every element in the iterable" ! ... return not nth(ifilter(pred, seq), 0) \end{verbatim} From rhettinger@users.sourceforge.net Sun Feb 9 06:41:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 08 Feb 2003 22:41:00 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_itertools.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv7878/Lib/test Modified Files: test_itertools.py Log Message: C Code: * Removed the ifilter flag wart by splitting it into two simpler functions. * Fixed comment tabbing in C code. * Factored module start-up code into a loop. Documentation: * Re-wrote introduction. * Addede examples for quantifiers. * Simplified python equivalent for islice(). * Documented split of ifilter(). Sets.py: * Replace old ifilter() usage with new. Index: test_itertools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_itertools.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_itertools.py 7 Feb 2003 05:32:58 -0000 1.3 --- test_itertools.py 9 Feb 2003 06:40:58 -0000 1.4 *************** *** 14,23 **** return x%2==0 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4]) - self.assertEqual(list(ifilter(isEven, range(6), True)), [1,3,5]) self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2]) self.assertRaises(TypeError, ifilter) self.assertRaises(TypeError, ifilter, 3) self.assertRaises(TypeError, ifilter, isEven, 3) ! self.assertRaises(TypeError, ifilter, isEven, [3], True, 4) def test_izip(self): --- 14,30 ---- return x%2==0 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4]) self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2]) self.assertRaises(TypeError, ifilter) self.assertRaises(TypeError, ifilter, 3) self.assertRaises(TypeError, ifilter, isEven, 3) ! ! def test_ifilterfalse(self): ! def isEven(x): ! return x%2==0 ! self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5]) ! self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0]) ! self.assertRaises(TypeError, ifilterfalse) ! self.assertRaises(TypeError, ifilterfalse, 3) ! self.assertRaises(TypeError, ifilterfalse, isEven, 3) def test_izip(self): *************** *** 134,138 **** >>> def nth(iterable, n): ... "Returns the nth item" ! ... return islice(iterable, n, n+1).next() """ --- 141,157 ---- >>> def nth(iterable, n): ... "Returns the nth item" ! ... return list(islice(iterable, n, n+1)) ! ! >>> def all(pred, seq): ! ... "Returns True if pred(x) is True for every element in the iterable" ! ... return not nth(ifilterfalse(pred, seq), 0) ! ! >>> def some(pred, seq): ! ... "Returns True if pred(x) is True at least one element in the iterable" ! ... return bool(nth(ifilter(pred, seq), 0)) ! ! >>> def no(pred, seq): ! ... "Returns True if pred(x) is False for every element in the iterable" ! ... return not nth(ifilter(pred, seq), 0) """ From rhettinger@users.sourceforge.net Sun Feb 9 06:41:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 08 Feb 2003 22:41:00 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv7878/Modules Modified Files: itertoolsmodule.c Log Message: C Code: * Removed the ifilter flag wart by splitting it into two simpler functions. * Fixed comment tabbing in C code. * Factored module start-up code into a loop. Documentation: * Re-wrote introduction. * Addede examples for quantifiers. * Simplified python equivalent for islice(). * Documented split of ifilter(). Sets.py: * Replace old ifilter() usage with new. Index: itertoolsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/itertoolsmodule.c,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** itertoolsmodule.c 7 Feb 2003 07:26:25 -0000 1.3 --- itertoolsmodule.c 9 Feb 2003 06:40:58 -0000 1.4 *************** *** 119,127 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.dropwhile", /* tp_name */ ! sizeof(dropwhileobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)dropwhile_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 119,127 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.dropwhile", /* tp_name */ ! sizeof(dropwhileobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)dropwhile_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 140,150 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! dropwhile_doc, /* tp_doc */ (traverseproc)dropwhile_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)dropwhile_getiter, /* tp_iter */ ! (iternextfunc)dropwhile_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 140,150 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! dropwhile_doc, /* tp_doc */ (traverseproc)dropwhile_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)dropwhile_getiter, /* tp_iter */ ! (iternextfunc)dropwhile_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 157,161 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! dropwhile_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 157,161 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! dropwhile_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 272,280 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.takewhile", /* tp_name */ ! sizeof(takewhileobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)takewhile_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 272,280 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.takewhile", /* tp_name */ ! sizeof(takewhileobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)takewhile_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 293,303 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! takewhile_doc, /* tp_doc */ (traverseproc)takewhile_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)takewhile_getiter, /* tp_iter */ ! (iternextfunc)takewhile_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 293,303 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! takewhile_doc, /* tp_doc */ (traverseproc)takewhile_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)takewhile_getiter, /* tp_iter */ ! (iternextfunc)takewhile_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 310,314 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! takewhile_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 310,314 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! takewhile_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 450,454 **** 0, /* tp_itemsize */ /* methods */ ! (destructor)islice_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 450,454 ---- 0, /* tp_itemsize */ /* methods */ ! (destructor)islice_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 467,477 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! islice_doc, /* tp_doc */ ! (traverseproc)islice_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)islice_getiter, /* tp_iter */ ! (iternextfunc)islice_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 467,477 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! islice_doc, /* tp_doc */ ! (traverseproc)islice_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)islice_getiter, /* tp_iter */ ! (iternextfunc)islice_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 590,598 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.starmap", /* tp_name */ ! sizeof(starmapobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)starmap_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 590,598 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.starmap", /* tp_name */ ! sizeof(starmapobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)starmap_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 611,621 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! starmap_doc, /* tp_doc */ ! (traverseproc)starmap_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)starmap_getiter, /* tp_iter */ ! (iternextfunc)starmap_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 611,621 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! starmap_doc, /* tp_doc */ ! (traverseproc)starmap_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)starmap_getiter, /* tp_iter */ ! (iternextfunc)starmap_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 628,632 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! starmap_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 628,632 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! starmap_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 784,789 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.imap", /* tp_name */ ! sizeof(imapobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ --- 784,789 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.imap", /* tp_name */ ! sizeof(imapobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ *************** *** 822,826 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! imap_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 822,826 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! imap_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 909,914 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.times", /* tp_name */ ! sizeof(timesobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ --- 909,914 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.times", /* tp_name */ ! sizeof(timesobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ *************** *** 930,940 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! times_doc, /* tp_doc */ (traverseproc)times_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)times_getiter, /* tp_iter */ ! (iternextfunc)times_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 930,940 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! times_doc, /* tp_doc */ (traverseproc)times_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)times_getiter, /* tp_iter */ ! (iternextfunc)times_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 958,962 **** PyObject *func; PyObject *it; - long invert; } ifilterobject; --- 958,961 ---- *************** *** 966,980 **** ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *func, *seq, *invert=NULL; PyObject *it; ifilterobject *lz; - long inv=0; ! if (!PyArg_UnpackTuple(args, "ifilter", 2, 3, &func, &seq, &invert)) return NULL; - if (invert != NULL && PyObject_IsTrue(invert)) - inv = 1; - /* Get iterator. */ it = PyObject_GetIter(seq); --- 965,975 ---- ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *func, *seq; PyObject *it; ifilterobject *lz; ! if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq)) return NULL; /* Get iterator. */ it = PyObject_GetIter(seq); *************** *** 991,995 **** lz->func = func; lz->it = it; - lz->invert = inv; return (PyObject *)lz; --- 986,989 ---- *************** *** 1047,1051 **** Py_DECREF(good); } ! if (ok ^ lz->invert) return item; Py_DECREF(item); --- 1041,1045 ---- Py_DECREF(good); } ! if (ok) return item; Py_DECREF(item); *************** *** 1061,1078 **** PyDoc_STRVAR(ifilter_doc, ! "ifilter(function or None, sequence [, invert]) --> ifilter object\n\ \n\ ! Return those items of sequence for which function(item) is true. If\n\ ! invert is set to True, return items for which function(item) if False.\n\ ! If function is None, return the items that are true (unless invert is set)."); PyTypeObject ifilter_type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.ifilter", /* tp_name */ ! sizeof(ifilterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)ifilter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 1055,1071 ---- PyDoc_STRVAR(ifilter_doc, ! "ifilter(function or None, sequence) --> ifilter object\n\ \n\ ! Return those items of sequence for which function(item) is true.\n\ ! If function is None, return the items that are true."); PyTypeObject ifilter_type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.ifilter", /* tp_name */ ! sizeof(ifilterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)ifilter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 1091,1101 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! ifilter_doc, /* tp_doc */ ! (traverseproc)ifilter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)ifilter_getiter, /* tp_iter */ ! (iternextfunc)ifilter_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 1084,1094 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! ifilter_doc, /* tp_doc */ ! (traverseproc)ifilter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)ifilter_getiter, /* tp_iter */ ! (iternextfunc)ifilter_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 1108,1112 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! ifilter_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 1101,1259 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! ifilter_new, /* tp_new */ ! PyObject_GC_Del, /* tp_free */ ! }; ! ! ! /* ifilterfalse object ************************************************************/ ! ! typedef struct { ! PyObject_HEAD ! PyObject *func; ! PyObject *it; ! } ifilterfalseobject; ! ! PyTypeObject ifilterfalse_type; ! ! static PyObject * ! ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) ! { ! PyObject *func, *seq, *invert=NULL; ! PyObject *it; ! ifilterfalseobject *lz; ! ! if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq)) ! return NULL; ! ! /* Get iterator. */ ! it = PyObject_GetIter(seq); ! if (it == NULL) ! return NULL; ! ! /* create ifilterfalseobject structure */ ! lz = (ifilterfalseobject *)type->tp_alloc(type, 0); ! if (lz == NULL) { ! Py_DECREF(it); ! return NULL; ! } ! Py_INCREF(func); ! lz->func = func; ! lz->it = it; ! ! return (PyObject *)lz; ! } ! ! static void ! ifilterfalse_dealloc(ifilterfalseobject *lz) ! { ! PyObject_GC_UnTrack(lz); ! Py_XDECREF(lz->func); ! Py_XDECREF(lz->it); ! lz->ob_type->tp_free(lz); ! } ! ! static int ! ifilterfalse_traverse(ifilterfalseobject *lz, visitproc visit, void *arg) ! { ! int err; ! ! if (lz->it) { ! err = visit(lz->it, arg); ! if (err) ! return err; ! } ! if (lz->func) { ! err = visit(lz->func, arg); ! if (err) ! return err; ! } ! return 0; ! } ! ! static PyObject * ! ifilterfalse_next(ifilterfalseobject *lz) ! { ! PyObject *item; ! long ok; ! ! for (;;) { ! item = PyIter_Next(lz->it); ! if (item == NULL) ! return NULL; ! ! if (lz->func == Py_None) { ! ok = PyObject_IsTrue(item); ! } else { ! PyObject *good; ! good = PyObject_CallFunctionObjArgs(lz->func, ! item, NULL); ! if (good == NULL) { ! Py_DECREF(item); ! return NULL; ! } ! ok = PyObject_IsTrue(good); ! Py_DECREF(good); ! } ! if (!ok) ! return item; ! Py_DECREF(item); ! } ! } ! ! static PyObject * ! ifilterfalse_getiter(PyObject *lz) ! { ! Py_INCREF(lz); ! return lz; ! } ! ! PyDoc_STRVAR(ifilterfalse_doc, ! "ifilterfalse(function or None, sequence) --> ifilterfalse object\n\ ! \n\ ! Return those items of sequence for which function(item) is false.\n\ ! If function is None, return the items that are false."); ! ! PyTypeObject ifilterfalse_type = { ! PyObject_HEAD_INIT(NULL) ! 0, /* ob_size */ ! "itertools.ifilterfalse", /* tp_name */ ! sizeof(ifilterfalseobject), /* tp_basicsize */ ! 0, /* tp_itemsize */ ! /* methods */ ! (destructor)ifilterfalse_dealloc, /* tp_dealloc */ ! 0, /* tp_print */ ! 0, /* tp_getattr */ ! 0, /* tp_setattr */ ! 0, /* tp_compare */ ! 0, /* tp_repr */ ! 0, /* tp_as_number */ ! 0, /* tp_as_sequence */ ! 0, /* tp_as_mapping */ ! 0, /* tp_hash */ ! 0, /* tp_call */ ! 0, /* tp_str */ ! PyObject_GenericGetAttr, /* tp_getattro */ ! 0, /* tp_setattro */ ! 0, /* tp_as_buffer */ ! Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | ! Py_TPFLAGS_BASETYPE, /* tp_flags */ ! ifilterfalse_doc, /* tp_doc */ ! (traverseproc)ifilterfalse_traverse, /* tp_traverse */ ! 0, /* tp_clear */ ! 0, /* tp_richcompare */ ! 0, /* tp_weaklistoffset */ ! (getiterfunc)ifilterfalse_getiter, /* tp_iter */ ! (iternextfunc)ifilterfalse_next, /* tp_iternext */ ! 0, /* tp_methods */ ! 0, /* tp_members */ ! 0, /* tp_getset */ ! 0, /* tp_base */ ! 0, /* tp_dict */ ! 0, /* tp_descr_get */ ! 0, /* tp_descr_set */ ! 0, /* tp_dictoffset */ ! 0, /* tp_init */ ! PyType_GenericAlloc, /* tp_alloc */ ! ifilterfalse_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 1162,1167 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.count", /* tp_name */ ! sizeof(countobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ --- 1309,1314 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.count", /* tp_name */ ! sizeof(countobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ *************** *** 1182,1192 **** 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ ! count_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)count_getiter, /* tp_iter */ ! (iternextfunc)count_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 1329,1339 ---- 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ ! count_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)count_getiter, /* tp_iter */ ! (iternextfunc)count_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 1350,1358 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.izip", /* tp_name */ ! sizeof(izipobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)izip_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 1497,1505 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.izip", /* tp_name */ ! sizeof(izipobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)izip_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 1371,1381 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! izip_doc, /* tp_doc */ (traverseproc)izip_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)izip_getiter, /* tp_iter */ ! (iternextfunc)izip_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 1518,1528 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! izip_doc, /* tp_doc */ (traverseproc)izip_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)izip_getiter, /* tp_iter */ ! (iternextfunc)izip_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 1388,1392 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! izip_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 1535,1539 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! izip_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 1459,1463 **** 0, /* tp_itemsize */ /* methods */ ! (destructor)repeat_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 1606,1610 ---- 0, /* tp_itemsize */ /* methods */ ! (destructor)repeat_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 1476,1486 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! repeat_doc, /* tp_doc */ ! (traverseproc)repeat_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)repeat_getiter, /* tp_iter */ ! (iternextfunc)repeat_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 1623,1633 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! repeat_doc, /* tp_doc */ ! (traverseproc)repeat_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)repeat_getiter, /* tp_iter */ ! (iternextfunc)repeat_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 1509,1514 **** Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ! ifilter(pred, seq, invert=False) --> elements of seq where\n\ ! pred(elem) is True (or False if invert is set)\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ seq[start:stop:step]\n\ --- 1656,1661 ---- Iterators terminating on the shortest input sequence:\n\ izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\ ! ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\ ! ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\ islice(seq, [start,] stop [, step]) --> elements from\n\ seq[start:stop:step]\n\ *************** *** 1524,1578 **** inititertools(void) { PyObject *m; ! m = Py_InitModule3("itertools", NULL, module_doc); ! ! PyModule_AddObject(m, "dropwhile", (PyObject *)&dropwhile_type); ! if (PyType_Ready(&dropwhile_type) < 0) ! return; ! Py_INCREF(&dropwhile_type); ! ! PyModule_AddObject(m, "takewhile", (PyObject *)&takewhile_type); ! if (PyType_Ready(&takewhile_type) < 0) ! return; ! Py_INCREF(&takewhile_type); ! ! PyModule_AddObject(m, "islice", (PyObject *)&islice_type); ! if (PyType_Ready(&islice_type) < 0) ! return; ! Py_INCREF(&islice_type); ! ! PyModule_AddObject(m, "starmap", (PyObject *)&starmap_type); ! if (PyType_Ready(&starmap_type) < 0) ! return; ! Py_INCREF(&starmap_type); ! ! PyModule_AddObject(m, "imap", (PyObject *)&imap_type); ! if (PyType_Ready(&imap_type) < 0) ! return; ! Py_INCREF(&imap_type); ! ! PyModule_AddObject(m, "times", (PyObject *)×_type); ! if (PyType_Ready(×_type) < 0) ! return; ! Py_INCREF(×_type); ! ! if (PyType_Ready(&ifilter_type) < 0) ! return; ! Py_INCREF(&ifilter_type); ! PyModule_AddObject(m, "ifilter", (PyObject *)&ifilter_type); ! ! if (PyType_Ready(&count_type) < 0) ! return; ! Py_INCREF(&count_type); ! PyModule_AddObject(m, "count", (PyObject *)&count_type); ! if (PyType_Ready(&izip_type) < 0) ! return; ! Py_INCREF(&izip_type); ! PyModule_AddObject(m, "izip", (PyObject *)&izip_type); ! if (PyType_Ready(&repeat_type) < 0) ! return; ! Py_INCREF(&repeat_type); ! PyModule_AddObject(m, "repeat", (PyObject *)&repeat_type); } --- 1671,1702 ---- inititertools(void) { + int i; PyObject *m; ! char *name; ! PyTypeObject *typelist[] = { ! &dropwhile_type, ! &takewhile_type, ! &islice_type, ! &starmap_type, ! &imap_type, ! ×_type, ! &ifilter_type, ! &ifilterfalse_type, ! &count_type, ! &izip_type, ! &repeat_type, ! NULL ! }; ! m = Py_InitModule3("itertools", NULL, module_doc); ! for (i=0 ; typelist[i] != NULL ; i++) { ! if (PyType_Ready(typelist[i]) < 0) ! return; ! name = strchr(typelist[i]->tp_name, '.') + 1; ! if (name == NULL) ! return; ! Py_INCREF(typelist[i]); ! PyModule_AddObject(m, name, (PyObject *)typelist[i]); ! } } From skip@pobox.com Sun Feb 9 16:51:37 2003 From: skip@pobox.com (Skip Montanaro) Date: Sun, 9 Feb 2003 10:51:37 -0600 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.17,1.18 pep-0308.txt,1.8,1.9 In-Reply-To: References: Message-ID: <15942.34585.704120.158988@montanaro.dyndns.org> >>>>> "goodger" == goodger writes: goodger> Log Message: goodger> fixed status ... goodger> Index: pep-0308.txt ... [ Active -> Draft ] Judging from the traffic on c.l.py surrounding this PEP, I'd just it's still "active". ;-) Skip From gvanrossum@users.sourceforge.net Sun Feb 9 17:11:14 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 09 Feb 2003 09:11:14 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv26513 Modified Files: pep-0307.txt Log Message: Fix grammar. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** pep-0307.txt 9 Feb 2003 05:12:54 -0000 1.18 --- pep-0307.txt 9 Feb 2003 17:11:10 -0000 1.19 *************** *** 175,183 **** state Additional state. If this is not None, the state is ! pickled, and obj.__setstate__(state) will called when ! unpickling. If no __setstate__ method is defined, a ! default implementation is provided, which assumes ! that state is a dictionary mapping instance variable ! names to their values, and calls obj.__dict__.update(state) or "for k, v in state.items(): obj[k] = v", if update() call fails. --- 175,183 ---- state Additional state. If this is not None, the state is ! pickled, and obj.__setstate__(state) will be called ! when unpickling. If no __setstate__ method is ! defined, a default implementation is provided, which ! assumes that state is a dictionary mapping instance ! variable names to their values, and calls obj.__dict__.update(state) or "for k, v in state.items(): obj[k] = v", if update() call fails. From gvanrossum@users.sourceforge.net Sun Feb 9 17:16:49 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 09 Feb 2003 09:16:49 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28445 Modified Files: pep-0307.txt Log Message: Rename 'proto' keyword arg to 'protocol' . Greg Ward's suggestion. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** pep-0307.txt 9 Feb 2003 17:11:10 -0000 1.19 --- pep-0307.txt 9 Feb 2003 17:16:45 -0000 1.20 *************** *** 81,85 **** to take a positional argument named 'bin' which was a flag, defaulting to 0, indicating binary mode. This argument is renamed ! to 'proto' and now gives the protocol number, still defaulting to 0. It so happens that passing 2 for the 'bin' argument in previous --- 81,86 ---- to take a positional argument named 'bin' which was a flag, defaulting to 0, indicating binary mode. This argument is renamed ! to 'protocol' and now gives the protocol number, still defaulting ! to 0. It so happens that passing 2 for the 'bin' argument in previous From gvanrossum@users.sourceforge.net Sun Feb 9 17:18:47 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 09 Feb 2003 09:18:47 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29388 Modified Files: itertoolsmodule.c Log Message: Remove unused variable. Index: itertoolsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/itertoolsmodule.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** itertoolsmodule.c 9 Feb 2003 06:40:58 -0000 1.4 --- itertoolsmodule.c 9 Feb 2003 17:18:42 -0000 1.5 *************** *** 1119,1123 **** ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *func, *seq, *invert=NULL; PyObject *it; ifilterfalseobject *lz; --- 1119,1123 ---- ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! PyObject *func, *seq; PyObject *it; ifilterfalseobject *lz; From gvanrossum@users.sourceforge.net Sun Feb 9 17:19:46 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 09 Feb 2003 09:19:46 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.148,1.149 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv29830 Modified Files: pickle.py Log Message: Rename 'proto' keyword arg to 'protocol' . Greg Ward's suggestion. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.148 retrieving revision 1.149 diff -C2 -d -r1.148 -r1.149 *** pickle.py 6 Feb 2003 22:57:00 -0000 1.148 --- pickle.py 9 Feb 2003 17:19:41 -0000 1.149 *************** *** 168,176 **** class Pickler: ! def __init__(self, file, proto=None, bin=None): """This takes a file-like object for writing a pickle data stream. ! The optional proto argument tells the pickler to use the given ! protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text --- 168,176 ---- class Pickler: ! def __init__(self, file, protocol=None, bin=None): """This takes a file-like object for writing a pickle data stream. ! The optional protocol argument tells the pickler to use the ! given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text *************** *** 192,211 **** """ ! if proto is not None and bin is not None: ! raise ValueError, "can't specify both 'proto' and 'bin' arguments" if bin is not None: warnings.warn("The 'bin' argument to Pickler() is deprecated", PendingDeprecationWarning) ! proto = bin ! if proto is None: ! proto = 0 ! if proto < 0: ! proto = 2 ! elif proto not in (0, 1, 2): raise ValueError, "pickle protocol must be 0, 1 or 2" self.write = file.write self.memo = {} ! self.proto = int(proto) ! self.bin = proto >= 1 self.fast = 0 --- 192,211 ---- """ ! if protocol is not None and bin is not None: ! raise ValueError, "can't specify both 'protocol' and 'bin'" if bin is not None: warnings.warn("The 'bin' argument to Pickler() is deprecated", PendingDeprecationWarning) ! protocol = bin ! if protocol is None: ! protocol = 0 ! if protocol < 0: ! protocol = 2 ! elif protocol not in (0, 1, 2): raise ValueError, "pickle protocol must be 0, 1 or 2" self.write = file.write self.memo = {} ! self.proto = int(protocol) ! self.bin = protocol >= 1 self.fast = 0 *************** *** 1370,1379 **** from StringIO import StringIO ! def dump(obj, file, proto=None, bin=None): ! Pickler(file, proto, bin).dump(obj) ! def dumps(obj, proto=None, bin=None): file = StringIO() ! Pickler(file, proto, bin).dump(obj) return file.getvalue() --- 1370,1379 ---- from StringIO import StringIO ! def dump(obj, file, protocol=None, bin=None): ! Pickler(file, protocol, bin).dump(obj) ! def dumps(obj, protocol=None, bin=None): file = StringIO() ! Pickler(file, protocol, bin).dump(obj) return file.getvalue() From gvanrossum@users.sourceforge.net Sun Feb 9 17:19:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 09 Feb 2003 09:19:23 -0800 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.76,2.77 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29630 Modified Files: parsermodule.c Log Message: Remove unused variable. Index: parsermodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/parsermodule.c,v retrieving revision 2.76 retrieving revision 2.77 diff -C2 -d -r2.76 -r2.77 *** parsermodule.c 8 Feb 2003 18:05:10 -0000 2.76 --- parsermodule.c 9 Feb 2003 17:19:18 -0000 2.77 *************** *** 773,777 **** int line_num = 0; PyObject *encoding = NULL; - PyObject *tmpTuple = NULL; if (num == encoding_decl) { --- 773,776 ---- From goodger@python.org Sun Feb 9 20:35:28 2003 From: goodger@python.org (David Goodger) Date: Sun, 09 Feb 2003 15:35:28 -0500 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.17,1.18 pep-0308.txt,1.8,1.9 In-Reply-To: <15942.34585.704120.158988@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: >>>>>> "goodger" == goodger writes: > goodger> Log Message: > goodger> fixed status > ... > goodger> Index: pep-0308.txt > ... > [ Active -> Draft ] > > Judging from the traffic on c.l.py surrounding this PEP, I'd just it's still > "active". ;-) "Active" doesn't apply to standards track PEPs, no matter how active the discussion ;-). It's procedural formality. According to PEP 1: Some Informational PEPs may also have a status of "Active" if they are never meant to be completed. E.g. PEP 1. PEPs that *are* meant to be completed go Draft -> Accepted -> Final (or -> Rejected if unsuccessful), after which they become historical record. -- David Goodger Python Enhancement Proposal (PEP) Editor (Please cc: all PEP correspondence to .) From jvr@users.sourceforge.net Sun Feb 9 20:38:50 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sun, 09 Feb 2003 12:38:50 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv21078/Lib/test Modified Files: test_builtin.py Log Message: patch 680474 that fixes bug 679880: compile/eval/exec refused utf-8 bom mark. Added unit test. Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** test_builtin.py 4 Feb 2003 20:24:45 -0000 1.9 --- test_builtin.py 9 Feb 2003 20:38:47 -0000 1.10 *************** *** 191,194 **** --- 191,196 ---- def test_compile(self): compile('print 1\n', '', 'exec') + bom = '\xef\xbb\xbf' + compile(bom + 'print 1\n', '', 'exec') self.assertRaises(TypeError, compile) self.assertRaises(ValueError, compile, 'print 42\n', '', 'badmode') *************** *** 306,309 **** --- 308,313 ---- self.assertEqual(eval(unicode('b'), globals, locals), 200) self.assertEqual(eval(unicode('c'), globals, locals), 300) + bom = '\xef\xbb\xbf' + self.assertEqual(eval(bom + 'a', globals, locals), 1) self.assertRaises(TypeError, eval) self.assertRaises(TypeError, eval, ()) From jvr@users.sourceforge.net Sun Feb 9 20:38:51 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sun, 09 Feb 2003 12:38:51 -0800 Subject: [Python-checkins] python/dist/src/Parser tokenizer.c,2.71,2.72 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv21078/Parser Modified Files: tokenizer.c Log Message: patch 680474 that fixes bug 679880: compile/eval/exec refused utf-8 bom mark. Added unit test. Index: tokenizer.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/tokenizer.c,v retrieving revision 2.71 retrieving revision 2.72 diff -C2 -d -r2.71 -r2.72 *** tokenizer.c 14 Jan 2003 23:15:22 -0000 2.71 --- tokenizer.c 9 Feb 2003 20:38:48 -0000 2.72 *************** *** 507,511 **** static int buf_getc(struct tok_state *tok) { ! return *tok->str++; } --- 507,511 ---- static int buf_getc(struct tok_state *tok) { ! return Py_CHARMASK(*tok->str++); } *************** *** 514,518 **** static void buf_ungetc(int c, struct tok_state *tok) { tok->str--; ! assert(*tok->str == c); /* tok->cur may point to read-only segment */ } --- 514,518 ---- static void buf_ungetc(int c, struct tok_state *tok) { tok->str--; ! assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } From goodger@users.sourceforge.net Sun Feb 9 20:47:39 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Sun, 09 Feb 2003 12:47:39 -0800 Subject: [Python-checkins] python/nondist/peps docutils.conf,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv27494 Modified Files: docutils.conf Log Message: updated stylesheet setting Index: docutils.conf =================================================================== RCS file: /cvsroot/python/python/nondist/peps/docutils.conf,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** docutils.conf 8 Feb 2003 22:23:42 -0000 1.3 --- docutils.conf 9 Feb 2003 20:47:36 -0000 1.4 *************** *** 14,16 **** # Standalone HTML: ! stylesheet: ../docutils.css --- 14,16 ---- # Standalone HTML: ! stylesheet: ../css/docutils.css From jackjansen@users.sourceforge.net Sun Feb 9 23:10:22 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 09 Feb 2003 15:10:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv20116 Added Files: pimp.py Log Message: Strawman for a Package Install Manager for Python. It isn't CPAN yet, but at less than 500 lines it already manages to test whether Numeric is installed, and can install it if it isn't, including any prerequisites. --- NEW FILE: pimp.py --- import sys import os import urllib import urlparse import plistlib import distutils.util _scriptExc_NotInstalled = "pimp._scriptExc_NotInstalled" _scriptExc_OldInstalled = "pimp._scriptExc_OldInstalled" _scriptExc_BadInstalled = "pimp._scriptExc_BadInstalled" NO_EXECUTE=0 DEFAULT_FLAVORORDER=['source', 'binary'] DEFAULT_DOWNLOADDIR='/tmp' DEFAULT_BUILDDIR='/tmp' DEFAULT_INSTALLDIR=os.path.join(sys.prefix, "Lib", "site-packages") DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() ARCHIVE_FORMATS = [ (".tar.Z", "zcat \"%s\" | tar xf -"), (".taz", "zcat \"%s\" | tar xf -"), (".tar.gz", "zcat \"%s\" | tar xf -"), (".tgz", "zcat \"%s\" | tar xf -"), (".tar.bz", "bzcat \"%s\" | tar xf -"), ] class PimpPreferences: def __init__(self, flavorOrder=None, downloadDir=None, buildDir=None, installDir=None, pimpDatabase=None): if not flavorOrder: flavorOrder = DEFAULT_FLAVORORDER if not downloadDir: downloadDir = DEFAULT_DOWNLOADDIR if not buildDir: buildDir = DEFAULT_BUILDDIR if not installDir: installDir = DEFAULT_INSTALLDIR if not pimpDatabase: pimpDatabase = DEFAULT_PIMPDATABASE self.flavorOrder = flavorOrder self.downloadDir = downloadDir self.buildDir = buildDir self.installDir = installDir self.pimpDatabase = pimpDatabase def check(self): rv = "" RWX_OK = os.R_OK|os.W_OK|os.X_OK if not os.path.exists(self.downloadDir): rv += "Warning: Download directory \"%s\" does not exist\n" % self.downloadDir elif not os.access(self.downloadDir, RWX_OK): rv += "Warning: Download directory \"%s\" is not writable or not readable\n" % self.downloadDir if not os.path.exists(self.buildDir): rv += "Warning: Build directory \"%s\" does not exist\n" % self.buildDir elif not os.access(self.buildDir, RWX_OK): rv += "Warning: Build directory \"%s\" is not writable or not readable\n" % self.buildDir if not os.path.exists(self.installDir): rv += "Warning: Install directory \"%s\" does not exist\n" % self.installDir elif not os.access(self.installDir, RWX_OK): rv += "Warning: Install directory \"%s\" is not writable or not readable\n" % self.installDir else: installDir = os.path.realpath(self.installDir) for p in sys.path: try: realpath = os.path.realpath(p) except: pass if installDir == realpath: break else: rv += "Warning: Install directory \"%s\" is not on sys.path\n" % self.installDir return rv def compareFlavors(self, left, right): if left in self.flavorOrder: if right in self.flavorOrder: return cmp(self.flavorOrder.index(left), self.flavorOrder.index(right)) return -1 if right in self.flavorOrder: return 1 return cmp(left, right) class PimpDatabase: def __init__(self, prefs): self._packages = [] self.preferences = prefs self._urllist = [] self._version = "" self._maintainer = "" self._description = "" def appendURL(self, url, included=0): if url in self._urllist: return self._urllist.append(url) fp = urllib.urlopen(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc if not included: self._version = dict.get('version', '0.1') self._maintainer = dict.get('maintainer', '') self._description = dict.get('description', '') self.appendPackages(dict['packages']) others = dict.get('include', []) for url in others: self.appendURL(url, included=1) def appendPackages(self, packages): for p in packages: pkg = PimpPackage(self, **dict(p)) self._packages.append(pkg) def list(self): return self._packages def listnames(self): rv = [] for pkg in self._packages: rv.append(_fmtpackagename(pkg)) return rv def dump(self, pathOrFile): packages = [] for pkg in self._packages: packages.append(pkg.dump()) dict = { 'version': self._version, 'maintainer': self._maintainer, 'description': self._description, 'packages': packages } plist = plistlib.Plist(**dict) plist.write(pathOrFile) def find(self, ident): if type(ident) == str: # Remove ( and ) for pseudo-packages if ident[0] == '(' and ident[-1] == ')': ident = ident[1:-1] # Split into name-version-flavor fields = ident.split('-') if len(fields) < 1 or len(fields) > 3: return None name = fields[0] if len(fields) > 1: version = fields[1] else: version = None if len(fields) > 2: flavor = fields[2] else: flavor = None else: name = ident['name'] version = ident.get('version') flavor = ident.get('flavor') found = None for p in self._packages: if name == p.name and \ (not version or version == p.version) and \ (not flavor or flavor == p.flavor): if not found or found < p: found = p return found class PimpPackage: def __init__(self, db, name, version=None, flavor=None, description=None, longdesc=None, downloadURL=None, installTest=None, prerequisites=None): self._db = db self.name = name self.version = version self.flavor = flavor self.description = description self.longdesc = longdesc self.downloadURL = downloadURL self._installTest = installTest self._prerequisites = prerequisites def dump(self): dict = { 'name': self.name, } if self.version: dict['version'] = self.version if self.flavor: dict['flavor'] = self.flavor if self.description: dict['description'] = self.description if self.longdesc: dict['longdesc'] = self.longdesc if self.downloadURL: dict['downloadURL'] = self.downloadURL if self._installTest: dict['installTest'] = self._installTest if self._prerequisites: dict['prerequisites'] = self._prerequisites return dict def __cmp__(self, other): if not isinstance(other, PimpPackage): return cmp(id(self), id(other)) if self.name != other.name: return cmp(self.name, other.name) if self.version != other.version: return cmp(self.version, other.version) return self._db.preferences.compareFlavors(self.flavor, other.flavor) def installed(self): namespace = { "NotInstalled": _scriptExc_NotInstalled, "OldInstalled": _scriptExc_OldInstalled, "BadInstalled": _scriptExc_BadInstalled, "os": os, "sys": sys, } installTest = self._installTest.strip() + '\n' try: exec installTest in namespace except ImportError, arg: return "no", str(arg) except _scriptExc_NotInstalled, arg: return "no", str(arg) except _scriptExc_OldInstalled, arg: return "old", str(arg) except _scriptExc_BadInstalled, arg: return "bad", str(arg) except: print 'TEST:', repr(self._installTest) return "bad", "Package install test got exception" return "yes", "" def prerequisites(self): rv = [] if not self.downloadURL: return [(None, "This package needs to be installed manually")] if not self._prerequisites: return [] for item in self._prerequisites: if type(item) == str: pkg = None descr = str(item) else: pkg = self._db.find(item) if not pkg: descr = "Requires unknown %s"%_fmtpackagename(item) else: descr = pkg.description rv.append((pkg, descr)) return rv def _cmd(self, output, dir, *cmditems): cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: output.write("+ %s\n" % cmd) if NO_EXECUTE: return 0 fp = os.popen(cmd, "r") while 1: line = fp.readline() if not line: break if output: output.write(line) rv = fp.close() return rv def downloadSinglePackage(self, output): scheme, loc, path, query, frag = urlparse.urlsplit(self.downloadURL) path = urllib.url2pathname(path) filename = os.path.split(path)[1] self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) if self._cmd(output, self._db.preferences.downloadDir, "curl", "--output", self.archiveFilename, self.downloadURL): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" def unpackSinglePackage(self, output): filename = os.path.split(self.archiveFilename)[1] for ext, cmd in ARCHIVE_FORMATS: if filename[-len(ext):] == ext: break else: return "unknown extension for archive file: %s" % filename basename = filename[:-len(ext)] cmd = cmd % self.archiveFilename self._buildDirname = os.path.join(self._db.preferences.buildDir, basename) if self._cmd(output, self._db.preferences.buildDir, cmd): return "unpack command failed" setupname = os.path.join(self._buildDirname, "setup.py") if not os.path.exists(setupname) and not NO_EXECUTE: return "no setup.py found after unpack of archive" def installSinglePackage(self, output): if not self.downloadURL: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = self.downloadSinglePackage(output) if msg: return "download %s: %s" % (_fmtpackagename(self), msg) msg = self.unpackSinglePackage(output) if msg: return "unpack %s: %s" % (_fmtpackagename(self), msg) if self._cmd(output, self._buildDirname, sys.executable, "setup.py install"): return "install %s: running \"setup.py install\" failed" % _fmtpackagename(self) return None class PimpInstaller: def __init__(self, db): self._todo = [] self._db = db self._curtodo = [] self._curmessages = [] def __contains__(self, package): return package in self._todo def _addPackages(self, packages): for package in packages: if not package in self._todo: self._todo.insert(0, package) def _prepareInstall(self, package, force=0, recursive=1): if not force: status, message = package.installed() if status == "yes": return if package in self._todo or package in self._curtodo: return self._curtodo.insert(0, package) if not recursive: return prereqs = package.prerequisites() for pkg, descr in prereqs: if pkg: self._prepareInstall(pkg, force, recursive) else: self._curmessages.append("Requires: %s" % descr) def prepareInstall(self, package, force=0, recursive=1): self._curtodo = [] self._curmessages = [] self._prepareInstall(package, force, recursive) rv = self._curtodo, self._curmessages self._curtodo = [] self._curmessages = [] return rv def install(self, packages, output): self._addPackages(packages) status = [] for pkg in self._todo: msg = pkg.installSinglePackage(output) if msg: status.append(msg) return status def _fmtpackagename(dict): if isinstance(dict, PimpPackage): dict = dict.dump() rv = dict['name'] if dict.has_key('version'): rv = rv + '-%s' % dict['version'] if dict.has_key('flavor'): rv = rv + '-%s' % dict['flavor'] if not dict.get('downloadURL'): # Pseudo-package, show in parentheses rv = '(%s)' % rv return rv def _run(mode, verbose, force, args): prefs = PimpPreferences() prefs.check() db = PimpDatabase(prefs) db.appendURL(prefs.pimpDatabase) if mode =='list': if not args: args = db.listnames() print "%-20.20s\t%s" % ("Package", "Description") print for pkgname in args: pkg = db.find(pkgname) if pkg: description = pkg.description pkgname = _fmtpackagename(pkg) else: description = 'Error: no such package' print "%-20.20s\t%s" % (pkgname, description) if verbose: print "\tHome page:\t", pkg.longdesc print "\tDownload URL:\t", pkg.downloadURL if mode =='status': if not args: args = db.listnames() print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message") print for pkgname in args: pkg = db.find(pkgname) if pkg: status, msg = pkg.installed() pkgname = _fmtpackagename(pkg) else: status = 'error' msg = 'No such package' print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg) if verbose and status == "no": prereq = pkg.prerequisites() for pkg, msg in prereq: if not pkg: pkg = '' else: pkg = _fmtpackagename(pkg) print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg) elif mode == 'install': if not args: print 'Please specify packages to install' sys.exit(1) inst = PimpInstaller(db) for pkgname in args: pkg = db.find(pkgname) if not pkg: print '%s: No such package' % pkgname continue list, messages = inst.prepareInstall(pkg, force) if messages and not force: print "%s: Not installed:" % pkgname for m in messages: print "\t", m else: if verbose: output = sys.stdout else: output = None messages = inst.install(list, output) if messages: print "%s: Not installed:" % pkgname for m in messages: print "\t", m def main(): import getopt def _help(): print "Usage: pimp [-v] -s [package ...] List installed status" print " pimp [-v] -l [package ...] Show package information" print " pimp [-vf] -i package ... Install packages" print "Options:" print " -v Verbose" print " -f Force installation" sys.exit(1) try: opts, args = getopt.getopt(sys.argv[1:], "slifv") except getopt.Error: _help() if not opts and not args: _help() mode = None force = 0 verbose = 0 for o, a in opts: if o == '-s': if mode: _help() mode = 'status' if o == '-l': if mode: _help() mode = 'list' if o == '-L': if mode: _help() mode = 'longlist' if o == '-i': mode = 'install' if o == '-f': force = 1 if o == '-v': verbose = 1 if not mode: _help() _run(mode, verbose, force, args) if __name__ == '__main__': main() From doerwalter@users.sourceforge.net Sun Feb 9 23:42:59 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Sun, 09 Feb 2003 15:42:59 -0800 Subject: [Python-checkins] python/dist/src/Objects unicodeobject.c,2.180,2.181 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv451/Objects Modified Files: unicodeobject.c Log Message: Fix two refcounting bugs Index: unicodeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/unicodeobject.c,v retrieving revision 2.180 retrieving revision 2.181 diff -C2 -d -r2.180 -r2.181 *** unicodeobject.c 31 Jan 2003 17:19:08 -0000 2.180 --- unicodeobject.c 9 Feb 2003 23:42:56 -0000 2.181 *************** *** 3257,3260 **** --- 3257,3261 ---- goto onError; } + Py_XDECREF(x); if (x!=Py_None) /* it worked => adjust input pointer */ ++p; *************** *** 3269,3273 **** const Py_UNICODE *coll; - Py_XDECREF(x); /* find all untranslatable characters */ while (collend < endp) { --- 3270,3273 ---- *************** *** 5399,5404 **** return NULL; str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2); ! if (str2 == NULL) return NULL; result = replace(self, str1, str2, maxcount); --- 5399,5406 ---- return NULL; str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2); ! if (str2 == NULL) { ! Py_DECREF(str1); return NULL; + } result = replace(self, str1, str2, maxcount); From montanaro@users.sourceforge.net Mon Feb 10 00:05:17 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 09 Feb 2003 16:05:17 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv7869 Modified Files: _csv.c Log Message: tweak some docstrings Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** _csv.c 9 Feb 2003 00:59:56 -0000 1.22 --- _csv.c 10 Feb 2003 00:05:14 -0000 1.23 *************** *** 1206,1218 **** PyDoc_STRVAR(csv_list_dialects_doc, " names = csv.list_dialects()"); PyDoc_STRVAR(csv_get_dialect_doc, ! " dialect = csv.get_dialects(name)"); PyDoc_STRVAR(csv_register_dialect_doc, " dialect = csv.register_dialect(name, dialect)"); PyDoc_STRVAR(csv_unregister_dialect_doc, " csv.unregister_dialect(name)"); --- 1206,1222 ---- PyDoc_STRVAR(csv_list_dialects_doc, + "Return a list of all know dialect names.\n" " names = csv.list_dialects()"); PyDoc_STRVAR(csv_get_dialect_doc, ! "Return the dialect instance associated with name.\n" ! " dialect = csv.get_dialect(name)"); PyDoc_STRVAR(csv_register_dialect_doc, + "Create a mapping from a string name to a dialect class.\n" " dialect = csv.register_dialect(name, dialect)"); PyDoc_STRVAR(csv_unregister_dialect_doc, + "Delete the name/dialect mapping associated with a string name.\n" " csv.unregister_dialect(name)"); From nnorwitz@users.sourceforge.net Mon Feb 10 01:08:52 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:08:52 -0800 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.77,2.78 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv28248/Modules Modified Files: parsermodule.c Log Message: Remove duplicate code introduced by fixing bug #678518 Index: parsermodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/parsermodule.c,v retrieving revision 2.77 retrieving revision 2.78 diff -C2 -d -r2.77 -r2.78 *** parsermodule.c 9 Feb 2003 17:19:18 -0000 2.77 --- parsermodule.c 10 Feb 2003 01:08:50 -0000 2.78 *************** *** 1720,1726 **** err_string("illegal global statement"); - if (!res && !PyErr_Occurred()) - err_string("illegal global statement"); - if (res) res = (validate_name(CHILD(tree, 0), "global") --- 1720,1723 ---- From nnorwitz@users.sourceforge.net Mon Feb 10 01:09:52 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:09:52 -0800 Subject: [Python-checkins] python/dist/src/Misc ACKS,1.226,1.227 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv28468/Misc Modified Files: ACKS Log Message: Alphabetize some names Add Grant Olson for patch provided to fix bug #678518 Index: ACKS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/ACKS,v retrieving revision 1.226 retrieving revision 1.227 diff -C2 -d -r1.226 -r1.227 *** ACKS 3 Feb 2003 20:45:52 -0000 1.226 --- ACKS 10 Feb 2003 01:09:49 -0000 1.227 *************** *** 381,393 **** Joe Norton Neal Norwitz - Jeffrey Ollie Nigel O'Brian Kevin O'Connor Tim O'Malley Pascal Oberndoerfer ! Denis S. Otkidach Piet van Oostrum Jason Orendorff Douglas Orr Russel Owen Todd R. Palmer --- 381,394 ---- Joe Norton Neal Norwitz Nigel O'Brian Kevin O'Connor Tim O'Malley Pascal Oberndoerfer ! Jeffrey Ollie ! Grant Olson Piet van Oostrum Jason Orendorff Douglas Orr + Denis S. Otkidach Russel Owen Todd R. Palmer From nnorwitz@users.sourceforge.net Mon Feb 10 01:54:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:54:08 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_parser.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv8407/Lib/test Modified Files: test_parser.py Log Message: Add tests and news entry about parser errors from bug #678518. Index: test_parser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_parser.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** test_parser.py 29 Jan 2003 14:20:23 -0000 1.14 --- test_parser.py 10 Feb 2003 01:54:06 -0000 1.15 *************** *** 135,138 **** --- 135,145 ---- self.check_suite("import sys, math as my_math") + def test_pep263(self): + self.check_suite("# -*- coding: iso-8859-1 -*-\n" + "pass\n") + + def test_assert(self): + self.check_suite("assert alo < ahi and blo < bhi\n") + # # Second, we take *invalid* trees and make sure we get ParserError *************** *** 356,359 **** --- 363,376 ---- self.check_bad_tree(tree, "a $= b") + def test_malformed_global(self): + #doesn't have global keyword in ast + tree = (257, + (264, + (265, + (266, + (282, (1, 'foo'))), (4, ''))), + (4, ''), + (0, '')) + self.check_bad_tree(tree, "malformed global ast") def test_main(): From nnorwitz@users.sourceforge.net Mon Feb 10 01:54:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:54:08 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.646,1.647 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv8407/Misc Modified Files: NEWS Log Message: Add tests and news entry about parser errors from bug #678518. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.646 retrieving revision 1.647 diff -C2 -d -r1.646 -r1.647 *** NEWS 7 Feb 2003 22:50:27 -0000 1.646 --- NEWS 10 Feb 2003 01:54:05 -0000 1.647 *************** *** 43,46 **** --- 43,48 ---- ----------------- + - Fix some bugs in the parser module. SF bug #678518. + - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrote the From nnorwitz@users.sourceforge.net Mon Feb 10 01:57:53 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:57:53 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.58,1.337.2.4.2.59 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv9503a/Misc Modified Files: Tag: release22-maint NEWS Log Message: Partial backport for changes to fix SF bug #678518 (assert & global). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.58 retrieving revision 1.337.2.4.2.59 diff -C2 -d -r1.337.2.4.2.58 -r1.337.2.4.2.59 *** NEWS 7 Feb 2003 15:59:28 -0000 1.337.2.4.2.58 --- NEWS 10 Feb 2003 01:57:50 -0000 1.337.2.4.2.59 *************** *** 3,6 **** --- 3,8 ---- ============================ + - SF bug #678518: fix some bugs in the parser module. + - Bastion.py and rexec.py are disabled. These modules are not safe in Python 2.2. or 2.3. From nnorwitz@users.sourceforge.net Mon Feb 10 01:57:53 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:57:53 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_parser.py,1.10.12.1,1.10.12.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv9503a/Lib/test Modified Files: Tag: release22-maint test_parser.py Log Message: Partial backport for changes to fix SF bug #678518 (assert & global). Index: test_parser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_parser.py,v retrieving revision 1.10.12.1 retrieving revision 1.10.12.2 diff -C2 -d -r1.10.12.1 -r1.10.12.2 *** test_parser.py 2 Feb 2003 19:34:40 -0000 1.10.12.1 --- test_parser.py 10 Feb 2003 01:57:51 -0000 1.10.12.2 *************** *** 138,141 **** --- 138,144 ---- self.check_suite("import sys, math as my_math") + def test_assert(self): + self.check_suite("assert alo < ahi and blo < bhi\n") + # # Second, we take *invalid* trees and make sure we get ParserError *************** *** 358,361 **** --- 361,374 ---- self.check_bad_tree(tree, "a $= b") + def test_malformed_global(self): + #doesn't have global keyword in ast + tree = (257, + (264, + (265, + (266, + (282, (1, 'foo'))), (4, ''))), + (4, ''), + (0, '')) + self.check_bad_tree(tree, "malformed global ast") def test_main(): From nnorwitz@users.sourceforge.net Mon Feb 10 01:57:53 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 17:57:53 -0800 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.68.6.1,2.68.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9503a/Modules Modified Files: Tag: release22-maint parsermodule.c Log Message: Partial backport for changes to fix SF bug #678518 (assert & global). Index: parsermodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/parsermodule.c,v retrieving revision 2.68.6.1 retrieving revision 2.68.6.2 diff -C2 -d -r2.68.6.1 -r2.68.6.2 *** parsermodule.c 2 Feb 2003 19:34:14 -0000 2.68.6.1 --- parsermodule.c 10 Feb 2003 01:57:51 -0000 2.68.6.2 *************** *** 1693,1696 **** --- 1693,1699 ---- && is_even(nch) && (nch >= 2)); + if (!res && !PyErr_Occurred()) + err_string("illegal global statement"); + if (res) res = (validate_name(CHILD(tree, 0), "global") *************** *** 1740,1745 **** int res = (validate_ntype(tree, assert_stmt) && ((nch == 2) || (nch == 4)) ! && (validate_name(CHILD(tree, 0), "__assert__") || ! validate_name(CHILD(tree, 0), "assert")) && validate_test(CHILD(tree, 1))); --- 1743,1747 ---- int res = (validate_ntype(tree, assert_stmt) && ((nch == 2) || (nch == 4)) ! && (validate_name(CHILD(tree, 0), "assert")) && validate_test(CHILD(tree, 1))); From nnorwitz@users.sourceforge.net Mon Feb 10 02:12:45 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 18:12:45 -0800 Subject: [Python-checkins] python/dist/src/Objects intobject.c,2.100,2.101 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv13524/Objects Modified Files: intobject.c Log Message: Fix SF bug #683467, 'int' ability to generate longs not inherited When subclassing from an int but not overriding __new__, long values were not converted properly. Try to convert longs into an int. Index: intobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/intobject.c,v retrieving revision 2.100 retrieving revision 2.101 diff -C2 -d -r2.100 -r2.101 *** intobject.c 29 Jan 2003 17:58:45 -0000 2.100 --- intobject.c 10 Feb 2003 02:12:42 -0000 2.101 *************** *** 837,840 **** --- 837,841 ---- { PyObject *tmp, *new; + long ival; assert(PyType_IsSubtype(type, &PyInt_Type)); *************** *** 842,850 **** if (tmp == NULL) return NULL; ! assert(PyInt_Check(tmp)); new = type->tp_alloc(type, 0); if (new == NULL) return NULL; ! ((PyIntObject *)new)->ob_ival = ((PyIntObject *)tmp)->ob_ival; Py_DECREF(tmp); return new; --- 843,864 ---- if (tmp == NULL) return NULL; ! if (!PyInt_Check(tmp)) { ! if (!PyLong_Check(tmp)) { ! PyErr_SetString(PyExc_ValueError, ! "value must convertable to an int"); ! return NULL; ! } ! ival = PyLong_AsLong(tmp); ! if (ival == -1 && PyErr_Occurred()) ! return NULL; ! ! } else { ! ival = ((PyIntObject *)tmp)->ob_ival; ! } ! new = type->tp_alloc(type, 0); if (new == NULL) return NULL; ! ((PyIntObject *)new)->ob_ival = ival; Py_DECREF(tmp); return new; From nnorwitz@users.sourceforge.net Mon Feb 10 02:12:45 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 18:12:45 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.178,1.179 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv13524/Lib/test Modified Files: test_descr.py Log Message: Fix SF bug #683467, 'int' ability to generate longs not inherited When subclassing from an int but not overriding __new__, long values were not converted properly. Try to convert longs into an int. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.178 retrieving revision 1.179 diff -C2 -d -r1.178 -r1.179 *** test_descr.py 7 Feb 2003 14:59:13 -0000 1.178 --- test_descr.py 10 Feb 2003 02:12:43 -0000 1.179 *************** *** 459,462 **** --- 459,463 ---- def __add__(self, other): return NotImplemented + vereq(C(5L), 5) try: C() + "" *************** *** 465,468 **** --- 466,476 ---- else: raise TestFailed, "NotImplemented should have caused TypeError" + import sys + try: + C(sys.maxint+1) + except OverflowError: + pass + else: + raise TestFailed, "should have raised OverflowError" def longs(): From nnorwitz@users.sourceforge.net Mon Feb 10 02:12:46 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 18:12:46 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.647,1.648 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv13524/Misc Modified Files: NEWS Log Message: Fix SF bug #683467, 'int' ability to generate longs not inherited When subclassing from an int but not overriding __new__, long values were not converted properly. Try to convert longs into an int. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.647 retrieving revision 1.648 diff -C2 -d -r1.647 -r1.648 *** NEWS 10 Feb 2003 01:54:05 -0000 1.647 --- NEWS 10 Feb 2003 02:12:43 -0000 1.648 *************** *** 13,16 **** --- 13,19 ---- ----------------- + - int subclasses can be initialized with longs if the value fits in an int. + See SF bug #683467. + - long(string, base) takes time linear in len(string) when base is a power of 2 now. It used to take time quadratic in len(string). From nnorwitz@users.sourceforge.net Mon Feb 10 03:10:45 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 09 Feb 2003 19:10:45 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.282,2.283 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29707/Modules Modified Files: posixmodule.c Log Message: Fix memory leak of newstr when putenv() fails Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.282 retrieving revision 2.283 diff -C2 -d -r2.282 -r2.283 *** posixmodule.c 10 Jan 2003 15:29:16 -0000 2.282 --- posixmodule.c 10 Feb 2003 03:10:43 -0000 2.283 *************** *** 5663,5666 **** --- 5663,5667 ---- PyOS_snprintf(new, len, "%s=%s", s1, s2); if (putenv(new)) { + Py_DECREF(newstr); posix_error(); return NULL; From montanaro@users.sourceforge.net Mon Feb 10 03:42:18 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 09 Feb 2003 19:42:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv6919 Modified Files: _csv.c Log Message: I think this is sufficient to allow csv readers to be iterated by user-defined classes. Thus, you can delegate to them, e.g., from csv.DictReader.next() (coming in csv.py) Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** _csv.c 10 Feb 2003 00:05:14 -0000 1.23 --- _csv.c 10 Feb 2003 03:42:16 -0000 1.24 *************** *** 80,83 **** --- 80,85 ---- staticforward PyTypeObject Reader_Type; + #define ReaderObject_Check(v) ((v)->ob_type == &Reader_Type) + typedef struct { PyObject_HEAD *************** *** 456,463 **** * READER */ - static struct PyMethodDef Reader_methods[] = { - { NULL, NULL } - }; - #define R_OFF(x) offsetof(ReaderObj, x) --- 458,461 ---- *************** *** 474,488 **** }; - static PyObject * - Reader_getattr(ReaderObj *self, char *name) - { - PyObject *rv; - - rv = dialect_getattr((PyObject *)self, Reader_memberlist, name); - if (rv) - return rv; - return Py_FindMethod(Reader_methods, (PyObject *)self, name); - } - static int Reader_setattr(ReaderObj *self, char *name, PyObject *v) --- 472,475 ---- *************** *** 577,580 **** --- 564,597 ---- PyDoc_STRVAR(Reader_Type_doc, "CSV reader"); + + static PyObject * + reader_next(PyObject *self, PyObject *args) + { + PyObject *result; + + if (!ReaderObject_Check(self)) + return NULL; + + result = Reader_iternext((ReaderObj *)self); + if (result == NULL) + PyErr_SetObject(PyExc_StopIteration, Py_None); + return result; + } + + static struct PyMethodDef Reader_methods[] = { + { "next", (PyCFunction)reader_next, METH_NOARGS }, + { NULL, NULL } + }; + + static PyObject * + Reader_getattr(ReaderObj *self, char *name) + { + PyObject *rv; + + rv = dialect_getattr((PyObject *)self, Reader_memberlist, name); + if (rv) + return rv; + return Py_FindMethod(Reader_methods, (PyObject *)self, name); + } static PyTypeObject Reader_Type = { From montanaro@users.sourceforge.net Mon Feb 10 03:47:23 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 09 Feb 2003 19:47:23 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv8462 Modified Files: csv.py Log Message: add DictReader and DictWriter Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** csv.py 8 Feb 2003 15:22:55 -0000 1.25 --- csv.py 10 Feb 2003 03:47:21 -0000 1.26 *************** *** 56,57 **** --- 56,87 ---- delimiter = '\t' register_dialect("excel-tab", excel_tab) + + + class DictReader: + def __init__(self, f, fieldnames, rest=None, dialect="excel", *args): + self.fieldnames = fieldnames # list of keys for the dict + self.rest = rest # key to catch long rows + self.reader = reader(f, dialect, *args) + + def next(self): + row = self.reader.next() + d = dict(zip(self.fieldnames, row)) + if len(self.fieldnames) < len(row) and self.rest != None: + d[self.rest] = row[len(self.fieldnames):] + return d + + + class DictWriter: + def __init__(self, f, fieldnames, dialect="excel", *args): + self.fieldnames = fieldnames # list of keys for the dict + self.writer = writer(f, dialect, *args) + + def writerow(self, rowdict): + row = [rowdict.get(key, "") for key in self.fieldnames] + return self.writer.writerow(row) + + def writerows(self, rowdicts): + rows = [] + for rowdict in rowdicts: + rows.append([rowdict.get(key, "") for key in self.fieldnames]) + return self.writer.writerows(rows) From montanaro@users.sourceforge.net Mon Feb 10 03:48:05 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 09 Feb 2003 19:48:05 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv8675 Modified Files: test_csv.py Log Message: reenable and tweak tests for reading/writing dictionaries Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** test_csv.py 7 Feb 2003 06:34:23 -0000 1.22 --- test_csv.py 10 Feb 2003 03:48:03 -0000 1.23 *************** *** 358,366 **** # Disabled, pending support in csv.utils module ! class xTestDictFields(unittest.TestCase): def test_write_simple_dict(self): fileobj = StringIO() ! writer = csv.writer(fileobj, dialect="excel", ! fieldnames = ["f1", "f2", "f3"]) writer.writerow({"f1": 10, "f3": "abc"}) self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") --- 358,365 ---- # Disabled, pending support in csv.utils module ! class TestDictFields(unittest.TestCase): def test_write_simple_dict(self): fileobj = StringIO() ! writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"]) writer.writerow({"f1": 10, "f3": "abc"}) self.assertEqual(fileobj.getvalue(), "10,,abc\r\n") *************** *** 368,387 **** def test_write_no_fields(self): fileobj = StringIO() ! writer = csv.writer(fileobj, dialect="excel") ! self.assertRaises(csv.Error, writer.writerow, {"f1": 10, "f3": "abc"}) def test_read_dict_fields(self): ! reader = csv.reader(StringIO("1,2,abc\r\n"), dialect="excel", ! fieldnames=["f1", "f2", "f3"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) def test_read_short(self): ! reader = csv.reader(StringIO("1,2,abc,4,5,6\r\n"), dialect="excel", ! fieldnames=["f1", "f2"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) def test_read_short_with_rest(self): ! reader = csv.reader(StringIO("1,2,abc,4,5,6\r\n"), dialect="excel", ! fieldnames=["f1", "f2"], restfield="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) --- 367,385 ---- def test_write_no_fields(self): fileobj = StringIO() ! self.assertRaises(TypeError, csv.DictWriter, fileobj) def test_read_dict_fields(self): ! reader = csv.DictReader(StringIO("1,2,abc\r\n"), dialect="excel", ! fieldnames=["f1", "f2", "f3"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) def test_read_short(self): ! reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), ! fieldnames=["f1", "f2"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) def test_read_short_with_rest(self): ! reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), ! fieldnames=["f1", "f2"], rest="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) From montanaro@users.sourceforge.net Mon Feb 10 04:03:51 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 09 Feb 2003 20:03:51 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv15762 Modified Files: pep-0305.txt Log Message: a number of changes to keep more-or-less up-to-date. Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** pep-0305.txt 3 Feb 2003 03:01:48 -0000 1.13 --- pep-0305.txt 10 Feb 2003 04:03:49 -0000 1.14 *************** *** 19,27 **** files are simple to parse, the format is not formally defined by a stable specification and is subtle enough that parsing lines of a CSV ! file with something like ``line.split(",")`` is bound to fail. This ! PEP defines an API for reading and writing CSV files which should make ! it possible for programmers to select a CSV module which meets their ! requirements. It is accompanied by a corresponding module which ! implements the API. --- 19,25 ---- files are simple to parse, the format is not formally defined by a stable specification and is subtle enough that parsing lines of a CSV ! file with something like ``line.split(",")`` is eventually bound to ! fail. This PEP defines an API for reading and writing CSV files. It ! is accompanied by a corresponding module which implements the API. *************** *** 29,59 **** ============================================== - - Need to better explain the advantages of a purpose-built csv module - over the simple ",".join() and [].split() approach. - - - Need to complete initial list of formatting parameters and settle on - names. - - Better motivation for the choice of passing a file object to the constructors. See http://manatee.mojam.com/pipermail/csv/2003-January/000179.html - Existing Modules - ================ ! Three widely available modules enable programmers to read and write ! CSV files: ! - Object Craft's CSV module [2]_ ! - Cliff Wells' Python-DSV module [3]_ ! - Laurence Tratt's ASV module [4]_ ! Each has a different API, making it somewhat difficult for programmers ! to switch between them. More of a problem may be that they interpret ! some of the CSV corner cases differently, so even after surmounting ! the differences in the module APIs, the programmer has to also deal ! with semantic differences between the packages. --- 27,55 ---- ============================================== - Better motivation for the choice of passing a file object to the constructors. See http://manatee.mojam.com/pipermail/csv/2003-January/000179.html + - Unicode. ugh. ! Application Domain ! ================== ! This PEP is about doing one thing well: parsing tabular data which may ! use a variety of field separators, quoting characters, quote escape ! mechanisms and line endings. The authors intend the proposed module ! to solve this one parsing problem efficiently. The authors do not ! intend to address any of these related topics:: ! - data interpretation (is a field containing the string "10" ! supposed to be a string, a float or an int? is it a number in ! base 10, base 16 or base 2? is a number in quotes a number or a ! string?) ! - locale-specific data representation (should the number 1.23 be ! written as "1.23" or "1,23" or "1 23"?) -- this may eventually ! be addressed. ! - fixed width tabular data - can already be parsed reliably. *************** *** 61,70 **** ========= ! By defining common APIs for reading and writing CSV files, we make it ! easier for programmers to choose an appropriate module to suit their ! needs, and make it easier to switch between modules if their needs ! change. This PEP also forms a set of requirements for creation of a ! module which will hopefully be incorporated into the Python ! distribution. CSV formats are not well-defined and different implementations have a --- 57,70 ---- ========= ! Often, CSV files are formatted simply enough that you can get by ! reading them line-by-line and splitting on the commas which delimit ! the fields. This is especially true if all the data being read is ! numeric. This approach may work for awhile, then come back to bite ! you in the butt when somebody puts something unexpected in the data ! like a comma. As you dig into the problem you may eventually come to ! the conclusion that you can solve the problem using regular ! expressions. This will work for awhile, then break mysteriously one ! day. The problem grows, so you dig deeper and eventually realize that ! you need a purpose-built parser for the format. CSV formats are not well-defined and different implementations have a *************** *** 72,85 **** the acronym stands for "Vague" instead of "Values". Different delimiters and quoting characters are just the start. Some programs ! generate whitespace after the delimiter. Others quote embedded ! quoting characters by doubling them or prefixing them with an escape ! character. The list of weird ways to do things seems nearly endless. ! Unfortunately, all this variability and subtlety means it is difficult ! for programmers to reliably parse CSV files from many sources or ! generate CSV files designed to be fed to specific external programs ! without deep knowledge of those sources and programs. This PEP and ! the software which accompany it attempt to make the process less ! fragile. --- 72,105 ---- the acronym stands for "Vague" instead of "Values". Different delimiters and quoting characters are just the start. Some programs ! generate whitespace after each delimiter which is not part of the ! following field. Others quote embedded quoting characters by doubling ! them, others by prefixing them with an escape character. The list of ! weird ways to do things can seem endless. ! All this variability means it is difficult for programmers to reliably ! parse CSV files from many sources or generate CSV files designed to be ! fed to specific external programs without a thorough understanding of ! those sources and programs. This PEP and the software which accompany ! it attempt to make the process less fragile. ! ! ! Existing Modules ! ================ ! ! This problem has been tackled before. At least three modules ! currently available in the Python community enable programmers to read ! and write CSV files: ! ! - Object Craft's CSV module [2]_ ! ! - Cliff Wells' Python-DSV module [3]_ ! ! - Laurence Tratt's ASV module [4]_ ! ! Each has a different API, making it somewhat difficult for programmers ! to switch between them. More of a problem may be that they interpret ! some of the CSV corner cases differently, so even after surmounting ! the differences between the different module APIs, the programmer has ! to also deal with semantic differences between the packages. *************** *** 87,102 **** ================ ! The module supports two basic APIs, one for reading and one for ! writing. The basic reading interface is:: obj = reader(iterable [, dialect='excel'] [optional keyword args]) ! A reader object is an iterable which takes an interable object which ! returns lines as the sole required parameter. The optional dialect ! parameter is discussed below. It also accepts several optional ! keyword arguments which define specific format settings for the parser ! (see the section "Formatting Parameters"). Readers are typically used ! as follows:: csvreader = csv.reader(file("some.csv")) --- 107,132 ---- ================ ! This PEP supports three basic APIs, one to read and parse CSV files, ! one to write them, and one to identify different CSV dialects to the ! readers and writers. ! ! ! Reading CSV Files ! ----------------- ! ! CSV readers are created with the reader factory function:: obj = reader(iterable [, dialect='excel'] [optional keyword args]) ! A reader object is an iterator which takes an iterable object ! returning lines as the sole required parameter. If it supports a ! binary mode (file objects do), the iterable argument to the reader ! function must have been opened in binary mode. This gives the reader ! object full control over the interpretation of the file's contents. ! The optional dialect parameter is discussed below. The reader ! function also accepts several optional keyword arguments which define ! specific format settings for the parser (see the section "Formatting ! Parameters"). Readers are typically used as follows:: csvreader = csv.reader(file("some.csv")) *************** *** 104,118 **** process(row) ! The writing interface is similar:: ! obj = writer(fileobj [, dialect='excel'], [, fieldnames=seq] [optional keyword args]) A writer object is a wrapper around a file-like object opened for ! writing. It accepts the same optional keyword parameters as the ! reader constructor. In addition, it accepts an optional fieldnames ! argument. This is a sequence that defines the order of fields in the ! output file. It allows the write() method to accept mapping objects ! as well as sequence objects. Writers are typically used as follows:: --- 134,156 ---- process(row) ! Each row returned by a reader object is a list of strings or Unicode ! objects. ! When both a dialect parameter and individual formatting parameters are ! passed to the constructor, first the dialect is queried for formatting ! parameters, then individual formatting parameters are examined. ! ! ! Writing CSV Files ! ----------------- ! ! Creating writers is similar:: ! ! obj = writer(fileobj [, dialect='excel'], [optional keyword args]) A writer object is a wrapper around a file-like object opened for ! writing in binary mode (if such a distinction is made). It accepts ! the same optional keyword parameters as the reader constructor. Writers are typically used as follows:: *************** *** 120,124 **** csvwriter = csv.writer(file("some.csv", "w")) for row in someiterable: ! csvwriter.write(row) To generate a set of field names as the first row of the CSV file, the --- 158,162 ---- csvwriter = csv.writer(file("some.csv", "w")) for row in someiterable: ! csvwriter.writerow(row) To generate a set of field names as the first row of the CSV file, the *************** *** 133,160 **** ! Dialects ! -------- ! Readers and writers support a dialect argument which is just a ! convenient handle on a group of lower level parameters. ! When dialect is a string it identifies one of the dialects which is ! known to the module, otherwise it is processed as a dialect class as ! described below. Dialects will generally be named after applications or organizations ! which define specific sets of format constraints. The initial dialect ! is "excel", which describes the format constraints of Excel 97 and ! Excel 2000 regarding CSV input and output. Another possible dialect ! (used here only as an example) might be "gnumeric". Dialects are implemented as attribute only classes to enable users to ! construct variant dialects by subclassing. The "excel" dialect is ! implemented as follows:: ! class excel: delimiter = ',' quotechar = '"' - escapechar = None doublequote = True skipinitialspace = False --- 171,217 ---- ! Managing Different Dialects ! --------------------------- ! Because CSV is a somewhat ill-defined format, there are plenty of ways ! one CSV file can differ from another, yet contain exactly the same ! data. Many tools which can import or export tabular data allow the ! user to indicate the field delimiter, quote character, line ! terminator, and other characteristics of the file. These can be ! fairly easily determined, but are still mildly annoying to figure out, ! and make for fairly long function calls when specified individually. ! To try and minimize the difficulty of figuring out and specifying a ! bunch of formatting parameters, reader and writer objects support a ! dialect argument which is just a convenient handle on a group of these ! lower level parameters. When a dialect is given as a string it ! identifies one of the dialects known to the module via its ! registration functions, otherwise it must be an instance of the ! Dialect class as described below. Dialects will generally be named after applications or organizations ! which define specific sets of format constraints. Two dialects are ! defined in the module as of this writing, "excel", which describes the ! default format constraints for CSV file export by Excel 97 and Excel ! 2000, and "excel-tab", which is the same as "excel" but specifies an ! ASCII TAB character as the field delimiter. Dialects are implemented as attribute only classes to enable users to ! construct variant dialects by subclassing. The "excel" dialect is a ! subclass of Dialect and is defined as follows:: ! class Dialect: ! # placeholders ! delimiter = None ! quotechar = None ! escapechar = None ! doublequote = None ! skipinitialspace = None ! lineterminator = None ! quoting = None ! ! class excel(Dialect): delimiter = ',' quotechar = '"' doublequote = True skipinitialspace = False *************** *** 162,182 **** quoting = QUOTE_MINIMAL ! An excel tab separated dialect can then be defined in user code as ! follows:: ! class exceltsv(csv.excel): delimiter = '\t' ! Three functions are defined in the API to set, get and list dialects:: - register_dialect(name, dialect) dialect = get_dialect(name) ! known_dialects = list_dialects() ! The dialect parameter is a class or instance whose attributes are the ! formatting parameters defined in the next section. The ! list_dialects() function returns all the registered dialect names as ! given in previous register_dialect() calls (both predefined and ! user-defined). --- 219,243 ---- quoting = QUOTE_MINIMAL ! The "excel-tab" dialect is defined as:: ! class exceltsv(excel): delimiter = '\t' ! (For a description of the individual formatting parameters see the ! section "Formatting Parameters".) ! ! To enable string references to specific dialects, the module defines ! several functions:: dialect = get_dialect(name) ! names = list_dialects() ! register_dialect(name, dialect) ! unregister_dialect(name) ! ``get_dialect()`` returns the dialect instance associated with the ! given name. ``list_dialects()`` returns a list of all registered ! dialect names. ``register_dialects()`` associates a string name with ! a dialect class. ``unregister_dialect()`` deletes a name/dialect ! association. *************** *** 184,241 **** --------------------- ! Both the reader and writer constructors take several specific ! formatting parameters, specified as keyword parameters. ! ! - ``quotechar`` specifies a one-character string to use as the quoting ! character. It defaults to '"'. Setting this to None has the same ! effect as setting quoting to csv.QUOTE_NONE. ! - ``delimiter`` specifies a one-character string to use as the field ! separator. It defaults to ','. ! - ``escapechar`` specifies a one-character string used to escape the ! delimiter when quotechar is set to None. ! - ``skipinitialspace`` specifies how to interpret whitespace which ! immediately follows a delimiter. It defaults to False, which means ! that whitespace immediately following a delimiter is part of the ! following field. ! - ``lineterminator`` specifies the character sequence which should ! terminate rows. ! - ``quoting`` controls when quotes should be generated by the ! writer. It can take on any of the following module constants:: ! csv.QUOTE_MINIMAL means only when required, for example, when a ! field contains either the quotechar or the delimiter ! csv.QUOTE_ALL means that quotes are always placed around fields. ! csv.QUOTE_NONNUMERIC means that quotes are always placed around ! fields which contain characters other than [+-0-9.]. ! csv.QUOTE_NONE means that quotes are never placed around ! fields. ! - ``doublequote`` controls the handling of quotes inside fields. When ! True two consecutive quotes are interpreted as one during read, and ! when writing, each quote is written as two quotes. ! - are there more to come? When processing a dialect setting and one or more of the other ! optional parameters, the dialect parameter is processed first, then ! the others are processed. This makes it easy to choose a dialect, ! then override one or more of the settings without defining a new ! dialect class. For example, if a CSV file was generated by Excel 2000 ! using single quotes as the quote character and TAB as the delimiter, ! you could create a reader like:: csvreader = csv.reader(file("some.csv"), dialect="excel", ! quotechar="'", delimiter='\t') Other details of how Excel generates CSV files would be handled ! automatically. --- 245,318 ---- --------------------- ! In addition to the dialect argument, both the reader and writer ! constructors take several specific formatting parameters, specified as ! keyword parameters. The formatting parameters understood are:: ! - ``quotechar`` specifies a one-character string to use as the ! quoting character. It defaults to '"'. Setting this to None ! has the same effect as setting quoting to csv.QUOTE_NONE. ! - ``delimiter`` specifies a one-character string to use as the ! field separator. It defaults to ','. ! - ``escapechar`` specifies a one-character string used to escape ! the delimiter when quotechar is set to None. ! - ``skipinitialspace`` specifies how to interpret whitespace which ! immediately follows a delimiter. It defaults to False, which ! means that whitespace immediately following a delimiter is part ! of the following field. ! - ``lineterminator`` specifies the character sequence which should ! terminate rows. ! - ``quoting`` controls when quotes should be generated by the ! writer. It can take on any of the following module constants:: ! * csv.QUOTE_MINIMAL means only when required, for example, ! when a field contains either the quotechar or the delimiter ! * csv.QUOTE_ALL means that quotes are always placed around ! fields. ! * csv.QUOTE_NONNUMERIC means that quotes are always placed ! around nonnumeric fields. ! * csv.QUOTE_NONE means that quotes are never placed around ! fields. ! - ``doublequote`` controls the handling of quotes inside fields. ! When True two consecutive quotes are interpreted as one during ! read, and when writing, each quote is written as two quotes. When processing a dialect setting and one or more of the other ! optional parameters, the dialect parameter is processed before the ! individual formatting parameters. This makes it easy to choose a ! dialect, then override one or more of the settings without defining a ! new dialect class. For example, if a CSV file was generated by Excel ! 2000 using single quotes as the quote character and a colon as the ! delimiter, you could create a reader like:: csvreader = csv.reader(file("some.csv"), dialect="excel", ! quotechar="'", delimiter=':') Other details of how Excel generates CSV files would be handled ! automatically because of the reference to the "excel" dialect. ! ! ! Reader Objects ! -------------- ! ! Reader objects are iterables whose next() method returns a sequence of ! strings, one string per field in the row. ! ! ! Writer Objects ! -------------- ! ! Writer objects have two methods, writerow() and writerows(). The ! former accepts an iterable (typically a list) of fields which are to ! be written to the output. The latter accepts a list of iterables and ! calls writerow() for each. *************** *** 258,318 **** ====== ! - Should a parameter control how consecutive delimiters are ! interpreted? Our thought is "no". Consecutive delimiters should ! always denote an empty field. ! ! - What about Unicode? Is it sufficient to pass a file object gotten ! from codecs.open()? For example:: ! ! csvreader = csv.reader(codecs.open("some.csv", "r", "cp1252")) ! ! csvwriter = csv.writer(codecs.open("some.csv", "w", "utf-8")) ! In the first example, text would be assumed to be encoded as cp1252. ! Should the system be aggressive in converting to Unicode or should ! Unicode strings only be returned if necessary? ! In the second example, the file will take care of automatically ! encoding Unicode strings as utf-8 before writing to disk. ! - What about alternate escape conventions? When Excel exports a file, ! it appears only the field delimiter needs to be escaped. It ! accomplishes this by quoting the entire field, then doubling any ! quote characters which appear in the field. It also quotes a field ! if the first character is a quote character. It would seem we need ! to support two modes: escape-by-quoting and escape-by-prefix. In ! addition, for the second mode, we'd have to specify the escape ! character (presumably defaulting to a backslash character). ! - Should there be a "fully quoted" mode for writing? What about ! "fully quoted except for numeric values"? ! - What about end-of-line? If I generate a CSV file on a Unix system, ! will Excel properly recognize the LF-only line terminators? ! - What about conversion to other file formats? Is the list-of-lists ! output from the csvreader sufficient to feed into other writers? ! - What about an option to generate list-of-dict output from the reader ! and accept list-of-dicts by the writer? This makes manipulating ! individual rows easier since each one is independent, but you lose ! field order when writing and have to tell the writer object the ! order the fields should appear in the file. ! - Are quote character and delimiters limited to single characters? I ! had a client not that long ago who wrote their own flat file format ! with a delimiter of ":::". ! - How should rows of different lengths be handled? The options seem ! to be: ! * raise an exception when a row is encountered whose length differs ! from the previous row ! * silently return short rows ! * allow the caller to specify the desired row length and what to do ! when rows of a different length are encountered: ignore, truncate, ! pad, raise exception, etc. --- 335,386 ---- ====== ! 1. Should a parameter control how consecutive delimiters are ! interpreted? Our thought is "no". Consecutive delimiters should ! always denote an empty field. ! 2. What about Unicode? Is it sufficient to pass a file object gotten ! from codecs.open()? For example:: ! csvreader = csv.reader(codecs.open("some.csv", "r", "cp1252")) ! csvwriter = csv.writer(codecs.open("some.csv", "w", "utf-8")) ! In the first example, text would be assumed to be encoded as cp1252. ! Should the system be aggressive in converting to Unicode or should ! Unicode strings only be returned if necessary? ! In the second example, the file will take care of automatically ! encoding Unicode strings as utf-8 before writing to disk. ! Note: As of this writing, the csv module doesn't handle Unicode ! data. ! 3. What about alternate escape conventions? If the dialect in use ! includes an ``escapechar`` parameter which is not None and the ! ``quoting`` parameter is set to QUOTE_NONE, delimiters appearing ! within fields will be prefixed by the escape character when writing ! and are expected to be prefixed by the escape character when ! reading. ! 4. Should there be a "fully quoted" mode for writing? What about ! "fully quoted except for numeric values"? Both are implemented ! (QUOTE_ALL and QUOTE_NONNUMERIC, respectively). ! 5. What about end-of-line? If I generate a CSV file on a Unix system, ! will Excel properly recognize the LF-only line terminators? Files ! must be opened for reading or writing as appropriate using binary ! mode. Specify the ``lineterminator`` sequence as '\r\n'. The ! resulting file will be written correctly. ! 6. What about an option to generate dicts from the reader and accept ! dicts by the writer? See the DictReader and DictWriter classes in ! csv.py. ! 8. Are quote character and delimiters limited to single characters? ! For the time being, yes. ! 9. How should rows of different lengths be handled? Interpretation of ! the data is the application's job. There is no such thing as a ! "short row" or a "long row" at this level. From jvr@users.sourceforge.net Mon Feb 10 08:21:39 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:21:39 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19147/Lib/test Modified Files: test_builtin.py Log Message: patch #683515: "Add unicode support to compile(), eval() and exec" Incorporated nnorwitz's comment re. Py__USING_UNICODE. Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** test_builtin.py 9 Feb 2003 20:38:47 -0000 1.10 --- test_builtin.py 10 Feb 2003 08:21:05 -0000 1.11 *************** *** 196,199 **** --- 196,201 ---- self.assertRaises(ValueError, compile, 'print 42\n', '', 'badmode') self.assertRaises(ValueError, compile, 'print 42\n', '', 'single', 0xff) + if have_unicode: + compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') def test_complex(self): *************** *** 310,313 **** --- 312,317 ---- bom = '\xef\xbb\xbf' self.assertEqual(eval(bom + 'a', globals, locals), 1) + self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals), + unicode('\xc3\xa5', 'utf8')) self.assertRaises(TypeError, eval) self.assertRaises(TypeError, eval, ()) From jvr@users.sourceforge.net Mon Feb 10 08:21:45 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:21:45 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.275,2.276 ceval.c,2.348,2.349 compile.c,2.273,2.274 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv19147/Python Modified Files: bltinmodule.c ceval.c compile.c Log Message: patch #683515: "Add unicode support to compile(), eval() and exec" Incorporated nnorwitz's comment re. Py__USING_UNICODE. Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.275 retrieving revision 2.276 diff -C2 -d -r2.275 -r2.276 *** bltinmodule.c 4 Feb 2003 20:24:43 -0000 2.275 --- bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 *************** *** 341,349 **** int supplied_flags = 0; PyCompilerFlags cf; ! if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename, &startstr, &supplied_flags, &dont_inherit)) return NULL; if (strcmp(startstr, "exec") == 0) start = Py_file_input; --- 341,370 ---- int supplied_flags = 0; PyCompilerFlags cf; + PyObject *result, *cmd, *tmp = NULL; ! if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename, &startstr, &supplied_flags, &dont_inherit)) return NULL; + cf.cf_flags = supplied_flags; + + #ifdef Py_USING_UNICODE + if (PyUnicode_Check(cmd)) { + tmp = PyUnicode_AsUTF8String(cmd); + if (tmp == NULL) + return NULL; + cmd = tmp; + cf.cf_flags |= PyCF_SOURCE_IS_UTF8; + } + #endif + if (!PyString_Check(cmd)) { + PyErr_SetString(PyExc_TypeError, + "compile() arg 1 must be a string"); + return NULL; + } + + if (PyString_AsStringAndSize(cmd, &str, NULL)) + return NULL; + if (strcmp(startstr, "exec") == 0) start = Py_file_input; *************** *** 365,373 **** /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ - cf.cf_flags = supplied_flags; if (!dont_inherit) { PyEval_MergeCompilerFlags(&cf); } ! return Py_CompileStringFlags(str, filename, start, &cf); } --- 386,395 ---- /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ if (!dont_inherit) { PyEval_MergeCompilerFlags(&cf); } ! result = Py_CompileStringFlags(str, filename, start, &cf); ! Py_XDECREF(tmp); ! return result; } *************** *** 429,433 **** builtin_eval(PyObject *self, PyObject *args) { ! PyObject *cmd; PyObject *globals = Py_None, *locals = Py_None; char *str; --- 451,455 ---- builtin_eval(PyObject *self, PyObject *args) { ! PyObject *cmd, *result, *tmp = NULL; PyObject *globals = Py_None, *locals = Py_None; char *str; *************** *** 468,471 **** --- 490,504 ---- return NULL; } + cf.cf_flags = 0; + + #ifdef Py_USING_UNICODE + if (PyUnicode_Check(cmd)) { + tmp = PyUnicode_AsUTF8String(cmd); + if (tmp == NULL) + return NULL; + cmd = tmp; + cf.cf_flags |= PyCF_SOURCE_IS_UTF8; + } + #endif if (PyString_AsStringAndSize(cmd, &str, NULL)) return NULL; *************** *** 473,479 **** str++; - cf.cf_flags = 0; (void)PyEval_MergeCompilerFlags(&cf); ! return PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); } --- 506,513 ---- str++; (void)PyEval_MergeCompilerFlags(&cf); ! result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); ! Py_XDECREF(tmp); ! return result; } Index: ceval.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/ceval.c,v retrieving revision 2.348 retrieving revision 2.349 diff -C2 -d -r2.348 -r2.349 *** ceval.c 5 Feb 2003 23:12:57 -0000 2.348 --- ceval.c 10 Feb 2003 08:21:08 -0000 2.349 *************** *** 3123,3127 **** { PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); ! int result = 0; if (current_frame != NULL) { --- 3123,3127 ---- { PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); ! int result = cf->cf_flags != 0; if (current_frame != NULL) { *************** *** 3899,3907 **** } else { char *str; PyCompilerFlags cf; if (PyString_AsStringAndSize(prog, &str, NULL)) return -1; - cf.cf_flags = 0; if (PyEval_MergeCompilerFlags(&cf)) v = PyRun_StringFlags(str, Py_file_input, globals, --- 3899,3917 ---- } else { + PyObject *tmp = NULL; char *str; PyCompilerFlags cf; + cf.cf_flags = 0; + #ifdef Py_USING_UNICODE + if (PyUnicode_Check(prog)) { + tmp = PyUnicode_AsUTF8String(prog); + if (tmp == NULL) + return -1; + prog = tmp; + cf.cf_flags |= PyCF_SOURCE_IS_UTF8; + } + #endif if (PyString_AsStringAndSize(prog, &str, NULL)) return -1; if (PyEval_MergeCompilerFlags(&cf)) v = PyRun_StringFlags(str, Py_file_input, globals, *************** *** 3909,3912 **** --- 3919,3923 ---- else v = PyRun_String(str, Py_file_input, globals, locals); + Py_XDECREF(tmp); } if (plain) Index: compile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/compile.c,v retrieving revision 2.273 retrieving revision 2.274 diff -C2 -d -r2.273 -r2.274 *** compile.c 5 Feb 2003 23:13:00 -0000 2.273 --- compile.c 10 Feb 2003 08:21:10 -0000 2.274 *************** *** 4207,4211 **** if (!com_init(&sc, filename)) return NULL; ! if (TYPE(n) == encoding_decl) { sc.c_encoding = STR(n); n = CHILD(n, 0); --- 4207,4213 ---- if (!com_init(&sc, filename)) return NULL; ! if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) { ! sc.c_encoding = "utf-8"; ! } else if (TYPE(n) == encoding_decl) { sc.c_encoding = STR(n); n = CHILD(n, 0); From jvr@users.sourceforge.net Mon Feb 10 08:21:40 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:21:40 -0800 Subject: [Python-checkins] python/dist/src/Include pythonrun.h,2.60,2.61 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv19147/Include Modified Files: pythonrun.h Log Message: patch #683515: "Add unicode support to compile(), eval() and exec" Incorporated nnorwitz's comment re. Py__USING_UNICODE. Index: pythonrun.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pythonrun.h,v retrieving revision 2.60 retrieving revision 2.61 diff -C2 -d -r2.60 -r2.61 *** pythonrun.h 1 Jan 2003 15:18:32 -0000 2.60 --- pythonrun.h 10 Feb 2003 08:21:06 -0000 2.61 *************** *** 10,13 **** --- 10,14 ---- #define PyCF_MASK (CO_FUTURE_DIVISION) #define PyCF_MASK_OBSOLETE (CO_GENERATOR_ALLOWED | CO_NESTED) + #define PyCF_SOURCE_IS_UTF8 0x0100 typedef struct { From andrewmcnamara@users.sourceforge.net Mon Feb 10 08:40:09 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:40:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv29422 Modified Files: _csv.c Log Message: Turned Dialect struct into a fully fledged Python type and moved dialect/keyword parsing onto it's init function. ReaderObj and WriterObj now contain pointers to objects of this type, and have a "dialect" attribute - this made several things cleaner. Switched Reader_Type and Writer_Type to use 2.2 style attribute access - this allows better introspection. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** _csv.c 10 Feb 2003 03:42:16 -0000 1.24 --- _csv.c 10 Feb 2003 08:40:04 -0000 1.25 *************** *** 52,55 **** --- 52,57 ---- typedef struct { + PyObject_HEAD + int doublequote; /* is " represented by ""? */ char delimiter; /* field separator */ *************** *** 61,65 **** [...1259 lines suppressed...] ! /* Add quote styles into disctionary */ for (style = quote_styles; style->name; style++) { v = PyInt_FromLong(style->style); --- 1417,1421 ---- return; ! /* Add quote styles into dictionary */ for (style = quote_styles; style->name; style++) { v = PyInt_FromLong(style->style); *************** *** 1297,1300 **** --- 1426,1433 ---- return; } + + /* Add the Dialect type */ + if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) + return; /* Add the CSV exception object to the module. */ From andrewmcnamara@users.sourceforge.net Mon Feb 10 08:40:10 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:40:10 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv29422/test Modified Files: test_csv.py Log Message: Turned Dialect struct into a fully fledged Python type and moved dialect/keyword parsing onto it's init function. ReaderObj and WriterObj now contain pointers to objects of this type, and have a "dialect" attribute - this made several things cleaner. Switched Reader_Type and Writer_Type to use 2.2 style attribute access - this allows better introspection. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** test_csv.py 10 Feb 2003 03:48:03 -0000 1.23 --- test_csv.py 10 Feb 2003 08:40:07 -0000 1.24 *************** *** 33,43 **** def _test_attrs(self, obj): ! self.assertEqual(obj.delimiter, ',') ! obj.delimiter = '\t' ! self.assertEqual(obj.delimiter, '\t') ! self.assertRaises(AttributeError, delattr, obj, 'delimiter') ! self.assertRaises(TypeError, setattr, obj, 'lineterminator', None) ! obj.escapechar = None ! self.assertEqual(obj.escapechar, None) def test_reader_attrs(self): --- 33,44 ---- def _test_attrs(self, obj): ! self.assertEqual(obj.dialect.delimiter, ',') ! obj.dialect.delimiter = '\t' ! self.assertEqual(obj.dialect.delimiter, '\t') ! self.assertRaises(TypeError, delattr, obj.dialect, 'delimiter') ! self.assertRaises(TypeError, setattr, obj.dialect, ! 'lineterminator', None) ! obj.dialect.escapechar = None ! self.assertEqual(obj.dialect.escapechar, None) def test_reader_attrs(self): *************** *** 51,55 **** writer = csv.writer(fileobj, **kwargs) writer.writerow(fields) ! self.assertEqual(fileobj.getvalue(), expect + writer.lineterminator) def test_write_arg_valid(self): --- 52,57 ---- writer = csv.writer(fileobj, **kwargs) writer.writerow(fields) ! self.assertEqual(fileobj.getvalue(), ! expect + writer.dialect.lineterminator) def test_write_arg_valid(self): From andrewmcnamara@users.sourceforge.net Mon Feb 10 08:52:59 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 00:52:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.25,1.26 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv4719 Modified Files: _csv.c Log Message: Replaced raise_exception with PyErr_Format. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** _csv.c 10 Feb 2003 08:40:04 -0000 1.25 --- _csv.c 10 Feb 2003 08:52:55 -0000 1.26 *************** *** 410,434 **** }; - PyObject * - raise_exception(char *fmt, ...) - { - va_list ap; - char msg[512]; - PyObject *pymsg; - - va_start(ap, fmt); - #ifdef _WIN32 - _vsnprintf(msg, sizeof(msg), fmt, ap); - #else - vsnprintf(msg, sizeof(msg), fmt, ap); - #endif - va_end(ap); - pymsg = PyString_FromString(msg); - PyErr_SetObject(error_obj, pymsg); - Py_XDECREF(pymsg); - - return NULL; - } - static void parse_save_field(ReaderObj *self) --- 410,413 ---- *************** *** 604,608 **** /* illegal */ self->had_parse_error = 1; ! raise_exception("%c expected after %c", dialect->delimiter, dialect->quotechar); --- 583,587 ---- /* illegal */ self->had_parse_error = 1; ! PyErr_Format(error_obj, "%c expected after %c", dialect->delimiter, dialect->quotechar); *************** *** 673,677 **** self->had_parse_error = 1; Py_DECREF(lineobj); ! return raise_exception("newline inside string"); } if (c == '\n') { --- 652,657 ---- self->had_parse_error = 1; Py_DECREF(lineobj); ! return PyErr_Format(error_obj, ! "newline inside string"); } if (c == '\n') { *************** *** 682,686 **** self->had_parse_error = 1; Py_DECREF(lineobj); ! return raise_exception("newline inside string"); } parse_process_char(self, c); --- 662,667 ---- self->had_parse_error = 1; Py_DECREF(lineobj); ! return PyErr_Format(error_obj, ! "newline inside string"); } parse_process_char(self, c); *************** *** 892,896 **** } else { ! raise_exception("delimiter must be quoted or escaped"); return -1; } --- 873,878 ---- } else { ! PyErr_Format(error_obj, ! "delimiter must be quoted or escaped"); return -1; } *************** *** 907,911 **** if (i == 0 && quote_empty) { if (dialect->quoting == QUOTE_NONE) { ! raise_exception("single empty field record must be quoted"); return -1; } else --- 889,894 ---- if (i == 0 && quote_empty) { if (dialect->quoting == QUOTE_NONE) { ! PyErr_Format(error_obj, ! "single empty field record must be quoted"); return -1; } else *************** *** 1004,1008 **** if (!PySequence_Check(seq)) ! return raise_exception("sequence expected"); len = PySequence_Length(seq); --- 987,991 ---- if (!PySequence_Check(seq)) ! return PyErr_Format(error_obj, "sequence expected"); len = PySequence_Length(seq); From mal@lemburg.com Mon Feb 10 08:57:15 2003 From: mal@lemburg.com (M.-A. Lemburg) Date: Mon, 10 Feb 2003 09:57:15 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.275,2.276 ceval.c,2.348,2.349 compile.c,2.273,2.274 In-Reply-To: References: Message-ID: <3E47696B.4050208@lemburg.com> jvr@users.sourceforge.net wrote: > Update of /cvsroot/python/python/dist/src/Python > In directory sc8-pr-cvs1:/tmp/cvs-serv19147/Python > > Modified Files: > bltinmodule.c ceval.c compile.c > Log Message: > patch #683515: "Add unicode support to compile(), eval() and exec" > Incorporated nnorwitz's comment re. Py__USING_UNICODE. > > > Index: bltinmodule.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v > retrieving revision 2.275 > retrieving revision 2.276 > diff -C2 -d -r2.275 -r2.276 > *** bltinmodule.c 4 Feb 2003 20:24:43 -0000 2.275 > --- bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 > *************** > *** 341,349 **** > int supplied_flags = 0; > PyCompilerFlags cf; > > ! if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename, > &startstr, &supplied_flags, &dont_inherit)) > return NULL; > > if (strcmp(startstr, "exec") == 0) > start = Py_file_input; > --- 341,370 ---- > int supplied_flags = 0; > PyCompilerFlags cf; > + PyObject *result, *cmd, *tmp = NULL; > > ! if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename, > &startstr, &supplied_flags, &dont_inherit)) > return NULL; > > + cf.cf_flags = supplied_flags; > + > + #ifdef Py_USING_UNICODE > + if (PyUnicode_Check(cmd)) { > + tmp = PyUnicode_AsUTF8String(cmd); > + if (tmp == NULL) > + return NULL; > + cmd = tmp; > + cf.cf_flags |= PyCF_SOURCE_IS_UTF8; > + } > + #endif > + if (!PyString_Check(cmd)) { > + PyErr_SetString(PyExc_TypeError, > + "compile() arg 1 must be a string"); > + return NULL; > + } > + > + if (PyString_AsStringAndSize(cmd, &str, NULL)) > + return NULL; > + This will break code: the "s" parser marker allows passing in any buffer compatible object. You'll have to use PyObject_AsReadBuffer() here to be backward compatible. -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Feb 09 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ Python UK 2003, Oxford: 51 days left EuroPython 2003, Charleroi, Belgium: 135 days left From jvr@users.sourceforge.net Mon Feb 10 09:22:04 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 01:22:04 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv18169/Python Modified Files: bltinmodule.c Log Message: My previous checkin caused compile() to no longer accept buffers, as noted my MAL. Fixed. (Btw. eval() still doesn't take buffers, but that was so even before my patch.) Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.276 retrieving revision 2.277 diff -C2 -d -r2.276 -r2.277 *** bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 --- bltinmodule.c 10 Feb 2003 09:22:01 -0000 2.277 *************** *** 19,22 **** --- 19,24 ---- #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) const char *Py_FileSystemDefaultEncoding = "mbcs"; + #elif defined(__APPLE__) + const char *Py_FileSystemDefaultEncoding = "utf-8"; #else const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ *************** *** 342,345 **** --- 344,348 ---- PyCompilerFlags cf; PyObject *result, *cmd, *tmp = NULL; + int length; if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename, *************** *** 358,369 **** } #endif ! if (!PyString_Check(cmd)) { PyErr_SetString(PyExc_TypeError, ! "compile() arg 1 must be a string"); return NULL; } - - if (PyString_AsStringAndSize(cmd, &str, NULL)) - return NULL; if (strcmp(startstr, "exec") == 0) --- 361,371 ---- } #endif ! if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) ! return NULL; ! if (length != strlen(str)) { PyErr_SetString(PyExc_TypeError, ! "expected string without null bytes"); return NULL; } if (strcmp(startstr, "exec") == 0) From just@letterror.com Mon Feb 10 09:29:57 2003 From: just@letterror.com (Just van Rossum) Date: Mon, 10 Feb 2003 10:29:57 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: Message-ID: jvr@users.sourceforge.net wrote: > Index: bltinmodule.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v > retrieving revision 2.276 > retrieving revision 2.277 > diff -C2 -d -r2.276 -r2.277 > *** bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 > --- bltinmodule.c 10 Feb 2003 09:22:01 -0000 2.277 > *************** > *** 19,22 **** > --- 19,24 ---- > #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) > const char *Py_FileSystemDefaultEncoding = "mbcs"; > + #elif defined(__APPLE__) > + const char *Py_FileSystemDefaultEncoding = "utf-8"; > #else > const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ Whoops, this wasn't meant to be checked in as a side effect of this... But then again, it should be ckecked in anyway, except perhaps with a different switch. Just From Jack.Jansen@cwi.nl Mon Feb 10 09:39:57 2003 From: Jack.Jansen@cwi.nl (Jack Jansen) Date: Mon, 10 Feb 2003 10:39:57 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: Message-ID: <9DBFE94E-3CDB-11D7-AF40-0030655234CE@cwi.nl> On Monday, Feb 10, 2003, at 10:29 Europe/Amsterdam, Just van Rossum wrote: > jvr@users.sourceforge.net wrote: > >> Index: bltinmodule.c >> =================================================================== >> RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v >> retrieving revision 2.276 >> retrieving revision 2.277 >> diff -C2 -d -r2.276 -r2.277 >> *** bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 >> --- bltinmodule.c 10 Feb 2003 09:22:01 -0000 2.277 >> *************** >> *** 19,22 **** >> --- 19,24 ---- >> #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) >> const char *Py_FileSystemDefaultEncoding = "mbcs"; >> + #elif defined(__APPLE__) >> + const char *Py_FileSystemDefaultEncoding = "utf-8"; >> #else >> const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ > > Whoops, this wasn't meant to be checked in as a side effect of this... > But then again, it should be ckecked in anyway, except perhaps with a > different switch. I don't like looking at __APPLE__ either (it looks too broad), but I haven't found anything else. So I'd say leave it as is. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From andrewmcnamara@users.sourceforge.net Mon Feb 10 09:41:31 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 01:41:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv28955 Modified Files: _csv.c Log Message: A few minor changes so the module works with Python2.2 Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** _csv.c 10 Feb 2003 08:52:55 -0000 1.26 --- _csv.c 10 Feb 2003 09:41:28 -0000 1.27 *************** *** 112,117 **** dialect_obj = PyDict_GetItem(dialects, name_obj); if (dialect_obj == NULL) ! return PyErr_Format(error_obj, "unknown dialect '%s'", ! PyString_AsString(name_obj)); Py_INCREF(dialect_obj); return dialect_obj; --- 112,116 ---- dialect_obj = PyDict_GetItem(dialects, name_obj); if (dialect_obj == NULL) ! return PyErr_Format(error_obj, "unknown dialect"); Py_INCREF(dialect_obj); return dialect_obj; *************** *** 407,411 **** PyType_GenericAlloc, /* tp_alloc */ dialect_new, /* tp_new */ ! PyObject_Del, /* tp_free */ }; --- 406,410 ---- PyType_GenericAlloc, /* tp_alloc */ dialect_new, /* tp_new */ ! 0, /* tp_free */ }; *************** *** 1173,1178 **** csv_list_dialects(PyObject *module, PyObject *args) { - if (!PyArg_ParseTuple(args, "")) - return NULL; return PyDict_Keys(dialects); } --- 1172,1175 ---- *************** *** 1183,1189 **** PyObject *name_obj, *dialect_obj; ! if (!PyArg_ParseTuple(args, "O!O", ! &PyBaseString_Type, &name_obj, ! &dialect_obj)) { return NULL; } --- 1180,1188 ---- PyObject *name_obj, *dialect_obj; ! if (!PyArg_ParseTuple(args, "OO", &name_obj, &dialect_obj)) ! return NULL; ! if (!PyString_Check(name_obj) && PyUnicode_Check(name_obj)) { ! PyErr_SetString(PyExc_TypeError, ! "dialect name must be a string or unicode"); return NULL; } *************** *** 1195,1199 **** Py_DECREF(dialect_obj); if (new_dia == NULL) ! return 0; dialect_obj = new_dia; } --- 1194,1198 ---- Py_DECREF(dialect_obj); if (new_dia == NULL) ! return NULL; dialect_obj = new_dia; } *************** *** 1202,1206 **** PyErr_SetString(PyExc_TypeError, "dialect must be an instance"); Py_DECREF(dialect_obj); ! return 0; } if (PyObject_SetAttrString(dialect_obj, "_name", name_obj) < 0) { --- 1201,1205 ---- PyErr_SetString(PyExc_TypeError, "dialect must be an instance"); Py_DECREF(dialect_obj); ! return NULL; } if (PyObject_SetAttrString(dialect_obj, "_name", name_obj) < 0) { *************** *** 1222,1230 **** PyObject *name_obj; ! if (!PyArg_ParseTuple(args, "O!", &PyBaseString_Type, &name_obj)) return NULL; if (PyDict_DelItem(dialects, name_obj) < 0) ! return PyErr_Format(error_obj, "unknown dialect '%s'", ! PyString_AsString(name_obj)); Py_INCREF(Py_None); return Py_None; --- 1221,1228 ---- PyObject *name_obj; ! if (!PyArg_ParseTuple(args, "O", &name_obj)) return NULL; if (PyDict_DelItem(dialects, name_obj) < 0) ! return PyErr_Format(error_obj, "unknown dialect"); Py_INCREF(Py_None); return Py_None; *************** *** 1236,1240 **** PyObject *name_obj; ! if (!PyArg_ParseTuple(args, "O!", &PyBaseString_Type, &name_obj)) return NULL; return get_dialect_from_registry(name_obj); --- 1234,1238 ---- PyObject *name_obj; ! if (!PyArg_ParseTuple(args, "O", &name_obj)) return NULL; return get_dialect_from_registry(name_obj); *************** *** 1353,1357 **** METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, { "list_dialects", (PyCFunction)csv_list_dialects, ! METH_VARARGS, csv_list_dialects_doc}, { "register_dialect", (PyCFunction)csv_register_dialect, METH_VARARGS, csv_register_dialect_doc}, --- 1351,1355 ---- METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, { "list_dialects", (PyCFunction)csv_list_dialects, ! METH_NOARGS, csv_list_dialects_doc}, { "register_dialect", (PyCFunction)csv_register_dialect, METH_VARARGS, csv_register_dialect_doc}, From andrewmcnamara@users.sourceforge.net Mon Feb 10 09:41:32 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 01:41:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv28955/test Modified Files: test_csv.py Log Message: A few minor changes so the module works with Python2.2 Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** test_csv.py 10 Feb 2003 08:40:07 -0000 1.24 --- test_csv.py 10 Feb 2003 09:41:29 -0000 1.25 *************** *** 152,158 **** def test_registry_badargs(self): self.assertRaises(TypeError, csv.list_dialects, None) ! self.assertRaises(TypeError, csv.get_dialect, None) self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") ! self.assertRaises(TypeError, csv.unregister_dialect, None) self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") self.assertRaises(TypeError, csv.register_dialect, None) --- 152,158 ---- def test_registry_badargs(self): self.assertRaises(TypeError, csv.list_dialects, None) ! self.assertRaises(csv.Error, csv.get_dialect, None) self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") ! self.assertRaises(csv.Error, csv.unregister_dialect, None) self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") self.assertRaises(TypeError, csv.register_dialect, None) From jvr@users.sourceforge.net Mon Feb 10 09:57:12 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 01:57:12 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.648,1.649 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv3439/Misc Modified Files: NEWS Log Message: mention unicode support in compile, eval and exec Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.648 retrieving revision 1.649 diff -C2 -d -r1.648 -r1.649 *** NEWS 10 Feb 2003 02:12:43 -0000 1.648 --- NEWS 10 Feb 2003 09:57:08 -0000 1.649 *************** *** 13,16 **** --- 13,19 ---- ----------------- + - compile(), eval() and the exec statement now fully support source code + passed as unicode strings. + - int subclasses can be initialized with longs if the value fits in an int. See SF bug #683467. From mwh@python.net Mon Feb 10 09:58:42 2003 From: mwh@python.net (Michael Hudson) Date: Mon, 10 Feb 2003 09:58:42 +0000 Subject: [Python-checkins] python/dist/src/Modules parsermodule.c,2.75,2.76 In-Reply-To: <20030208182820.GK23059@epoch.metaslash.com> (Neal Norwitz's message of "Sat, 08 Feb 2003 13:28:20 -0500") References: <20030208182820.GK23059@epoch.metaslash.com> Message-ID: <2m4r7cmp7x.fsf@starship.python.net> Neal Norwitz writes: >> *************** >> *** 1695,1698 **** >> --- 1718,1727 ---- >> + if (!res && !PyErr_Occurred()) >> + err_string("illegal global statement"); >> + >> + if (!res && !PyErr_Occurred()) >> + err_string("illegal global statement"); > > Isn't only one of these is required? Uh, yeah. Silly patch program. Sorry about that. Cheers, M. -- > so python will fork if activestate starts polluting it? I find it more relevant to speculate on whether Python would fork if the merpeople start invading our cities riding on the backs of giant king crabs. -- Brian Quinlan, comp.lang.python From jvr@users.sourceforge.net Mon Feb 10 10:06:23 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 02:06:23 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.649,1.650 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv7554/Misc Modified Files: NEWS Log Message: mention unicode file name support on OSX Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.649 retrieving revision 1.650 diff -C2 -d -r1.649 -r1.650 *** NEWS 10 Feb 2003 09:57:08 -0000 1.649 --- NEWS 10 Feb 2003 10:06:18 -0000 1.650 *************** *** 1325,1328 **** --- 1325,1332 ---- - Mac/Relnotes is gone, the release notes are now here. + - Python (the OSX-only, unix-based version, not the OS9-compatible CFM + version) now fully supports unicode strings as arguments to various file + system calls, eg. open(), file(), os.stat() and os.listdir(). + - The current naming convention for Python on the Macintosh is that MacPython refers to the unix-based OSX-only version, and MacPython-OS9 refers to the From andrewmcnamara@users.sourceforge.net Mon Feb 10 10:41:11 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 02:41:11 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv20704/test Modified Files: test_csv.py Log Message: Picked up a couple of module bugs while using test coverage tools, improved test coverage slightly. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** test_csv.py 10 Feb 2003 09:41:29 -0000 1.25 --- test_csv.py 10 Feb 2003 10:41:09 -0000 1.26 *************** *** 41,44 **** --- 41,48 ---- obj.dialect.escapechar = None self.assertEqual(obj.dialect.escapechar, None) + self.assertRaises(TypeError, delattr, obj.dialect, 'quoting') + self.assertRaises(TypeError, setattr, obj.dialect, 'quoting', None) + obj.dialect.quoting = csv.QUOTE_MINIMAL + self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL) def test_reader_attrs(self): *************** *** 152,160 **** --- 156,167 ---- def test_registry_badargs(self): self.assertRaises(TypeError, csv.list_dialects, None) + self.assertRaises(TypeError, csv.get_dialect) self.assertRaises(csv.Error, csv.get_dialect, None) self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") + self.assertRaises(TypeError, csv.unregister_dialect) self.assertRaises(csv.Error, csv.unregister_dialect, None) self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") self.assertRaises(TypeError, csv.register_dialect, None) + self.assertRaises(TypeError, csv.register_dialect, None, None) self.assertRaises(TypeError, csv.register_dialect, "nonesuch", None) class bogus: From andrewmcnamara@users.sourceforge.net Mon Feb 10 10:41:11 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 02:41:11 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv20704 Modified Files: _csv.c Log Message: Picked up a couple of module bugs while using test coverage tools, improved test coverage slightly. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** _csv.c 10 Feb 2003 09:41:28 -0000 1.27 --- _csv.c 10 Feb 2003 10:41:08 -0000 1.28 *************** *** 117,120 **** --- 117,131 ---- } + static int + check_delattr(PyObject *v) + { + if (v == NULL) { + PyErr_SetString(PyExc_TypeError, + "Cannot delete attribute"); + return -1; + } + return 0; + } + static PyObject * get_string(PyObject *str) *************** *** 127,135 **** set_string(PyObject **str, PyObject *v) { ! if (v == NULL) { ! PyErr_SetString(PyExc_AttributeError, ! "Cannot delete attribute"); ! return -1; ! } if (!PyString_Check(v) && !PyUnicode_Check(v)) { PyErr_BadArgument(); --- 138,143 ---- set_string(PyObject **str, PyObject *v) { ! if (check_delattr(v) < 0) ! return -1; if (!PyString_Check(v) && !PyUnicode_Check(v)) { PyErr_BadArgument(); *************** *** 156,164 **** set_None_as_nullchar(char * addr, PyObject *v) { ! if (v == NULL) { ! PyErr_SetString(PyExc_AttributeError, ! "Cannot delete attribute"); ! return -1; ! } if (v == Py_None) *addr = '\0'; --- 164,169 ---- set_None_as_nullchar(char * addr, PyObject *v) { ! if (check_delattr(v) < 0) ! return -1; if (v == Py_None) *addr = '\0'; *************** *** 208,211 **** --- 213,218 ---- StyleDesc *qs = quote_styles; + if (check_delattr(v) < 0) + return -1; if (!PyInt_Check(v)) { PyErr_BadArgument(); *************** *** 1182,1186 **** if (!PyArg_ParseTuple(args, "OO", &name_obj, &dialect_obj)) return NULL; ! if (!PyString_Check(name_obj) && PyUnicode_Check(name_obj)) { PyErr_SetString(PyExc_TypeError, "dialect name must be a string or unicode"); --- 1189,1193 ---- if (!PyArg_ParseTuple(args, "OO", &name_obj, &dialect_obj)) return NULL; ! if (!PyString_Check(name_obj) && !PyUnicode_Check(name_obj)) { PyErr_SetString(PyExc_TypeError, "dialect name must be a string or unicode"); From guido@python.org Mon Feb 10 13:01:51 2003 From: guido@python.org (Guido van Rossum) Date: Mon, 10 Feb 2003 08:01:51 -0500 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: "Your message of Mon, 10 Feb 2003 01:22:04 PST." References: Message-ID: <200302101301.h1AD1pN00300@pcp02138704pcs.reston01.va.comcast.net> > My previous checkin caused compile() to no longer accept buffers, as noted > my MAL. Fixed. (Btw. eval() still doesn't take buffers, but that was so > even before my patch.) Well, I think eval() should be fixed to accept buffers too. That it doesn't surely was an oversight and not by design. --Guido van Rossum (home page: http://www.python.org/~guido/) From guido@python.org Mon Feb 10 13:02:47 2003 From: guido@python.org (Guido van Rossum) Date: Mon, 10 Feb 2003 08:02:47 -0500 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: "Your message of Mon, 10 Feb 2003 10:39:57 +0100." <9DBFE94E-3CDB-11D7-AF40-0030655234CE@cwi.nl> References: <9DBFE94E-3CDB-11D7-AF40-0030655234CE@cwi.nl> Message-ID: <200302101302.h1AD2mM00315@pcp02138704pcs.reston01.va.comcast.net> > > jvr@users.sourceforge.net wrote: > > > >> Index: bltinmodule.c > >> =================================================================== > >> RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v > >> retrieving revision 2.276 > >> retrieving revision 2.277 > >> diff -C2 -d -r2.276 -r2.277 > >> *** bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 > >> --- bltinmodule.c 10 Feb 2003 09:22:01 -0000 2.277 > >> *************** > >> *** 19,22 **** > >> --- 19,24 ---- > >> #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) > >> const char *Py_FileSystemDefaultEncoding = "mbcs"; > >> + #elif defined(__APPLE__) > >> + const char *Py_FileSystemDefaultEncoding = "utf-8"; > >> #else > >> const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ > > > > Whoops, this wasn't meant to be checked in as a side effect of this... > > But then again, it should be ckecked in anyway, except perhaps with a > > different switch. > > I don't like looking at __APPLE__ either (it looks too broad), but I > haven't found > anything else. So I'd say leave it as is. Really? Is there nothing to distinguish OS 9 from OS X? I don't believe that. --Guido van Rossum (home page: http://www.python.org/~guido/) From jackjansen@users.sourceforge.net Mon Feb 10 13:08:06 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 05:08:06 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv23847 Modified Files: pimp.py Log Message: Added preInstall and postInstall commands to packages. PIL needs this (preInstall, at least). Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pimp.py 9 Feb 2003 23:10:20 -0000 1.1 --- pimp.py 10 Feb 2003 13:08:04 -0000 1.2 *************** *** 177,181 **** downloadURL=None, installTest=None, ! prerequisites=None): self._db = db self.name = name --- 177,183 ---- downloadURL=None, installTest=None, ! prerequisites=None, ! preInstall=None, ! postInstall=None): self._db = db self.name = name *************** *** 187,190 **** --- 189,194 ---- self._installTest = installTest self._prerequisites = prerequisites + self._preInstall = preInstall + self._postInstall = postInstall def dump(self): *************** *** 206,209 **** --- 210,217 ---- if self._prerequisites: dict['prerequisites'] = self._prerequisites + if self._preInstall: + dict['preInstall'] = self._preInstall + if self._postInstall: + dict['postInstall'] = self._postInstall return dict *************** *** 313,318 **** --- 321,334 ---- if msg: return "unpack %s: %s" % (_fmtpackagename(self), msg) + if self._preInstall: + if self._cmd(output, self._buildDirname, self._preInstall): + return "pre-install %s: running \"%s\" failed" % \ + (_fmtpackagename(self), self._preInstall) if self._cmd(output, self._buildDirname, sys.executable, "setup.py install"): return "install %s: running \"setup.py install\" failed" % _fmtpackagename(self) + if self._postInstall: + if self._cmd(output, self._buildDirname, self._postInstall): + return "post-install %s: running \"%s\" failed" % \ + (_fmtpackagename(self), self._postInstall) return None From doerwalter@users.sourceforge.net Mon Feb 10 13:19:15 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 05:19:15 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.277,2.278 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv29110/Python Modified Files: bltinmodule.c Log Message: Change filterstring() and filterunicode(): If the object is not a real str or unicode but an instance of a subclass, construct the output via looping over __getitem__. This guarantees that the result is the same for function==None and function==lambda x:x This doesn't happen for tuples, because filtertuple() uses PyTuple_GetItem(). (This was discussed on SF bug #665835). Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.277 retrieving revision 2.278 diff -C2 -d -r2.277 -r2.278 *** bltinmodule.c 10 Feb 2003 09:22:01 -0000 2.277 --- bltinmodule.c 10 Feb 2003 13:19:12 -0000 2.278 *************** *** 1935,1948 **** if (func == Py_None) { ! /* No character is ever false -- share input string ! * (if it's not a subclass) */ ! if (PyString_CheckExact(strobj)) Py_INCREF(strobj); ! else ! strobj = PyString_FromStringAndSize( ! PyString_AS_STRING(strobj), ! len ! ); ! return strobj; } if ((result = PyString_FromStringAndSize(NULL, len)) == NULL) --- 1935,1946 ---- if (func == Py_None) { ! /* If it's a real string we can return the original, ! * as no character is ever false and __getitem__ ! * does return this character. If it's a subclass ! * we must go through the __getitem__ loop */ ! if (PyString_CheckExact(strobj)) { Py_INCREF(strobj); ! return strobj; ! } } if ((result = PyString_FromStringAndSize(NULL, len)) == NULL) *************** *** 1950,1954 **** for (i = j = 0; i < len; ++i) { ! PyObject *item, *arg, *good; int ok; --- 1948,1952 ---- for (i = j = 0; i < len; ++i) { ! PyObject *item; int ok; *************** *** 1956,1972 **** if (item == NULL) goto Fail_1; ! arg = Py_BuildValue("(O)", item); ! if (arg == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! good = PyEval_CallObject(func, arg); ! Py_DECREF(arg); ! if (good == NULL) { ! Py_DECREF(item); ! goto Fail_1; } - ok = PyObject_IsTrue(good); - Py_DECREF(good); if (ok) { int reslen; --- 1954,1975 ---- if (item == NULL) goto Fail_1; ! if (func==Py_None) { ! ok = 1; ! } else { ! PyObject *arg, *good; ! arg = Py_BuildValue("(O)", item); ! if (arg == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! good = PyEval_CallObject(func, arg); ! Py_DECREF(arg); ! if (good == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! ok = PyObject_IsTrue(good); ! Py_DECREF(good); } if (ok) { int reslen; *************** *** 2027,2040 **** if (func == Py_None) { ! /* No character is ever false -- share input string ! * (it if's not a subclass) */ ! if (PyUnicode_CheckExact(strobj)) Py_INCREF(strobj); ! else ! strobj = PyUnicode_FromUnicode( ! PyUnicode_AS_UNICODE(strobj), ! len ! ); ! return strobj; } if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL) --- 2030,2041 ---- if (func == Py_None) { ! /* If it's a real string we can return the original, ! * as no character is ever false and __getitem__ ! * does return this character. If it's a subclass ! * we must go through the __getitem__ loop */ ! if (PyUnicode_CheckExact(strobj)) { Py_INCREF(strobj); ! return strobj; ! } } if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL) *************** *** 2048,2064 **** if (item == NULL) goto Fail_1; ! arg = Py_BuildValue("(O)", item); ! if (arg == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! good = PyEval_CallObject(func, arg); ! Py_DECREF(arg); ! if (good == NULL) { ! Py_DECREF(item); ! goto Fail_1; } - ok = PyObject_IsTrue(good); - Py_DECREF(good); if (ok) { int reslen; --- 2049,2069 ---- if (item == NULL) goto Fail_1; ! if (func == Py_None) { ! ok = 1; ! } else { ! arg = Py_BuildValue("(O)", item); ! if (arg == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! good = PyEval_CallObject(func, arg); ! Py_DECREF(arg); ! if (good == NULL) { ! Py_DECREF(item); ! goto Fail_1; ! } ! ok = PyObject_IsTrue(good); ! Py_DECREF(good); } if (ok) { int reslen; From doerwalter@users.sourceforge.net Mon Feb 10 13:19:15 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 05:19:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv29110/Lib/test Modified Files: test_builtin.py Log Message: Change filterstring() and filterunicode(): If the object is not a real str or unicode but an instance of a subclass, construct the output via looping over __getitem__. This guarantees that the result is the same for function==None and function==lambda x:x This doesn't happen for tuples, because filtertuple() uses PyTuple_GetItem(). (This was discussed on SF bug #665835). Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_builtin.py 10 Feb 2003 08:21:05 -0000 1.11 --- test_builtin.py 10 Feb 2003 13:19:13 -0000 1.12 *************** *** 419,442 **** def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): ! pass class str2(str): ! pass inputs = { ! tuple2: [(), (1,2,3)], ! str2: ["", "123"] } if have_unicode: class unicode2(unicode): ! pass ! inputs[unicode2] = [unicode(), unicode("123")] ! for func in funcs: ! for (cls, inps) in inputs.iteritems(): ! for inp in inps: ! out = filter(func, cls(inp)) ! self.assertEqual(inp, out) ! self.assert_(not isinstance(out, cls)) def test_float(self): --- 419,456 ---- def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses + # and that the result always go's through __getitem__ + # FIXME: For tuple currently it doesn't go through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): ! def __getitem__(self, index): ! return 2*tuple.__getitem__(self, index) class str2(str): ! def __getitem__(self, index): ! return 2*str.__getitem__(self, index) inputs = { ! tuple2: {(): (), (1, 2, 3): (1, 2, 3)}, # FIXME ! str2: {"": "", "123": "112233"} } if have_unicode: class unicode2(unicode): ! def __getitem__(self, index): ! return 2*unicode.__getitem__(self, index) ! inputs[unicode2] = { ! unicode(): unicode(), ! unicode("123"): unicode("112233") ! } ! for (cls, inps) in inputs.iteritems(): ! for (inp, exp) in inps.iteritems(): ! # make sure the output goes through __getitem__ ! # even if func is None ! self.assertEqual( ! filter(funcs[0], cls(inp)), ! filter(funcs[1], cls(inp)) ! ) ! for func in funcs: ! outp = filter(func, cls(inp)) ! self.assertEqual(outp, exp) ! self.assert_(not isinstance(outp, cls)) def test_float(self): From jackjansen@users.sourceforge.net Mon Feb 10 13:38:47 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 05:38:47 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv5925 Modified Files: pimp.py Log Message: Use MD5 checksums to check archive integrity and forestall downloads. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** pimp.py 10 Feb 2003 13:08:04 -0000 1.2 --- pimp.py 10 Feb 2003 13:38:44 -0000 1.3 *************** *** 5,8 **** --- 5,9 ---- import plistlib import distutils.util + import md5 _scriptExc_NotInstalled = "pimp._scriptExc_NotInstalled" *************** *** 26,29 **** --- 27,35 ---- ] + class MyURLopener(urllib.FancyURLopener): + """Like FancyURLOpener, but we do want to get errors as exceptions""" + def http_error_default(self, url, fp, errcode, errmsg, headers): + urllib.URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) + class PimpPreferences: def __init__(self, *************** *** 179,183 **** prerequisites=None, preInstall=None, ! postInstall=None): self._db = db self.name = name --- 185,190 ---- prerequisites=None, preInstall=None, ! postInstall=None, ! MD5Sum=None): self._db = db self.name = name *************** *** 191,194 **** --- 198,202 ---- self._preInstall = preInstall self._postInstall = postInstall + self._MD5Sum = MD5Sum def dump(self): *************** *** 214,217 **** --- 222,227 ---- if self._postInstall: dict['postInstall'] = self._postInstall + if self._MD5Sum: + dict['MD5Sum'] = self._MD5Sum return dict *************** *** 288,298 **** path = urllib.url2pathname(path) filename = os.path.split(path)[1] ! self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) ! if self._cmd(output, self._db.preferences.downloadDir, "curl", ! "--output", self.archiveFilename, ! self.downloadURL): ! return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" def unpackSinglePackage(self, output): --- 298,322 ---- path = urllib.url2pathname(path) filename = os.path.split(path)[1] ! self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) ! if not self._archiveOK(): ! if self._cmd(output, self._db.preferences.downloadDir, ! "curl", ! "--output", self.archiveFilename, ! self.downloadURL): ! return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: return "archive not found after download" + if not self._archiveOK(): + return "archive does not have correct MD5 checksum" + + def _archiveOK(self): + if not os.path.exists(self.archiveFilename): + return 0 + if not self._MD5Sum: + sys.stderr.write("Warning: no MD5Sum for %s\n" % _fmtpackagename(self)) + return 1 + data = open(self.archiveFilename, 'rb').read() + checksum = md5.new(data).hexdigest() + return checksum == self._MD5Sum def unpackSinglePackage(self, output): *************** *** 403,407 **** db.appendURL(prefs.pimpDatabase) ! if mode =='list': if not args: args = db.listnames() --- 427,433 ---- db.appendURL(prefs.pimpDatabase) ! if mode == 'dump': ! db.dump(sys.stdout) ! elif mode =='list': if not args: args = db.listnames() *************** *** 419,423 **** print "\tHome page:\t", pkg.longdesc print "\tDownload URL:\t", pkg.downloadURL ! if mode =='status': if not args: args = db.listnames() --- 445,449 ---- print "\tHome page:\t", pkg.longdesc print "\tDownload URL:\t", pkg.downloadURL ! elif mode =='status': if not args: args = db.listnames() *************** *** 473,476 **** --- 499,503 ---- print " pimp [-v] -l [package ...] Show package information" print " pimp [-vf] -i package ... Install packages" + print " pimp -d Dump database to stdout" print "Options:" print " -v Verbose" *************** *** 479,483 **** try: ! opts, args = getopt.getopt(sys.argv[1:], "slifv") except getopt.Error: _help() --- 506,510 ---- try: ! opts, args = getopt.getopt(sys.argv[1:], "slifvd") except getopt.Error: _help() *************** *** 496,503 **** _help() mode = 'list' ! if o == '-L': if mode: _help() ! mode = 'longlist' if o == '-i': mode = 'install' --- 523,530 ---- _help() mode = 'list' ! if o == '-d': if mode: _help() ! mode = 'dump' if o == '-i': mode = 'install' From jackjansen@users.sourceforge.net Mon Feb 10 14:02:35 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:02:35 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils sysconfig.py,1.56,1.57 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv16445 Modified Files: sysconfig.py Log Message: Pick up Makefile variable BASECFLAGS too. This is needed since OPT was split into OPT and BASECFLAGS (Makefile.pre.in rev. 1.108), because now there are essential CFLAGS in BASECFLAGS. Index: sysconfig.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/sysconfig.py,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** sysconfig.py 14 Nov 2002 02:25:41 -0000 1.56 --- sysconfig.py 10 Feb 2003 14:02:33 -0000 1.57 *************** *** 147,152 **** """ if compiler.compiler_type == "unix": ! (cc, cxx, opt, ccshared, ldshared, so_ext) = \ ! get_config_vars('CC', 'CXX', 'OPT', 'CCSHARED', 'LDSHARED', 'SO') if os.environ.has_key('CC'): --- 147,152 ---- """ if compiler.compiler_type == "unix": ! (cc, cxx, opt, basecflags, ccshared, ldshared, so_ext) = \ ! get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', 'CCSHARED', 'LDSHARED', 'SO') if os.environ.has_key('CC'): *************** *** 160,163 **** --- 160,165 ---- if os.environ.has_key('LDFLAGS'): ldshared = ldshared + ' ' + os.environ['LDFLAGS'] + if basecflags: + opt = basecflags + ' ' + opt if os.environ.has_key('CFLAGS'): opt = opt + ' ' + os.environ['CFLAGS'] From jackjansen@users.sourceforge.net Mon Feb 10 14:19:17 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:19:17 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv25111 Modified Files: pimp.py Log Message: - Better exception when the database isn't found. - Allow for "manual:" pseudo-scheme in downloadURL to signal that the download should be done manually. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** pimp.py 10 Feb 2003 13:38:44 -0000 1.3 --- pimp.py 10 Feb 2003 14:19:14 -0000 1.4 *************** *** 105,109 **** return self._urllist.append(url) ! fp = urllib.urlopen(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc --- 105,109 ---- return self._urllist.append(url) ! fp = MyURLopener().open(url).fp dict = plistlib.Plist.fromFile(fp) # Test here for Pimp version, etc *************** *** 300,303 **** --- 300,305 ---- self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename) if not self._archiveOK(): + if scheme == 'manual': + return "Please download package manually and save as %s" % self.archiveFilename if self._cmd(output, self._db.preferences.downloadDir, "curl", From Jack.Jansen@cwi.nl Mon Feb 10 14:32:12 2003 From: Jack.Jansen@cwi.nl (Jack Jansen) Date: Mon, 10 Feb 2003 15:32:12 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: <200302101302.h1AD2mM00315@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <71939A38-3D04-11D7-AF40-0030655234CE@cwi.nl> On Monday, Feb 10, 2003, at 14:02 Europe/Amsterdam, Guido van Rossum wrote: >> I don't like looking at __APPLE__ either (it looks too broad), but I >> haven't found >> anything else. So I'd say leave it as is. > > Really? Is there nothing to distinguish OS 9 from OS X? I don't > believe that. There is, if you import MacOS-specific headers (Universal Headers on MacOS9, or Carbon/Carbon.h on OSX). Then you have defines like TARGET_API_MAC_OSX and TARGET_API_MAC_OS8 and many many more. But by default you only get what gcc predefines, and that's preciously little. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From just@letterror.com Mon Feb 10 14:36:44 2003 From: just@letterror.com (Just van Rossum) Date: Mon, 10 Feb 2003 15:36:44 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: <71939A38-3D04-11D7-AF40-0030655234CE@cwi.nl> Message-ID: Jack Jansen wrote: > > Really? Is there nothing to distinguish OS 9 from OS X? I don't > > believe that. > > There is, if you import MacOS-specific headers (Universal Headers on > MacOS9, or Carbon/Carbon.h on OSX). > Then you have defines like TARGET_API_MAC_OSX and TARGET_API_MAC_OS8 > and many many more. > > But by default you only get what gcc predefines, and that's preciously > little. The question remains: is __APPLE__ defined when compiling for OS9 or not? If not, we're fine, but I'd like to _know_... Just From tim_one@users.sourceforge.net Mon Feb 10 14:48:33 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:48:33 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.278,2.279 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv6185/Python Modified Files: bltinmodule.c Log Message: Squashed compiler wng about signed/unsigned clash in comparison. Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.278 retrieving revision 2.279 diff -C2 -d -r2.278 -r2.279 *** bltinmodule.c 10 Feb 2003 13:19:12 -0000 2.278 --- bltinmodule.c 10 Feb 2003 14:48:29 -0000 2.279 *************** *** 363,367 **** if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) return NULL; ! if (length != strlen(str)) { PyErr_SetString(PyExc_TypeError, "expected string without null bytes"); --- 363,367 ---- if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length)) return NULL; ! if ((size_t)length != strlen(str)) { PyErr_SetString(PyExc_TypeError, "expected string without null bytes"); From goodger@users.sourceforge.net Mon Feb 10 14:51:47 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:51:47 -0800 Subject: [Python-checkins] python/nondist/peps pep-0309.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv7836 Added Files: pep-0309.txt Log Message: Built-in Closure Type, by Peter Harris --- NEW FILE: pep-0309.txt --- PEP: 309 Title: Built-in Closure Type Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/02/10 14:51:45 $ Author: Peter Harris Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 08-Feb-2003 Python-Version: 2.4 Post-History: Abstract ========= This proposal is for a built-in closure type for Python that allows a new callable to be constructed from another callable and a partial argument list (including positional and keyword arguments). A concise syntax shorthand for closures is suggested (tentatively). Motivation =========== Closures are useful as functional 'sections' or as convenient anonymous functions for use as callbacks. In some functional languages, (e.g. Miranda) you can use an expression such as ``(+1)`` to mean the equivalent of Python's ``(lambda x: x + 1)``. In general, languages like that are strongly typed, so the compiler always knows the number of arguments expected and can do the right thing when presented with a functor and less arguments than expected. Python has more flexible argument-passing, and so closures cannot be implicit in the same way. Instead of using them, a Python programmer will probably either define another named function or use a lambda. But lambda syntax is horrible, especially when you want to do something complex. We need something better. Rationale ========== Here is one way to do closures in Python:: class closure(object): def __init__(self, fn, *args, **kw): self.fn, self.args, self.kw = (fn, args, kw) def __call__(self, *args, **kw): d = self.kw.copy() d.update(kw) return self.fn(*(self.args + args), **d) Note that when the closure is called, positional arguments are appended to those provided to the constructor, and keyword arguments override and augment those provided to the constructor. So ``closure(operator.add,1)`` is a bit like ``(lambda x: 1+x)``, and ``closure(Tkinter.Label,fg='blue')`` is a callable like the Tkinter Label class, but with a blue foreground by default. I think a built-in type called ``closure``, that behaves the same way but maybe implemented more efficiently, would be very useful. Tentative Syntax Proposal ========================== I know syntax proposals have the odds stacked against them, and introducing new punctuation characters is frowned upon, but I think closures are a sufficiently powerful abstraction to deserve it. I propose the syntax ``fn@(*args,**kw)``, meaning the same as ``closure(fn,*args,**kw)``. I have no idea what havoc this would wreak on the parser. At least there are no backwards-compatibility issues because the @ character isn't a legal operator in any previous versions of Python. The @ sign is used in some assembly languages to imply register indirection, and the use here is also a kind of indirection. ``f@(x)`` is not ``f(x)`` , but a thing that becomes ``f(x)`` when you call it. Examples of Use --------------- Using closures as callbacks with bound arguments:: def handler(arg1, arg2, opt=0): #whatever... button1 = Button(window, text="Action A", command=handler@('A','1')) button2 = Button(window, text="Action B", command=handler@('B','2',opt=1)) Convenience functions :: nextarg = sys.argv.pop@(0) Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From goodger@users.sourceforge.net Mon Feb 10 14:52:53 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:52:53 -0800 Subject: [Python-checkins] python/nondist/peps pep-0310.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv8313 Added Files: pep-0310.txt Log Message: Reliable Acquisition/Release Pairs, by Michael Hudson and Paul Moore --- NEW FILE: pep-0310.txt --- PEP: 310 Title: Syntax for Reliable Acquisition/Release Pairs Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/02/10 14:52:51 $ Author: Michael Hudson , Paul Moore Status: Draft Type: Standards Track Content-Type: text/plain Created: 18-Dec-2002 Python-Version: 2.4 Post-History: Abstract It would be nice to have a less typing-intense way of writing: the_lock.acquire() try: .... finally: the_lock.release() This PEP proposes a piece of syntax (a 'with' block) and a "small-i" interface that generalizes the above. Rationale One of the advantages of Python's exception handling philosophy is that it makes it harder to do the "wrong" thing (e.g. failing to check the return value of some system call). Currently, this does not apply to resource cleanup. The current syntax for acquisition and release of a resource (for example, a lock) is the_lock.acquire() try: .... finally: the_lock.release() This syntax separates the acquisition and release by a (possibly large) block of code, which makes it difficult to confirm "at a glance" that the code manages the resource correctly. Another common error is to code the "acquire" call within the try block, which incorrectly releases the lock if the acquire fails. Basic Syntax and Semantics The syntax of a 'with' statement is as follows:: 'with' [ var '=' ] expr ':' suite This statement is defined as being equivalent to the following sequence of statements: var = expr if hasattr(var, "__enter__"): var.__enter__() try: suite finally: if hasattr(var, "__exit__"): var.__exit__() If the variable is omitted, an unnamed object is allocated on the stack. In that case, the suite has no access to the unnamed object. Possible Extensions A number of potential extensions to the basic syntax have been discussed on the Python Developers list. None of these extensions are included in the solution proposed by this PEP. In many cases, the arguments are nearly equally strong in both directions. In such cases, the PEP has always chosen simplicity, simply because where extra power is needed, the existing try block is available. Multiple expressions One proposal was for allowing multiple expressions within one 'with' statement. The __enter__ methods would be called left to right, and the __exit__ methods right to left. The advantage of doing so is that where more than one resource is being managed, nested 'with' statements will result in code drifting towards the right margin. The solution to this problem is the same as for any other deep nesting - factor out some of the code into a separate function. Furthermore, the question of what happens if one of the __exit__ methods raises an exception (should the other __exit__ methods be called?) needs to be addressed. Exception handling An extension to the protocol to include an optional __except__ handler, which is called when an exception is raised, and which can handle or re-raise the exception, has been suggested. It is not at all clear that the semantics of this extension can be made precise and understandable. For example, should the equivalent code be try ... except ... else if an exception handler is defined, and try ... finally if not? How can this be determined at compile time, in general? The alternative is to define the code as expanding to a try ... except inside a try ... finally. But this may not do the right thing in real life. The only use case identified for exception handling is with transactional processing (commit on a clean finish, and rollback on an exception). This is probably just as easy to handle with a conventional try ... except ... else block, and so the PEP does not include any support for exception handlers. Implementation Notes The optional assignment in 'with' [ var '=' ] expr ':' was initially considered to be too hard to parse correctly. However, by parsing the statement as 'with' expr [ '=' expr ] ':' and interpreting the result in the compiler phase, this can be worked around. There is a potential race condition in the code specified as equivalent to the with statement. For example, if a KeyboardInterrupt exception is raised between the completion of the __enter__ method call and the start of the try block, the __exit__ method will not be called. This can lead to resource leaks, or to deadlocks. [XXX Guido has stated that he cares about this sort of race condition, and intends to write some C magic to handle them. The implementation of the 'with' statement should copy this.] Open Issues Should existing classes (for example, file-like objects and locks) gain appropriate __enter__ and __exit__ methods? The obvious reason in favour is convenience (no adapter needed). The argument against is that if built-in files have this but (say) StringIO does not, then code that uses "with" on a file object can't be reused with a StringIO object. So __exit__ = close becomes a part of the "file-like object" protocol, which user-defined classes may need to support. The __enter__ hook may be unnecessary - for many use cases, an adapter class is needed and in that case, the work done by the __enter__ hook can just as easily be done in the __init__ hook. If a way of controlling object lifetimes explicitly was available, the function of the __exit__ hook could be taken over by the existing __del__ hook. Unfortunately, no workable proposal for controlling object lifetimes has been made so far. Alternative Ideas IEXEC: Holger Krekel -- generalised approach with XML-like syntax (no URL found...) Backwards Compatibility This PEP proposes a new keyword, so the __future__ game will need to be played. References There are various python-list and python-dev discussions that could be mentioned here. Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From goodger@users.sourceforge.net Mon Feb 10 14:54:13 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Mon, 10 Feb 2003 06:54:13 -0800 Subject: [Python-checkins] python/nondist/peps pep-0000.txt,1.228,1.229 pep-0306.txt,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv8911 Modified Files: pep-0000.txt pep-0306.txt Log Message: updated Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.228 retrieving revision 1.229 diff -C2 -d -r1.228 -r1.229 *** pep-0000.txt 7 Feb 2003 17:03:29 -0000 1.228 --- pep-0000.txt 10 Feb 2003 14:54:10 -0000 1.229 *************** *** 56,59 **** --- 56,60 ---- I 290 Code Migration and Modernization Hettinger I 291 Backward Compatibility for Standard Library Norwitz + I 306 How to Change Python's Grammar Hudson Accepted PEPs (accepted; may not be implemented yet) *************** *** 107,114 **** S 303 Extend divmod() for Multiple Divisors Bellman S 304 Controlling Generation of Bytecode Files Montanaro ! I 305 CSV File API Montanaro, et al ! I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR Finished PEPs (done, implemented in CVS) --- 108,116 ---- S 303 Extend divmod() for Multiple Divisors Bellman S 304 Controlling Generation of Bytecode Files Montanaro ! S 305 CSV File API Montanaro, et al S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR + S 309 Built-in Closure Type Harris + S 310 Reliable Acquisition/Release Pairs Hudson, Moore Finished PEPs (done, implemented in CVS) *************** *** 305,312 **** S 303 Extend divmod() for Multiple Divisors Bellman S 304 Controlling Generation of Bytecode Files Montanaro ! I 305 CSV File API Montanaro, et al I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR SR 666 Reject Foolish Indentation Creighton --- 307,316 ---- S 303 Extend divmod() for Multiple Divisors Bellman S 304 Controlling Generation of Bytecode Files Montanaro ! S 305 CSV File API Montanaro, et al I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR + S 309 Built-in Closure Type Harris + S 310 Reliable Acquisition/Release Pairs Hudson, Moore SR 666 Reject Foolish Indentation Creighton *************** *** 349,352 **** --- 353,357 ---- Goodger, David goodger@python.org Griffin, Grant g2@iowegian.com + Harris, Peter scav@blueyonder.co.uk Heller, Thomas theller@python.net Hetland, Magnus Lie magnus@hetland.org Index: pep-0306.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0306.txt,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** pep-0306.txt 30 Jan 2003 15:22:56 -0000 1.3 --- pep-0306.txt 10 Feb 2003 14:54:10 -0000 1.4 *************** *** 4,8 **** Last-Modified: $Date$ Author: Michael Hudson ! Status: Draft Type: Informational Content-Type: text/plain --- 4,8 ---- Last-Modified: $Date$ Author: Michael Hudson ! Status: Active Type: Informational Content-Type: text/plain From montanaro@users.sourceforge.net Mon Feb 10 15:06:49 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:06:49 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv14215 Modified Files: csv.py Log Message: add default value for short rows (#fieldnames > len(row)) Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** csv.py 10 Feb 2003 03:47:21 -0000 1.26 --- csv.py 10 Feb 2003 15:06:46 -0000 1.27 *************** *** 59,65 **** class DictReader: ! def __init__(self, f, fieldnames, rest=None, dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict self.rest = rest # key to catch long rows self.reader = reader(f, dialect, *args) --- 59,67 ---- class DictReader: ! def __init__(self, f, fieldnames, rest=None, restval=None, ! dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict self.rest = rest # key to catch long rows + self.restval = restval # default value for short rows self.reader = reader(f, dialect, *args) *************** *** 67,72 **** row = self.reader.next() d = dict(zip(self.fieldnames, row)) ! if len(self.fieldnames) < len(row) and self.rest != None: ! d[self.rest] = row[len(self.fieldnames):] return d --- 69,79 ---- row = self.reader.next() d = dict(zip(self.fieldnames, row)) ! lf = len(self.fieldnames) ! lr = len(row) ! if lf < lr and self.rest != None: ! d[self.rest] = row[lf:] ! elif lf > lr: ! for key in self.fieldnames[lr:]: ! d[key] = self.restval return d From Jack.Jansen@cwi.nl Mon Feb 10 15:07:29 2003 From: Jack.Jansen@cwi.nl (Jack Jansen) Date: Mon, 10 Feb 2003 16:07:29 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: Message-ID: <5F4F97C8-3D09-11D7-AF40-0030655234CE@cwi.nl> On Monday, Feb 10, 2003, at 15:36 Europe/Amsterdam, Just van Rossum wrote: > Jack Jansen wrote: > >>> Really? Is there nothing to distinguish OS 9 from OS X? I don't >>> believe that. >> >> There is, if you import MacOS-specific headers (Universal Headers on >> MacOS9, or Carbon/Carbon.h on OSX). >> Then you have defines like TARGET_API_MAC_OSX and TARGET_API_MAC_OS8 >> and many many more. >> >> But by default you only get what gcc predefines, and that's preciously >> little. > > The question remains: is __APPLE__ defined when compiling for OS9 or > not? If not, we're fine, but I'd like to _know_... If you compile with the MetroWerks compiler it isn't, so for the normal build of MacPython-OS9 there is no problem. If you build with Apple's MPW compilers it probably is, but (a) these compilers are horribly outdated and (b) it would take major surgery to compile Python with MPW anyway, nowadays. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From akuchling@users.sourceforge.net Mon Feb 10 15:08:19 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:08:19 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.115,1.116 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv14835 Modified Files: whatsnew23.tex Log Message: Add Neil's suggestions for avoiding this warning Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.115 retrieving revision 1.116 diff -C2 -d -r1.115 -r1.116 *** whatsnew23.tex 7 Feb 2003 20:22:33 -0000 1.115 --- whatsnew23.tex 10 Feb 2003 15:08:16 -0000 1.116 *************** *** 2077,2083 **** \item Large octal and hex literals such as ! 0xffffffff now trigger a \exception{FutureWarning} because currently they're stored as 32-bit numbers and result in a negative value, but ! in Python 2.4 they'll become positive long integers. \item You can no longer disable assertions by assigning to \code{__debug__}. --- 2077,2091 ---- \item Large octal and hex literals such as ! \code{0xffffffff} now trigger a \exception{FutureWarning}. Currently they're stored as 32-bit numbers and result in a negative value, but ! in Python 2.4 they'll become positive long integers. ! ! There are a few ways to fix this warning. If you really need a ! positive number, just add an \samp{L} to the end of the literal. If ! you're trying to get a 32-bit integer with low bits set and have ! previously used an expression such as \code{~(1 << 31)}, it's probably ! clearest to start with all bits set and clear the desired upper bits. ! For example, to clear just the top bit (bit 31), you could write ! \code{0xffffffffL {\&}{\textasciitilde}(1L<<31)}. \item You can no longer disable assertions by assigning to \code{__debug__}. From montanaro@users.sourceforge.net Mon Feb 10 15:10:20 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:10:20 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv15640 Modified Files: test_csv.py Log Message: add test for reading short rows (and filling in default values) Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** test_csv.py 10 Feb 2003 10:41:09 -0000 1.26 --- test_csv.py 10 Feb 2003 15:10:16 -0000 1.27 *************** *** 368,371 **** --- 368,373 ---- # Disabled, pending support in csv.utils module class TestDictFields(unittest.TestCase): + ### "long" means the row is longer than the number of fieldnames + ### "short" means there are fewer elements in the row than fieldnames def test_write_simple_dict(self): fileobj = StringIO() *************** *** 379,396 **** def test_read_dict_fields(self): ! reader = csv.DictReader(StringIO("1,2,abc\r\n"), dialect="excel", fieldnames=["f1", "f2", "f3"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) ! def test_read_short(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) ! def test_read_short_with_rest(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"], rest="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) class TestArrayWrites(unittest.TestCase): --- 381,408 ---- def test_read_dict_fields(self): ! reader = csv.DictReader(StringIO("1,2,abc\r\n"), fieldnames=["f1", "f2", "f3"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "f3": 'abc'}) ! def test_read_long(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"]) self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) ! def test_read_long_with_rest(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"], rest="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) + + def test_read_short(self): + reader = csv.DictReader(["1,2,abc,4,5,6\r\n","1,2,abc\r\n"], + fieldnames="1 2 3 4 5 6".split(), + restval="DEFAULT") + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": 'DEFAULT', "5": 'DEFAULT', + "6": 'DEFAULT'}) class TestArrayWrites(unittest.TestCase): From mwh@python.net Mon Feb 10 15:11:51 2003 From: mwh@python.net (Michael Hudson) Date: Mon, 10 Feb 2003 15:11:51 +0000 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.276,2.277 In-Reply-To: <71939A38-3D04-11D7-AF40-0030655234CE@cwi.nl> (Jack Jansen's message of "Mon, 10 Feb 2003 15:32:12 +0100") References: <71939A38-3D04-11D7-AF40-0030655234CE@cwi.nl> Message-ID: <2m1y2gkw5k.fsf@starship.python.net> Jack Jansen writes: > On Monday, Feb 10, 2003, at 14:02 Europe/Amsterdam, Guido van Rossum > wrote: > >>> I don't like looking at __APPLE__ either (it looks too broad), but I >>> haven't found >>> anything else. So I'd say leave it as is. >> >> Really? Is there nothing to distinguish OS 9 from OS X? I don't >> believe that. > > There is, if you import MacOS-specific headers (Universal Headers on > MacOS9, or Carbon/Carbon.h on OSX). > Then you have defines like TARGET_API_MAC_OSX and TARGET_API_MAC_OS8 > and many many more. Well, __APPLE__ and some kind of unix identifier might work in concert... Cheers, M. -- You're posting to a Scheme group. Around here, arguing that Java is better than C++ is like arguing that grasshoppers taste better than tree bark. -- Thant Tessman, comp.lang.scheme From montanaro@users.sourceforge.net Mon Feb 10 15:14:43 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:14:43 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv17365 Modified Files: csv.py Log Message: DictReader: better not to lose data - always provide a dict field keyed by self.rest if the row is longer than the number of fieldnames. Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** csv.py 10 Feb 2003 15:06:46 -0000 1.27 --- csv.py 10 Feb 2003 15:14:39 -0000 1.28 *************** *** 71,75 **** lf = len(self.fieldnames) lr = len(row) ! if lf < lr and self.rest != None: d[self.rest] = row[lf:] elif lf > lr: --- 71,75 ---- lf = len(self.fieldnames) lr = len(row) ! if lf < lr: d[self.rest] = row[lf:] elif lf > lr: From montanaro@users.sourceforge.net Mon Feb 10 15:15:19 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:15:19 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv17622 Modified Files: test_csv.py Log Message: adjust for data preservation behavior in DictReader Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** test_csv.py 10 Feb 2003 15:10:16 -0000 1.27 --- test_csv.py 10 Feb 2003 15:15:15 -0000 1.28 *************** *** 388,392 **** reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"]) ! self.assertEqual(reader.next(), {"f1": '1', "f2": '2'}) def test_read_long_with_rest(self): --- 388,393 ---- reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), fieldnames=["f1", "f2"]) ! self.assertEqual(reader.next(), {"f1": '1', "f2": '2', ! None: ["abc", "4", "5", "6"]}) def test_read_long_with_rest(self): From jackjansen@users.sourceforge.net Mon Feb 10 15:55:57 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:55:57 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv3675 Modified Files: pimp.py Log Message: Added docstrings. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** pimp.py 10 Feb 2003 14:19:14 -0000 1.4 --- pimp.py 10 Feb 2003 15:55:51 -0000 1.5 *************** *** 1,2 **** --- 1,16 ---- + """Package Install Manager for Python. + + This is currently a MacOSX-only strawman implementation. + Motto: "He may be shabby, but he gets you what you need" :-) + + Tools to allow easy installation of packages. The idea is that there is + an online XML database per (platform, python-version) containing packages + known to work with that combination. This module contains tools for getting + and parsing the database, testing whether packages are installed, computing + dependencies and installing packages. + + There is a minimal main program that works as a command line tool, but the + intention is that the end user will use this through a GUI. + """ import sys import os *************** *** 7,10 **** --- 21,26 ---- import md5 + __all__ = ["PimpPreferences", "PimpDatabase", "PimpPackage", "main"] + _scriptExc_NotInstalled = "pimp._scriptExc_NotInstalled" _scriptExc_OldInstalled = "pimp._scriptExc_OldInstalled" *************** *** 33,36 **** --- 49,55 ---- class PimpPreferences: + """Container for per-user preferences, such as the database to use + and where to install packages""" + def __init__(self, flavorOrder=None, *************** *** 56,59 **** --- 75,81 ---- def check(self): + """Check that the preferences make sense: directories exist and are + writable, the install directory is on sys.path, etc.""" + rv = "" RWX_OK = os.R_OK|os.W_OK|os.X_OK *************** *** 84,87 **** --- 106,111 ---- def compareFlavors(self, left, right): + """Compare two flavor strings. This is part of your preferences + because whether the user prefers installing from source or binary is.""" if left in self.flavorOrder: if right in self.flavorOrder: *************** *** 93,96 **** --- 117,125 ---- class PimpDatabase: + """Class representing a pimp database. It can actually contain + information from multiple databases through inclusion, but the + toplevel database is considered the master, as its maintainer is + "responsible" for the contents""" + def __init__(self, prefs): self._packages = [] *************** *** 102,105 **** --- 131,138 ---- def appendURL(self, url, included=0): + """Append packages from the database with the given URL. + Only the first database should specify included=0, so the + global information (maintainer, description) get stored.""" + if url in self._urllist: return *************** *** 112,121 **** self._maintainer = dict.get('maintainer', '') self._description = dict.get('description', '') ! self.appendPackages(dict['packages']) others = dict.get('include', []) for url in others: self.appendURL(url, included=1) ! def appendPackages(self, packages): for p in packages: pkg = PimpPackage(self, **dict(p)) --- 145,158 ---- self._maintainer = dict.get('maintainer', '') self._description = dict.get('description', '') ! self._appendPackages(dict['packages']) others = dict.get('include', []) for url in others: self.appendURL(url, included=1) ! def _appendPackages(self, packages): ! """Given a list of dictionaries containing package ! descriptions create the PimpPackage objects and append them ! to our internal storage.""" ! for p in packages: pkg = PimpPackage(self, **dict(p)) *************** *** 123,129 **** --- 160,170 ---- def list(self): + """Return a list of all PimpPackage objects in the database.""" + return self._packages def listnames(self): + """Return a list of names of all packages in the database.""" + rv = [] for pkg in self._packages: *************** *** 132,135 **** --- 173,181 ---- def dump(self, pathOrFile): + """Dump the contents of the database to an XML .plist file. + + The file can be passed as either a file object or a pathname. + All data, including included databases, is dumped.""" + packages = [] for pkg in self._packages: *************** *** 145,148 **** --- 191,201 ---- def find(self, ident): + """Find a package. The package can be specified by name + or as a dictionary with name, version and flavor entries. + + Only name is obligatory. If there are multiple matches the + best one (higher version number, flavors ordered according to + users' preference) is returned.""" + if type(ident) == str: # Remove ( and ) for pseudo-packages *************** *** 176,179 **** --- 229,234 ---- class PimpPackage: + """Class representing a single package.""" + def __init__(self, db, name, version=None, *************** *** 201,204 **** --- 256,260 ---- def dump(self): + """Return a dict object containing the information on the package.""" dict = { 'name': self.name, *************** *** 227,230 **** --- 283,288 ---- def __cmp__(self, other): + """Compare two packages, where the "better" package sorts lower.""" + if not isinstance(other, PimpPackage): return cmp(id(self), id(other)) *************** *** 232,239 **** return cmp(self.name, other.name) if self.version != other.version: ! return cmp(self.version, other.version) return self._db.preferences.compareFlavors(self.flavor, other.flavor) def installed(self): namespace = { "NotInstalled": _scriptExc_NotInstalled, --- 290,304 ---- return cmp(self.name, other.name) if self.version != other.version: ! return -cmp(self.version, other.version) return self._db.preferences.compareFlavors(self.flavor, other.flavor) def installed(self): + """Test wheter the package is installed. + + Returns two values: a status indicator which is one of + "yes", "no", "old" (an older version is installed) or "bad" + (something went wrong during the install test) and a human + readable string which may contain more details.""" + namespace = { "NotInstalled": _scriptExc_NotInstalled, *************** *** 260,263 **** --- 325,336 ---- def prerequisites(self): + """Return a list of prerequisites for this package. + + The list contains 2-tuples, of which the first item is either + a PimpPackage object or None, and the second is a descriptive + string. The first item can be None if this package depends on + something that isn't pimp-installable, in which case the descriptive + string should tell the user what to do.""" + rv = [] if not self.downloadURL: *************** *** 279,282 **** --- 352,357 ---- def _cmd(self, output, dir, *cmditems): + """Internal routine to run a shell command in a given directory.""" + cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems) if output: *************** *** 294,298 **** return rv ! def downloadSinglePackage(self, output): scheme, loc, path, query, frag = urlparse.urlsplit(self.downloadURL) path = urllib.url2pathname(path) --- 369,384 ---- return rv ! def downloadSinglePackage(self, output=None): ! """Download a single package, if needed. ! ! An MD5 signature is used to determine whether download is needed, ! and to test that we actually downloaded what we expected. ! If output is given it is a file-like object that will receive a log ! of what happens. ! ! If anything unforeseen happened the method returns an error message ! string. ! """ ! scheme, loc, path, query, frag = urlparse.urlsplit(self.downloadURL) path = urllib.url2pathname(path) *************** *** 313,316 **** --- 399,404 ---- def _archiveOK(self): + """Test an archive. It should exist and the MD5 checksum should be correct.""" + if not os.path.exists(self.archiveFilename): return 0 *************** *** 322,326 **** return checksum == self._MD5Sum ! def unpackSinglePackage(self, output): filename = os.path.split(self.archiveFilename)[1] for ext, cmd in ARCHIVE_FORMATS: --- 410,416 ---- return checksum == self._MD5Sum ! def unpackSinglePackage(self, output=None): ! """Unpack a downloaded package archive.""" ! filename = os.path.split(self.archiveFilename)[1] for ext, cmd in ARCHIVE_FORMATS: *************** *** 338,342 **** return "no setup.py found after unpack of archive" ! def installSinglePackage(self, output): if not self.downloadURL: return "%s: This package needs to be installed manually" % _fmtpackagename(self) --- 428,437 ---- return "no setup.py found after unpack of archive" ! def installSinglePackage(self, output=None): ! """Download, unpack and install a single package. ! ! If output is given it should be a file-like object and it ! will receive a log of what happened.""" ! if not self.downloadURL: return "%s: This package needs to be installed manually" % _fmtpackagename(self) *************** *** 360,363 **** --- 455,461 ---- class PimpInstaller: + """Installer engine: computes dependencies and installs + packages in the right order.""" + def __init__(self, db): self._todo = [] *************** *** 375,378 **** --- 473,482 ---- def _prepareInstall(self, package, force=0, recursive=1): + """Internal routine, recursive engine for prepareInstall. + + Test whether the package is installed and (if not installed + or if force==1) prepend it to the temporary todo list and + call ourselves recursively on all prerequisites.""" + if not force: status, message = package.installed() *************** *** 392,395 **** --- 496,508 ---- def prepareInstall(self, package, force=0, recursive=1): + """Prepare installation of a package. + + If the package is already installed and force is false nothing + is done. If recursive is true prerequisites are installed first. + + Returns a list of packages (to be passed to install) and a list + of messages of any problems encountered. + """ + self._curtodo = [] self._curmessages = [] *************** *** 401,404 **** --- 514,519 ---- def install(self, packages, output): + """Install a list of packages.""" + self._addPackages(packages) status = [] *************** *** 411,414 **** --- 526,534 ---- def _fmtpackagename(dict): + """Return the full name "name-version-flavor" of a package. + + If the package is a pseudo-package, something that cannot be + installed through pimp, return the name in (parentheses).""" + if isinstance(dict, PimpPackage): dict = dict.dump() *************** *** 424,427 **** --- 544,549 ---- def _run(mode, verbose, force, args): + """Engine for the main program""" + prefs = PimpPreferences() prefs.check() *************** *** 496,499 **** --- 618,623 ---- def main(): + """Minimal commandline tool to drive pimp.""" + import getopt def _help(): From gvanrossum@users.sourceforge.net Mon Feb 10 16:05:48 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 08:05:48 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.114,2.115 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv8425 Modified Files: abstract.c Log Message: Fold long lines. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.114 retrieving revision 2.115 diff -C2 -d -r2.114 -r2.115 *** abstract.c 31 Dec 2002 19:50:03 -0000 2.114 --- abstract.c 10 Feb 2003 16:05:43 -0000 2.115 *************** *** 1,5 **** /* Abstract Object Interface (many thanks to Jim Fulton) */ - #include "Python.h" #include --- 1,4 ---- *************** *** 2094,2098 **** if (!PyClass_Check(derived) || !PyClass_Check(cls)) { ! if (!check_class(derived, "issubclass() arg 1 must be a class")) return -1; --- 2093,2098 ---- if (!PyClass_Check(derived) || !PyClass_Check(cls)) { ! if (!check_class(derived, ! "issubclass() arg 1 must be a class")) return -1; *************** *** 2101,2107 **** int n = PyTuple_GET_SIZE(cls); for (i = 0; i < n; ++i) { ! retval = PyObject_IsSubclass(derived, PyTuple_GET_ITEM(cls, i)); ! if (retval != 0) /* either found it, or got an error */ return retval; } return 0; --- 2101,2110 ---- int n = PyTuple_GET_SIZE(cls); for (i = 0; i < n; ++i) { ! retval = PyObject_IsSubclass( ! derived, PyTuple_GET_ITEM(cls, i)); ! if (retval != 0) { ! /* either found it, or got an error */ return retval; + } } return 0; From jackjansen@users.sourceforge.net Mon Feb 10 16:08:20 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 10 Feb 2003 08:08:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv9623 Modified Files: pimp.py Log Message: Punctuation fixes in docstrings. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** pimp.py 10 Feb 2003 15:55:51 -0000 1.5 --- pimp.py 10 Feb 2003 16:08:17 -0000 1.6 *************** *** 44,48 **** class MyURLopener(urllib.FancyURLopener): ! """Like FancyURLOpener, but we do want to get errors as exceptions""" def http_error_default(self, url, fp, errcode, errmsg, headers): urllib.URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) --- 44,48 ---- class MyURLopener(urllib.FancyURLopener): ! """Like FancyURLOpener, but we do want to get errors as exceptions.""" def http_error_default(self, url, fp, errcode, errmsg, headers): urllib.URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) *************** *** 50,54 **** class PimpPreferences: """Container for per-user preferences, such as the database to use ! and where to install packages""" def __init__(self, --- 50,54 ---- class PimpPreferences: """Container for per-user preferences, such as the database to use ! and where to install packages.""" def __init__(self, *************** *** 120,124 **** information from multiple databases through inclusion, but the toplevel database is considered the master, as its maintainer is ! "responsible" for the contents""" def __init__(self, prefs): --- 120,124 ---- information from multiple databases through inclusion, but the toplevel database is considered the master, as its maintainer is ! "responsible" for the contents.""" def __init__(self, prefs): From goodger@users.sourceforge.net Mon Feb 10 15:34:57 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Mon, 10 Feb 2003 07:34:57 -0800 Subject: [Python-checkins] python/nondist/peps pep-0310.txt,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv26318 Modified Files: pep-0310.txt Log Message: update title, same as in PEP 0 Index: pep-0310.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0310.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pep-0310.txt 10 Feb 2003 14:52:51 -0000 1.1 --- pep-0310.txt 10 Feb 2003 15:34:54 -0000 1.2 *************** *** 1,4 **** PEP: 310 ! Title: Syntax for Reliable Acquisition/Release Pairs Version: $Revision$ Last-Modified: $Date$ --- 1,4 ---- PEP: 310 ! Title: Reliable Acquisition/Release Pairs Version: $Revision$ Last-Modified: $Date$ From doerwalter@users.sourceforge.net Mon Feb 10 17:36:43 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 09:36:43 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.279,2.280 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv28462/Python Modified Files: bltinmodule.c Log Message: Change filtertuple() to use tp_as_sequence->sq_item instead of PyTuple_GetItem, so an overwritten __getitem__ in a tuple subclass works. SF bug #665835. Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.279 retrieving revision 2.280 diff -C2 -d -r2.279 -r2.280 *** bltinmodule.c 10 Feb 2003 14:48:29 -0000 2.279 --- bltinmodule.c 10 Feb 2003 17:36:40 -0000 2.280 *************** *** 1889,1894 **** int ok; ! if ((item = PyTuple_GetItem(tuple, i)) == NULL) goto Fail_1; if (func == Py_None) { Py_INCREF(item); --- 1889,1899 ---- int ok; ! if (tuple->ob_type->tp_as_sequence && ! tuple->ob_type->tp_as_sequence->sq_item) { ! item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i); ! } else { ! PyErr_SetString(PyExc_TypeError, "unsubscriptable object"); goto Fail_1; + } if (func == Py_None) { Py_INCREF(item); From doerwalter@users.sourceforge.net Mon Feb 10 17:36:42 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 09:36:42 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_builtin.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28462/Lib/test Modified Files: test_builtin.py Log Message: Change filtertuple() to use tp_as_sequence->sq_item instead of PyTuple_GetItem, so an overwritten __getitem__ in a tuple subclass works. SF bug #665835. Index: test_builtin.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_builtin.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_builtin.py 10 Feb 2003 13:19:13 -0000 1.12 --- test_builtin.py 10 Feb 2003 17:36:40 -0000 1.13 *************** *** 420,424 **** # test, that filter() never returns tuple, str or unicode subclasses # and that the result always go's through __getitem__ - # FIXME: For tuple currently it doesn't go through __getitem__ funcs = (None, lambda x: True) class tuple2(tuple): --- 420,423 ---- *************** *** 429,433 **** return 2*str.__getitem__(self, index) inputs = { ! tuple2: {(): (), (1, 2, 3): (1, 2, 3)}, # FIXME str2: {"": "", "123": "112233"} } --- 428,432 ---- return 2*str.__getitem__(self, index) inputs = { ! tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, str2: {"": "", "123": "112233"} } From doerwalter@users.sourceforge.net Mon Feb 10 17:44:19 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 09:44:19 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_unicode.py,1.76,1.77 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv32031/Lib/test Modified Files: test_unicode.py Log Message: Fix copy&paste error: call title instead of count Index: test_unicode.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_unicode.py,v retrieving revision 1.76 retrieving revision 1.77 diff -C2 -d -r1.76 -r1.77 *** test_unicode.py 19 Jan 2003 16:59:20 -0000 1.76 --- test_unicode.py 10 Feb 2003 17:44:16 -0000 1.77 *************** *** 91,95 **** self.checkmethod('title', u"getInt", u'Getint') ! self.assertRaises(TypeError, u'hello'.count, 42) def test_find(self): --- 91,95 ---- self.checkmethod('title', u"getInt", u'Getint') ! self.assertRaises(TypeError, u'hello'.title, 42) def test_find(self): From doerwalter@users.sourceforge.net Mon Feb 10 17:51:07 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 10 Feb 2003 09:51:07 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_unicode.py,1.77,1.78 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2388/Lib/test Modified Files: test_unicode.py Log Message: Add a few tests to test_count() to increase coverage in Object/unicodeobject.c::unicode_count(). Index: test_unicode.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_unicode.py,v retrieving revision 1.77 retrieving revision 1.78 diff -C2 -d -r1.77 -r1.78 *** test_unicode.py 10 Feb 2003 17:44:16 -0000 1.77 --- test_unicode.py 10 Feb 2003 17:51:03 -0000 1.78 *************** *** 80,85 **** --- 80,91 ---- self.checkmethod('count', u'aaa', 3, 'a') self.checkmethod('count', u'aaa', 0, 'b') + self.checkmethod('count', u'aaa', 0, 'b') + self.checkmethod('count', u'aaa', 1, 'a', -1) + self.checkmethod('count', u'aaa', 3, 'a', -10) + self.checkmethod('count', u'aaa', 2, 'a', 0, -1) + self.checkmethod('count', u'aaa', 0, 'a', 0, -10) self.assertRaises(TypeError, u'hello'.count) + self.assertRaises(TypeError, u'hello'.count, 42) def test_title(self): From mwh@users.sourceforge.net Mon Feb 10 19:12:46 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:12:46 -0800 Subject: [Python-checkins] python/dist/src/Doc/api init.tex,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv10571 Modified Files: init.tex Log Message: A typo, and desist from inaccurately describing some things as lists. Index: init.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/init.tex,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** init.tex 6 Dec 2002 22:42:13 -0000 1.5 --- init.tex 10 Feb 2003 19:12:42 -0000 1.6 *************** *** 59,65 **** leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension ! modules may not be freed. Some extension may not work properly if their initialization routine is called more than once; this can ! happen if an applcation calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more than once. \end{cfuncdesc} --- 59,65 ---- leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension ! modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can ! happen if an application calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more than once. \end{cfuncdesc} *************** *** 257,261 **** version separated by a period. The returned string points into static storage; the caller should not modify its value. The value ! is available to Python code as the list \code{sys.version}. \withsubitem{(in module sys)}{\ttindex{version}} \end{cfuncdesc} --- 257,261 ---- version separated by a period. The returned string points into static storage; the caller should not modify its value. The value ! is available to Python code as \code{sys.version}. \withsubitem{(in module sys)}{\ttindex{version}} \end{cfuncdesc} *************** *** 280,285 **** The returned string points into static storage; the caller should ! not modify its value. The value is available to Python code as the ! list \code{sys.copyright}. \withsubitem{(in module sys)}{\ttindex{copyright}} \end{cfuncdesc} --- 280,285 ---- The returned string points into static storage; the caller should ! not modify its value. The value is available to Python code as ! \code{sys.copyright}. \withsubitem{(in module sys)}{\ttindex{copyright}} \end{cfuncdesc} From mwh@users.sourceforge.net Mon Feb 10 19:18:25 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:18:25 -0800 Subject: [Python-checkins] python/dist/src/Doc/api newtypes.tex,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv11461 Modified Files: newtypes.tex Log Message: Update advice about __module__ and __name__ and tp_name wrt. new types. Add \refs to GC section that were XXXed out. Index: newtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/newtypes.tex,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** newtypes.tex 6 Feb 2003 18:37:11 -0000 1.20 --- newtypes.tex 10 Feb 2003 19:18:21 -0000 1.21 *************** *** 425,439 **** should have the \member{tp_name} initializer \code{"P.Q.M.T"}. ! For dynamically allocated type objects, this may be just the type ! name, if the module name is explicitly stored in the type dict as ! the value for key \code{'__module__'}. ! If the tp_name field contains a dot, everything before the last dot ! is made accessible as the \member{__module__} attribute, and ! everything after the last dot is made accessible as the ! \member{__name__} attribute. If no dot is present, the entire ! \member{tp_name} field is made accessible as the \member{__name__} ! attribute, and the \member{__module__} attribute is undefined ! (unless explicitly set in the dictionary, as explained above). This field is not inherited by subtypes. --- 425,442 ---- should have the \member{tp_name} initializer \code{"P.Q.M.T"}. ! For dynamically allocated type objects, this should just be the type ! name, and the module name explicitly stored in the type dict as the ! value for key \code{'__module__'}. ! For statically allocated type objects, the tp_name field should ! contain a dot. Everything before the last dot is made accessible as ! the \member{__module__} attribute, and everything after the last dot ! is made accessible as the \member{__name__} attribute. ! ! If no dot is present, the entire \member{tp_name} field is made ! accessible as the \member{__name__} attribute, and the ! \member{__module__} attribute is undefined (unless explicitly set in ! the dictionary, as explained above). This means your type will be ! impossible to pickle. This field is not inherited by subtypes. *************** *** 883,888 **** An optional pointer to a traversal function for the garbage collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC} ! flag bit is set. More information in section XXX about garbage ! collection. This field is inherited by subtypes together with \member{tp_clear} --- 886,891 ---- An optional pointer to a traversal function for the garbage collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC} ! flag bit is set. More information in section ! \ref{supporting-cycle-detection} about garbage collection. This field is inherited by subtypes together with \member{tp_clear} *************** *** 896,900 **** An optional pointer to a clear function for the garbage collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is ! set. More information in section XXX about garbage collection. This field is inherited by subtypes together with \member{tp_clear} --- 899,904 ---- An optional pointer to a clear function for the garbage collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is ! set. More information in section ! \ref{supporting-cycle-detection} about garbage collection. This field is inherited by subtypes together with \member{tp_clear} From mwh@users.sourceforge.net Mon Feb 10 19:24:54 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:24:54 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.116,1.117 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv16682 Modified Files: whatsnew23.tex Log Message: Sundry very picky changes. Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.116 retrieving revision 1.117 diff -C2 -d -r1.116 -r1.117 *** whatsnew23.tex 10 Feb 2003 15:08:16 -0000 1.116 --- whatsnew23.tex 10 Feb 2003 19:24:50 -0000 1.117 *************** *** 102,107 **** There are also \method{issubset()} and \method{issuperset()} methods ! for checking whether one set is a strict subset or superset of ! another: \begin{verbatim} --- 102,106 ---- There are also \method{issubset()} and \method{issuperset()} methods ! for checking whether one set is a subset or superset of another: \begin{verbatim} *************** *** 544,548 **** \constant{False}. (\constant{True} and \constant{False} constants were added to the built-ins ! in Python 2.2.2, but the 2.2.2 versions simply have integer values of 1 and 0 and aren't a different type.) --- 543,547 ---- \constant{False}. (\constant{True} and \constant{False} constants were added to the built-ins ! in Python 2.2.1, but the 2.2.1 versions simply have integer values of 1 and 0 and aren't a different type.) *************** *** 1485,1489 **** \item On Windows, the \module{socket} module now ships with Secure ! Sockets Library (SSL) support. \item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed --- 1484,1488 ---- \item On Windows, the \module{socket} module now ships with Secure ! Sockets Layer (SSL) support. \item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed *************** *** 1660,1663 **** --- 1659,1664 ---- %====================================================================== \subsection{Date/Time Type} + + % XXX This is out-of-date already: timetz and so on have gone away. Date and time types suitable for expressing timestamps were added as From mwh@users.sourceforge.net Mon Feb 10 19:36:50 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:36:50 -0800 Subject: [Python-checkins] python/dist/src/Include pyport.h,2.58,2.59 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv25975/Include Modified Files: pyport.h Log Message: Make comments agree with code (I think). Index: pyport.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pyport.h,v retrieving revision 2.58 retrieving revision 2.59 diff -C2 -d -r2.58 -r2.59 *** pyport.h 6 Jan 2003 12:41:24 -0000 2.58 --- pyport.h 10 Feb 2003 19:36:46 -0000 2.59 *************** *** 412,418 **** /* ! All windows ports, except cygwin, are handled in PC/pyconfig.h ! BeOS is only other autoconf platform requiring special linkage handling ! and both these use __declspec() */ #if defined(__CYGWIN__) || defined(__BEOS__) --- 412,419 ---- /* ! All windows ports, except cygwin, are handled in PC/pyconfig.h. ! ! BeOS and cygwin are the only other autoconf platform requiring special ! linkage handling and both of these use __declspec(). */ #if defined(__CYGWIN__) || defined(__BEOS__) From jvr@users.sourceforge.net Mon Feb 10 19:38:42 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:38:42 -0800 Subject: [Python-checkins] python/dist/src/Lib types.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv27736/Lib Modified Files: types.py Log Message: [ 683376 ] Adding NotImplementedType to types.py Index: types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/types.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** types.py 14 Jun 2002 20:41:13 -0000 1.29 --- types.py 10 Feb 2003 19:38:33 -0000 1.30 *************** *** 86,89 **** --- 86,90 ---- DictProxyType = type(TypeType.__dict__) + NotImplementedType = type(NotImplemented) del sys, _f, _C, _x # Not for export From mwh@users.sourceforge.net Mon Feb 10 19:21:21 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 10 Feb 2003 11:21:21 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libunittest.tex,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv14952 Modified Files: libunittest.tex Log Message: Remove erroneous period. Index: libunittest.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libunittest.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** libunittest.tex 29 Dec 2002 17:59:24 -0000 1.12 --- libunittest.tex 10 Feb 2003 19:21:16 -0000 1.13 *************** *** 299,303 **** \item The test module can be run standalone from the command line. \item The test code can more easily be separated from shipped code. ! \item There is less temptation to change test code to fit the code. it tests without a good reason. \item Test code should be modified much less frequently than the --- 299,303 ---- \item The test module can be run standalone from the command line. \item The test code can more easily be separated from shipped code. ! \item There is less temptation to change test code to fit the code it tests without a good reason. \item Test code should be modified much less frequently than the From jlt63@users.sourceforge.net Mon Feb 10 20:45:53 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Mon, 10 Feb 2003 12:45:53 -0800 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.82,2.83 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2818 Modified Files: arraymodule.c Log Message: Patch #676837: Cygwin array module patch The attached patch enables the array module to build cleanly under Cygwin again. Index: arraymodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/arraymodule.c,v retrieving revision 2.82 retrieving revision 2.83 diff -C2 -d -r2.82 -r2.83 *** arraymodule.c 7 Jan 2003 01:58:51 -0000 2.82 --- arraymodule.c 10 Feb 2003 20:45:47 -0000 2.83 *************** *** 1950,1954 **** static PyTypeObject PyArrayIter_Type = { ! PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ "arrayiterator", /* tp_name */ --- 1950,1954 ---- static PyTypeObject PyArrayIter_Type = { ! PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "arrayiterator", /* tp_name */ *************** *** 1997,2000 **** --- 1997,2001 ---- Arraytype.ob_type = &PyType_Type; + PyArrayIter_Type.ob_type = &PyType_Type; m = Py_InitModule3("array", a_methods, module_doc); From gvanrossum@users.sourceforge.net Mon Feb 10 20:48:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 12:48:23 -0800 Subject: [Python-checkins] python/dist/src/Lib unittest.py,1.14.4.1,1.14.4.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv4806 Modified Files: Tag: release22-maint unittest.py Log Message: Backport 1.16: Fix printing plural (s or ""). Index: unittest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/unittest.py,v retrieving revision 1.14.4.1 retrieving revision 1.14.4.2 diff -C2 -d -r1.14.4.1 -r1.14.4.2 *** unittest.py 21 May 2002 03:50:49 -0000 1.14.4.1 --- unittest.py 10 Feb 2003 20:48:19 -0000 1.14.4.2 *************** *** 617,621 **** run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % ! (run, run == 1 and "" or "s", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): --- 617,621 ---- run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % ! (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() if not result.wasSuccessful(): From jlt63@users.sourceforge.net Mon Feb 10 20:48:38 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Mon, 10 Feb 2003 12:48:38 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv4224 Modified Files: _iconv_codec.c Log Message: Patch #676839: Cygwin _iconv_codec module patch The attached patch enables the _iconv_codec module to build cleanly under Cygwin. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** _iconv_codec.c 4 Feb 2003 20:46:50 -0000 1.9 --- _iconv_codec.c 10 Feb 2003 20:48:35 -0000 1.10 *************** *** 608,612 **** static PyTypeObject iconvcodec_Type = { ! PyObject_HEAD_INIT(&PyType_Type) 0, /* Number of items for varobject */ "iconvcodec", /* Name of this type */ --- 608,612 ---- static PyTypeObject iconvcodec_Type = { ! PyObject_HEAD_INIT(NULL) 0, /* Number of items for varobject */ "iconvcodec", /* Name of this type */ *************** *** 689,692 **** --- 689,693 ---- iconv_close(hdl); + iconvcodec_Type.ob_type = &PyType_Type; m = Py_InitModule("_iconv_codec", _iconv_codec_methods); From tim_one@users.sourceforge.net Mon Feb 10 21:25:28 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:25:28 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv23524 Modified Files: pep-0307.txt Log Message: Tried to clarify the point about classic classes and __reduce__. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** pep-0307.txt 9 Feb 2003 17:16:45 -0000 1.20 --- pep-0307.txt 10 Feb 2003 21:25:25 -0000 1.21 *************** *** 143,149 **** though, and we'll refer to these collectively as __reduce__. ! IMPORTANT: a classic class cannot provide __reduce__ ! functionality. It must use __getinitargs__ and/or __gestate__ to ! customize pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns --- 143,151 ---- though, and we'll refer to these collectively as __reduce__. ! IMPORTANT: while a classic class can implement a __reduce__() ! method, pickling its instances ignores the method, so that a classic ! class cannot provide __reduce__ functionality in the sense intended ! here. A classic class must use __getinitargs__ and/or __gestate__ ! to customize pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns *************** *** 625,629 **** - When the __reduce__ method is inherited from object, it is ! (unconditionally) replaced by a better one that uses the same APIs as pickle protocol 2: __getnewargs__, __getstate__, and __setstate__, handling list and dict subclasses, and handling --- 627,631 ---- - When the __reduce__ method is inherited from object, it is ! (unconditionally) replaced by a better one that uses the same APIs as pickle protocol 2: __getnewargs__, __getstate__, and __setstate__, handling list and dict subclasses, and handling From gvanrossum@users.sourceforge.net Mon Feb 10 21:32:01 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:32:01 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv25780/Lib Modified Files: copy_reg.py Log Message: Get rid of the "bozo" __getstate__ that was inserted when __slots__ was used. This simplifies some logic in copy_reg.py (used by pickling). It also broke a test, but this was rewritten to test the new feature. :-) Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** copy_reg.py 7 Feb 2003 20:56:38 -0000 1.18 --- copy_reg.py 10 Feb 2003 21:31:25 -0000 1.19 *************** *** 59,62 **** --- 59,65 ---- getstate = self.__getstate__ except AttributeError: + if getattr(self, "__slots__", None): + raise TypeError("a class that defines __slots__ without " + "defining __getstate__ cannot be pickled") try: dict = self.__dict__ *************** *** 84,97 **** getstate = getattr(obj, "__getstate__", None) if getstate: ! try: ! state = getstate() ! except TypeError, err: ! # XXX Catch generic exception caused by __slots__ ! if str(err) != ("a class that defines __slots__ " ! "without defining __getstate__ " ! "cannot be pickled"): ! raise # Not that specific exception ! getstate = None ! if not getstate: state = getattr(obj, "__dict__", None) names = _slotnames(cls) --- 87,92 ---- getstate = getattr(obj, "__getstate__", None) if getstate: ! state = getstate() ! else: state = getattr(obj, "__dict__", None) names = _slotnames(cls) From gvanrossum@users.sourceforge.net Mon Feb 10 21:31:29 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:31:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.179,1.180 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25780/Lib/test Modified Files: test_descr.py Log Message: Get rid of the "bozo" __getstate__ that was inserted when __slots__ was used. This simplifies some logic in copy_reg.py (used by pickling). It also broke a test, but this was rewritten to test the new feature. :-) Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.179 retrieving revision 1.180 diff -C2 -d -r1.179 -r1.180 *** test_descr.py 10 Feb 2003 02:12:43 -0000 1.179 --- test_descr.py 10 Feb 2003 21:31:26 -0000 1.180 *************** *** 2836,2840 **** else: raise TestFailed, "should fail: cPickle D instance - %s" % base ! # Give C a __getstate__ and __setstate__ class C(base): __slots__ = ['a'] --- 2836,2840 ---- else: raise TestFailed, "should fail: cPickle D instance - %s" % base ! # Give C a nice generic __getstate__ and __setstate__ class C(base): __slots__ = ['a'] *************** *** 2844,2851 **** except AttributeError: d = {} ! try: ! d['a'] = self.a ! except AttributeError: ! pass return d def __setstate__(self, d): --- 2844,2853 ---- except AttributeError: d = {} ! for cls in self.__class__.__mro__: ! for sn in cls.__dict__.get('__slots__', ()): ! try: ! d[sn] = getattr(self, sn) ! except AttributeError: ! pass return d def __setstate__(self, d): *************** *** 2872,2890 **** y = cPickle.loads(cPickle.dumps(x)) vereq(y.a + y.b, 142) ! # But a subclass that adds a slot should not work class E(C): __slots__ = ['b'] ! try: ! pickle.dumps(E()) ! except TypeError: ! pass ! else: ! raise TestFailed, "should fail: pickle E instance - %s" % base ! try: ! cPickle.dumps(E()) ! except TypeError: ! pass ! else: ! raise TestFailed, "should fail: cPickle E instance - %s" % base def copies(): --- 2874,2889 ---- y = cPickle.loads(cPickle.dumps(x)) vereq(y.a + y.b, 142) ! # A subclass that adds a slot should also work class E(C): __slots__ = ['b'] ! x = E() ! x.a = 42 ! x.b = "foo" ! y = pickle.loads(pickle.dumps(x)) ! vereq(y.a, x.a) ! vereq(y.b, x.b) ! y = cPickle.loads(cPickle.dumps(x)) ! vereq(y.a, x.a) ! vereq(y.b, x.b) def copies(): From gvanrossum@users.sourceforge.net Mon Feb 10 21:31:31 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:31:31 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.204,2.205 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv25780/Objects Modified Files: typeobject.c Log Message: Get rid of the "bozo" __getstate__ that was inserted when __slots__ was used. This simplifies some logic in copy_reg.py (used by pickling). It also broke a test, but this was rewritten to test the new feature. :-) Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.204 retrieving revision 2.205 diff -C2 -d -r2.204 -r2.205 *** typeobject.c 6 Feb 2003 15:22:49 -0000 2.204 --- typeobject.c 10 Feb 2003 21:31:27 -0000 2.205 *************** *** 1469,1487 **** }; - /* bozo: __getstate__ that raises TypeError */ - - static PyObject * - bozo_func(PyObject *self, PyObject *args) - { - PyErr_SetString(PyExc_TypeError, - "a class that defines __slots__ without " - "defining __getstate__ cannot be pickled"); - return NULL; - } - - static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS}; - - static PyObject *bozo_obj = NULL; - static int valid_identifier(PyObject *s) --- 1469,1472 ---- *************** *** 1740,1760 **** Py_DECREF(slots); slots = newslots; - - /* See if *this* class defines __getstate__ */ - if (PyDict_GetItemString(dict, "__getstate__") == NULL) { - /* If not, provide a bozo that raises TypeError */ - if (bozo_obj == NULL) { - bozo_obj = PyCFunction_New(&bozo_ml, NULL); - if (bozo_obj == NULL) - goto bad_slots; - } - if (PyDict_SetItemString(dict, - "__getstate__", - bozo_obj) < 0) - { - Py_DECREF(bozo_obj); - goto bad_slots; - } - } /* Secondary bases may provide weakrefs or dict */ --- 1725,1728 ---- From gvanrossum@users.sourceforge.net Mon Feb 10 21:34:32 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:34:32 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28568 Modified Files: pep-0307.txt Log Message: Clarify __reduce__ and classic classes more. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** pep-0307.txt 10 Feb 2003 21:25:25 -0000 1.21 --- pep-0307.txt 10 Feb 2003 21:34:28 -0000 1.22 *************** *** 146,151 **** method, pickling its instances ignores the method, so that a classic class cannot provide __reduce__ functionality in the sense intended ! here. A classic class must use __getinitargs__ and/or __gestate__ ! to customize pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns --- 146,152 ---- method, pickling its instances ignores the method, so that a classic class cannot provide __reduce__ functionality in the sense intended ! here. (The copy_reg dispatch table is not consulted for classic ! classes either.) A classic class must use __getinitargs__ and/or ! __gestate__ to customize pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns From tim_one@users.sourceforge.net Mon Feb 10 21:39:28 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:39:28 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv31693 Modified Files: pep-0307.txt Log Message: Mostly paragraph relowing, after typographical fiddling to make it screamingly obvious which state tuple elements are required, which obvious, and which new in this PEP. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** pep-0307.txt 10 Feb 2003 21:34:28 -0000 1.22 --- pep-0307.txt 10 Feb 2003 21:39:25 -0000 1.23 *************** *** 158,167 **** The rest of this section is concerned with the tuple returned by ! __reduce__. It is a variable length tuple. Only the first two ! items (function and arguments) are required. The remaining items ! may be None or left off from the end. The last two items are new ! in this PEP. The items are, in order: ! function A callable object (not necessarily a function) called to create the initial version of the object; state may be added to the object later to fully reconstruct --- 158,170 ---- The rest of this section is concerned with the tuple returned by ! __reduce__. It is a variable size tuple, of length 2 through 5. ! The first two items (function and arguments) are required. The ! remaining items are optional and may be left off from the end; ! giving None for the value of an optional item acts the same as ! leaving it off. The last two items are new in this PEP. The items ! are, in order: ! function Required. ! A callable object (not necessarily a function) called to create the initial version of the object; state may be added to the object later to fully reconstruct *************** *** 170,174 **** special case (new in this PEP) here. ! arguments A tuple giving the argument list for the function. As a special case, designed for Zope 2's ExtensionClass, this may be None; in that case, --- 173,178 ---- special case (new in this PEP) here. ! arguments Required. ! A tuple giving the argument list for the function. As a special case, designed for Zope 2's ExtensionClass, this may be None; in that case, *************** *** 178,182 **** deprecated. ! state Additional state. If this is not None, the state is pickled, and obj.__setstate__(state) will be called when unpickling. If no __setstate__ method is --- 182,187 ---- deprecated. ! state Optional. ! Additional state. If this is not None, the state is pickled, and obj.__setstate__(state) will be called when unpickling. If no __setstate__ method is *************** *** 187,210 **** state.items(): obj[k] = v", if update() call fails. ! listitems New in this PEP. If this is not None, it should be ! an iterator (not a sequence!) yielding successive ! list items. These list items will be pickled, and ! appended to the object using either obj.append(item) ! or obj.extend(list_of_items). This is primarily used ! for list subclasses, but may be used by other classes ! as long as they have append() and extend() methods ! with the appropriate signature. (Whether append() or ! extend() is used depend on which pickle protocol ! version is used as well as the number of items to ! append, so both must be supported.) ! dictitems New in this PEP. If this is not None, it should be ! an iterator (not a sequence!) yielding successive ! dictionary items, which should be tuples of the form ! (key, value). These items will be pickled, and ! stored to the object using obj[key] = value. This is ! primarily used for dict subclasses, but may be used ! by other classes as long as they implement ! __setitem__. Note: in Python 2.2 and before, when using cPickle, state would be --- 192,215 ---- state.items(): obj[k] = v", if update() call fails. ! listitems Optional, and new in this PEP. ! If this is not None, it should be an iterator (not a ! sequence!) yielding successive list items. These list ! items will be pickled, and appended to the object using ! either obj.append(item) or obj.extend(list_of_items). ! This is primarily used for list subclasses, but may ! be used by other classes as long as they have append() ! and extend() methods with the appropriate signature. ! (Whether append() or extend() is used depend on which ! pickle protocol version is used as well as the number ! of items to append, so both must be supported.) ! dictitems Optionals, and new in this PEP. ! If this is not None, it should be an iterator (not a ! sequence!) yielding successive dictionary items, which ! should be tuples of the form (key, value). These items ! will be pickled, and stored to the object using ! obj[key] = value. This is primarily used for dict ! subclasses, but may be used by other classes as long ! as they implement __setitem__. Note: in Python 2.2 and before, when using cPickle, state would be From gvanrossum@users.sourceforge.net Mon Feb 10 21:44:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 10 Feb 2003 13:44:30 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv2256 Modified Files: pep-0307.txt Log Message: Bozo __getstate__ is gone. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** pep-0307.txt 10 Feb 2003 21:39:25 -0000 1.23 --- pep-0307.txt 10 Feb 2003 21:44:25 -0000 1.24 *************** *** 390,397 **** pickled and __setstate__ will not be called at all. ! Note that this strategy ignores slots. New-style classes that ! define slots and don't define __getstate__ in the same class that ! defines the slots automatically have a __getstate__ method added ! that raises TypeError. --- 390,397 ---- pickled and __setstate__ will not be called at all. ! Note that this strategy ignores slots. Instances of new-style ! classes that have slots but no __getstate__ method cannot be ! pickled by protocols 0 and 1; the code explicitly checks for ! this condition. *************** *** 441,450 **** None and whose second item is a dictionary mapping slot names to slot values described in the previous bullet. - - Note that new-style classes that define slots and don't define - __getstate__ in the same class that defines the slots - automatically have a __getstate__ method added that raises - TypeError. Protocol 2 ignores this __getstate__ method - (recognized by the specific text of the error message). The __setstate__ method --- 441,444 ---- From tim_one@users.sourceforge.net Mon Feb 10 22:13:38 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 14:13:38 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv16647 Modified Files: pep-0307.txt Log Message: Clarified the distinction between pickling time and unpickling time where that seemed to help, and made explicit where "the object" came from originally in the descriptions of the optional __reduce__ tuple elements. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** pep-0307.txt 10 Feb 2003 21:44:25 -0000 1.24 --- pep-0307.txt 10 Feb 2003 22:13:34 -0000 1.25 *************** *** 182,185 **** --- 182,190 ---- deprecated. + Unpickling invokes function(*arguments) to create an initial object, + called obj below. If the remaining items are left off, that's the end + of unpickling and obj is the result. Else obj is modified at + unpickling time by each item specified, as follows. + state Optional. Additional state. If this is not None, the state is *************** *** 188,194 **** defined, a default implementation is provided, which assumes that state is a dictionary mapping instance ! variable names to their values, and calls ! obj.__dict__.update(state) or "for k, v in ! state.items(): obj[k] = v", if update() call fails. listitems Optional, and new in this PEP. --- 193,205 ---- defined, a default implementation is provided, which assumes that state is a dictionary mapping instance ! variable names to their values. The default ! implementation calls ! ! obj.__dict__.update(state) ! ! or, if the update() call fails, ! ! for k, v in state.items(): ! obj[k] = v listitems Optional, and new in this PEP. *************** *** 204,208 **** of items to append, so both must be supported.) ! dictitems Optionals, and new in this PEP. If this is not None, it should be an iterator (not a sequence!) yielding successive dictionary items, which --- 215,219 ---- of items to append, so both must be supported.) ! dictitems Optional, and new in this PEP. If this is not None, it should be an iterator (not a sequence!) yielding successive dictionary items, which *************** *** 217,222 **** the __setstate__ call was to return a two-tuple from __reduce__. (But pickle.py would not pickle state if it was None.) In Python ! 2.3, __setstate__ will never be called when __reduce__ returns a ! state with value None. A __reduce__ implementation that needs to work both under Python --- 228,233 ---- the __setstate__ call was to return a two-tuple from __reduce__. (But pickle.py would not pickle state if it was None.) In Python ! 2.3, __setstate__ will never be called at unpickling time when ! __reduce__ returns a state with value None at pickling time. A __reduce__ implementation that needs to work both under Python *************** *** 225,229 **** and dictitems features. If this value is >= "2.0" then they are supported. If not, any list or dict items should be incorporated ! somehow in the 'state' return value; the __setstate__ method should be prepared to accept list or dict items as part of the state (how this is done is up to the application). --- 236,240 ---- and dictitems features. If this value is >= "2.0" then they are supported. If not, any list or dict items should be incorporated ! somehow in the 'state' return value, and the __setstate__ method should be prepared to accept list or dict items as part of the state (how this is done is up to the application). From montanaro@users.sourceforge.net Mon Feb 10 22:43:15 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 14:43:15 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv31575 Modified Files: libcsv.tex Log Message: * correct a number of Latex errors * add blurbs about the DictReader and DictWriter classes Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** libcsv.tex 6 Feb 2003 04:50:10 -0000 1.4 --- libcsv.tex 10 Feb 2003 22:43:12 -0000 1.5 *************** *** 16,44 **** many applications which read and write it. The lack of a standard means there can be subtle differences in the data produced and consumed by ! different applications. These differences can be maddeningly subtle. ! The \module{csv} allows programmers to say, ``write this data in the format ! preferred by Excel (tm),'' without knowing all the fiddly little details of ! the CSV format used by Excel. Programmers can also easily define their own ! CSV formats. \subsection{Relationship to other Python modules} ! The csv module reads and writes sequences. It can also read data and return ! the rows as dicts. Sequence types other than lists and tuples ! (e.g. \code{array} objects) can be written. To make it as easy as possible ! to interface with modules which implement the DB API, the value None is ! written as the empty string. While this isn't a reversible transformation, ! it makes it easier to dump SQL NULL data values to CSV files without ! preprocessing the data returned from a {}\code{cursor.fetch*()} call. \subsection{Module Contents} ! The \module{csv} module defines the following classes. ! \begin{classdesc}{reader}{iterable\optional{, dialect="excel"} \optional{, fmtparam}} ! Create a reader object which will iterate over lines in the given {}\var{csvfile}. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. --- 16,46 ---- many applications which read and write it. The lack of a standard means there can be subtle differences in the data produced and consumed by ! different applications. These differences can it annoying to process CSV ! files from multiple sources. ! The \module{csv} module allows programmers to say, ``write this data in the ! format preferred by Excel (tm),'' without knowing all the fiddly little ! details of the CSV format used by Excel. Programmers can also easily define ! their own CSV formats. \subsection{Relationship to other Python modules} ! The csv module reads and writes sequences. It can also read and write data ! in dictionary form using the \class{DictReader} and \class{DictWriter} ! classes. Sequence types other than lists and tuples (e.g. \code{array} ! objects) can be written. To make it as easy as possible to interface with ! modules which implement the DB API, the value None is written as the empty ! string. While this isn't a reversible transformation, it makes it easier to ! dump SQL NULL data values to CSV files without preprocessing the data ! returned from a {}\code{cursor.fetch*()} call. \subsection{Module Contents} ! The \module{csv} module defines the following functions. ! \begin{funcdesc}{reader}{iterable\optional{, dialect="excel"} \optional{, fmtparam}} ! Return a reader object which will iterate over lines in the given {}\var{csvfile}. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. *************** *** 48,71 **** {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. ! \end{classdesc} ! \begin{classdesc}{writer}{fileobj\optional{, dialect="excel"} ! \optional{, fieldnames} \optional{, fmtparam}} ! Create a writer object responsible for converting the user's data into delimited strings on the given file-like object. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific ! to a particular CSV dialect. If a sequence of strings is given as the ! optional \var{fieldnames} parameter, the writer will use them to properly ! order mapping objects passed to the object's \method{write} methods. The ! other optional \var{fmtparam} keyword arguments can be given to override ! individual formatting parameters in the current dialect. For more ! information about the dialect and formatting parameters, see section ! {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of ! these parameters. ! \end{classdesc} ! ! The \module{csv} module defines the following functions. \begin{funcdesc}{register_dialect}{name, dialect} --- 50,67 ---- {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. ! \end{funcdesc} ! \begin{funcdesc}{writer}{fileobj\optional{, dialect="excel"} \optional{, fmtparam}} ! Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific ! to a particular CSV dialect. The other optional \var{fmtparam} keyword ! arguments can be given to override individual formatting parameters in the ! current dialect. For more information about the dialect and formatting ! parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. ! \end{funcdesc} \begin{funcdesc}{register_dialect}{name, dialect} *************** *** 83,86 **** --- 79,118 ---- \end{funcdesc} + The \module{csv} module defines the following classes. + + \begin{classdesc}{DictReader}{fileobj, fieldnames + \optional{, restkey=None} + \optional{, restval=None} + \optional{, dialect="excel"} + \optional{, fmtparam}} + Create an object which operates like a regular reader but maps the + information read into a dict whose keys are given by the {}\var{fieldnames} + parameter. If the row read has fewer fields than the fieldnames sequence, + the value of \var{restval} will be used as the default value. If the row + read has more fields than the fieldnames sequence, the remaining data is + added as a sequence keyed by the value of \var{restkey}. If the row read + has fewer fields than the fieldnames sequence, the remaining keys take the + value of the optiona \var{restval} parameter. All other parameters are + interpreted as for regular readers. + \end{classdesc} + + \begin{classdesc}{DictWriter}{fileobj, fieldnames + \optional{, restval=""} + \optional{, extrasaction="raise"} + \optional{, dialect="excel"} + \optional{, fmtparam}} + Create an object which operates like a regular writer but maps dictionaries + onto output rows. The \var{fieldnames} parameter identifies the order in + which values in the dictionary passed to the \method{writerow} method are + written to the \var{fileobj}. The optional \var{restval} parameter + specifies the value to be written if the dictionary is missing a key in + {}\var{fieldnames}. If the dictionary passed to the \method{writerow} + method contains a key not found in {}\var{fieldnames}, the optional + {}\var{extrasaction} parameter indicates what action to take. If it is set + to \code{"raise"} a {}\exception{ValueError} is raised. If it is set to + {}\code{"ignore"}, extra values in the dictionary are ignored. All other + parameters are interpreted as for regular writers. + \end{classdesc} + The \module{csv} module defines the following exception. *************** *** 131,169 **** \begin{description} ! \item{quotechar}{specifies a one-character string to use as the quoting character. It defaults to \code{"}.} ! \item{delimiter}{specifies a one-character string to use as the field separator. It defaults to \code{,}.} ! \item{escapechar}{specifies a one-character string used to escape the delimiter when quotechar is set to \var{None}.} ! \item{skipinitialspace}{specifies how to interpret whitespace which immediately follows a delimiter. It defaults to False, which means that whitespace immediately following a delimiter is part of the following field.} ! \item{lineterminator}{specifies the character sequence which should terminate rows.} ! \item{quoting}{controls when quotes should be generated by the ! writer. It can take on any of the following module constants:} ! ! \begin{description} ! \item{QUOTE_MINIMAL}{means only when required, for example, when a ! field contains either the quotechar or the delimiter.} ! ! \item{QUOTE_ALL}{means that quotes are always placed around all fields.} ! ! \item{QUOTE_NONNUMERIC}{means that quotes are always placed around ! fields which contain characters other than [+-0-9.].} ! ! \item{QUOTE_NONE}{means that quotes are never placed around fields. ! Instead, the \var{escapechar} is used to escape any instances of the ! \var{delimiter} which occurs in the data.} ! \end{description} ! \item{doublequote}{controls the handling of quotes inside fields. When \var{True}, two consecutive quotes are interpreted as one during read, and when writing, each quote is written as two quotes.} --- 163,187 ---- \begin{description} ! \item[quotechar]{specifies a one-character string to use as the quoting character. It defaults to \code{"}.} ! \item[delimiter]{specifies a one-character string to use as the field separator. It defaults to \code{,}.} ! \item[escapechar]{specifies a one-character string used to escape the delimiter when quotechar is set to \var{None}.} ! \item[skipinitialspace]{specifies how to interpret whitespace which immediately follows a delimiter. It defaults to False, which means that whitespace immediately following a delimiter is part of the following field.} ! \item[lineterminator]{specifies the character sequence which should terminate rows.} ! \item[quoting]{controls when quotes should be generated by the ! writer. It can take on any of the \code{QUOTE_*} constants defined above.} ! \item[doublequote]{controls the handling of quotes inside fields. When \var{True}, two consecutive quotes are interpreted as one during read, and when writing, each quote is written as two quotes.} *************** *** 173,177 **** \subsection{Reader Objects} ! \class{Reader} objects have the following public methods. \begin{methoddesc}{next}{} --- 191,196 ---- \subsection{Reader Objects} ! \class{DictReader} and \var{reader} objects have the following public ! methods. \begin{methoddesc}{next}{} *************** *** 183,187 **** \subsection{Writer Objects} ! \class{Writer} objects have the following public methods. \begin{methoddesc}{writerow}{row} --- 202,207 ---- \subsection{Writer Objects} ! \class{DictWriter} and \var{writer} objects have the following public ! methods. \begin{methoddesc}{writerow}{row} *************** *** 198,202 **** \subsection{Examples} ! The ``hello world'' of csv reading is \begin{verbatim} --- 218,222 ---- \subsection{Examples} ! The \code{"hello world"} of csv reading is \begin{verbatim} *************** *** 213,220 **** writer.writerow(row) \end{verbatim} - - Both the \class{reader} and \class{writer} classes accept a number of - optional arguments which are used to tailor them to the dialect of the input - or output file. \begin{seealso} --- 233,236 ---- From montanaro@users.sourceforge.net Mon Feb 10 22:45:25 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Mon, 10 Feb 2003 14:45:25 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv32758 Modified Files: csv.py Log Message: * rename "rest" parameter to "restkey" in DictReader to tie in better with "restval". * add "extrasaction" parameter to DictWriter which tells how to treat dicts which have keys not in the known fieldnames. (still need some tests.) Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** csv.py 10 Feb 2003 15:14:39 -0000 1.28 --- csv.py 10 Feb 2003 22:45:21 -0000 1.29 *************** *** 59,69 **** class DictReader: ! def __init__(self, f, fieldnames, rest=None, restval=None, dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict ! self.rest = rest # key to catch long rows self.restval = restval # default value for short rows self.reader = reader(f, dialect, *args) def next(self): row = self.reader.next() --- 59,72 ---- class DictReader: ! def __init__(self, f, fieldnames, restkey=None, restval=None, dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict ! self.restkey = restkey # key to catch long rows self.restval = restval # default value for short rows self.reader = reader(f, dialect, *args) + def __iter__(self): + return self + def next(self): row = self.reader.next() *************** *** 72,76 **** lr = len(row) if lf < lr: ! d[self.rest] = row[lf:] elif lf > lr: for key in self.fieldnames[lr:]: --- 75,79 ---- lr = len(row) if lf < lr: ! d[self.restkey] = row[lf:] elif lf > lr: for key in self.fieldnames[lr:]: *************** *** 80,94 **** class DictWriter: ! def __init__(self, f, fieldnames, dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict self.writer = writer(f, dialect, *args) def writerow(self, rowdict): ! row = [rowdict.get(key, "") for key in self.fieldnames] ! return self.writer.writerow(row) def writerows(self, rowdicts): rows = [] for rowdict in rowdicts: ! rows.append([rowdict.get(key, "") for key in self.fieldnames]) return self.writer.writerows(rows) --- 83,113 ---- class DictWriter: ! def __init__(self, f, fieldnames, restval="", extrasaction="raise", ! dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict + self._fnsort = fieldnames[:] + self._fnsort.sort() + self.restval = restval # for writing short dicts + if extrasaction.lower() not in ("raise", "ignore"): + raise ValueError, \ + ("extrasaction (%s) must be 'raise' or 'ignore'" % + extrasaction) + self.extrasaction = extrasaction self.writer = writer(f, dialect, *args) + def _dict_to_list(self, rowdict): + keys = rowdict.keys() + keys.sort() + if keys != self._fnsort: + if self.extrasaction == "raise": + raise ValueError, "dict contains fields not in fieldnames" + return [rowdict.get(key, self.restval) for key in self.fieldnames] + def writerow(self, rowdict): ! return self.writer.writerow(self._dict_to_list(rowdict)) def writerows(self, rowdicts): rows = [] for rowdict in rowdicts: ! rows.append(self._dict_to_list(rowdict)) return self.writer.writerows(rows) From tim_one@users.sourceforge.net Mon Feb 10 23:21:09 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 15:21:09 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.25,1.26 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv19376 Modified Files: pep-0307.txt Log Message: + Add XXX comments. I'll clean those up later (or Guido and I both will). + Minor typo repair. + Added very brief sections about the other stuff that's new in protocol 2. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** pep-0307.txt 10 Feb 2003 22:13:34 -0000 1.25 --- pep-0307.txt 10 Feb 2003 23:21:03 -0000 1.26 *************** *** 372,375 **** --- 372,377 ---- For new-style classes implemented in Python, the default __reduce__ implementation works as follows: + XXX We seem to be missing a section for new-style classes implemented + XXX in C. Let D be the class on the object to be pickled. First, find the *************** *** 393,396 **** --- 395,405 ---- state = B(obj) + XXX How does the above relate to the steps explained earlier for + XXX __reduce__? For example, what here corresponds to the earlier + XXX description's function(*arguments) step? + + XXX Below, does __getstate__() customization replace the source of + XXX the value called "state" just above, or is this customization a + XXX distinct step? Objects for which this default __reduce__ implementation is used can customize it by defining __getstate__ and/or __setstate__ *************** *** 406,409 **** --- 415,420 ---- this condition. + XXX Is it the case that "pickling new-style class instances using + XXX protocols 0 or 1" ignores __getinitargs__? Case 3: pickling new-style class instances using protocol 2 *************** *** 546,551 **** such applications. ! First of all, a few ranges of extension codes is reserved for ! private use. Any application can register codes in these ranges. Two applications exchanging pickles using codes in these ranges need to have some out-of-band mechanism to agree on the mapping --- 557,562 ---- such applications. ! First, a few ranges of extension codes are reserved for private ! use. Any application can register codes in these ranges. Two applications exchanging pickles using codes in these ranges need to have some out-of-band mechanism to agree on the mapping *************** *** 597,601 **** (module, name) pair may not be mapped to more than one code, nor may a code be mapped to more than one (module, name) ! pair. (XXX Aliasing may actually cause as problem for this requirement; we'll see as we go.) --- 608,612 ---- (module, name) pair may not be mapped to more than one code, nor may a code be mapped to more than one (module, name) ! pair. (XXX Aliasing may actually cause a problem for this requirement; we'll see as we go.) *************** *** 657,660 **** --- 668,702 ---- To fix this, a __getnewargs__ method should be added that returns the appropriate argument tuple (excluding the class). + + + Pickling Python longs + + Pickling and unpickling Python longs takes time quadratic in + the number of digits, in protocols 1 and 2. Under protocol 2, + new opcodes support linear-time pickling and unpickling of longs. + + + Pickling bools + + Protocol 2 introduces new opcodes for pickling True and False + directly. Under protocols 0 and 1, bools are pickled as integers, + using a trick in the representation of the integer in the pickle + so that an unpickler can recognize that a bool was intended. + + + Pickling small tuples + + Protocol 2 introduces new opcodes for more-compact pickling of + tuples of lengths 1, 2 and 3. Protocol 1 previously introduced + an opcode for more-compact pickling of empty tuples. + + + Protocol identification + + Protocol 2 introduces a new opcode, with which all protocol 2 + pickles begin, identifying that the pickle is protocol 2. + Attempting to unpickle a protocol 2 pickle under older versions + of Python will therefore raise an "unknown opcode" exception + immediately. From andrewmcnamara@users.sourceforge.net Tue Feb 11 04:19:35 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Mon, 10 Feb 2003 20:19:35 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv24895 Modified Files: _csv.c Log Message: dialect_init can be called more than once for a given instance - fix self->lineterminator ref counting for this scenario. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** _csv.c 10 Feb 2003 10:41:08 -0000 1.28 --- _csv.c 11 Feb 2003 04:19:33 -0000 1.29 *************** *** 272,275 **** --- 272,276 ---- self->escapechar = '\0'; self->skipinitialspace = 0; + Py_XDECREF(self->lineterminator); self->lineterminator = PyString_FromString("\r\n"); if (self->lineterminator == NULL) From tim_one@users.sourceforge.net Tue Feb 11 04:51:02 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 10 Feb 2003 20:51:02 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv3287 Modified Files: pep-0307.txt Log Message: Cleared up the XXX comments I added earlier today, and fixed some additional typos. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** pep-0307.txt 10 Feb 2003 23:21:03 -0000 1.26 --- pep-0307.txt 11 Feb 2003 04:50:59 -0000 1.27 *************** *** 184,189 **** Unpickling invokes function(*arguments) to create an initial object, called obj below. If the remaining items are left off, that's the end ! of unpickling and obj is the result. Else obj is modified at ! unpickling time by each item specified, as follows. state Optional. --- 184,189 ---- Unpickling invokes function(*arguments) to create an initial object, called obj below. If the remaining items are left off, that's the end ! of unpickling for this object and obj is the result. Else obj is ! modified at unpickling time by each item specified, as follows. state Optional. *************** *** 368,412 **** The default __reduce__ implementation will fail at pickling time ! for built-in types not mentioned above. For new-style classes implemented in Python, the default ! __reduce__ implementation works as follows: ! XXX We seem to be missing a section for new-style classes implemented ! XXX in C. ! Let D be the class on the object to be pickled. First, find the ! nearest base class that is implemented in C (either as a ! built-in type or as a type defined by an extension class). Call ! this base class B, and the class of the object to be pickled D. ! Unless B is the class 'object', instances of class B must be ! picklable, either by having built-in support (as defined in the ! above three bullet points), or by having a non-default ! __reduce__ implementation. B must not be the same class as D ! (if it were, it would mean that D is not implemented in Python). ! The new object is created at unpickling time using the following ! code: ! obj = B.__new__(D, state) ! B.__init__(obj, state) ! where state is a value computed at pickling time as follows: ! state = B(obj) ! XXX How does the above relate to the steps explained earlier for ! XXX __reduce__? For example, what here corresponds to the earlier ! XXX description's function(*arguments) step? ! XXX Below, does __getstate__() customization replace the source of ! XXX the value called "state" just above, or is this customization a ! XXX distinct step? ! Objects for which this default __reduce__ implementation is used ! can customize it by defining __getstate__ and/or __setstate__ ! methods. These work almost the same as described for classic ! classes above, except that if __getstate__ returns an object (of ! any type) whose value is considered false (e.g. None, or a number ! that is zero, or an empty sequence or mapping), this state is not ! pickled and __setstate__ will not be called at all. Note that this strategy ignores slots. Instances of new-style --- 368,421 ---- The default __reduce__ implementation will fail at pickling time ! for built-in types not mentioned above, and for new-style classes ! implemented in C: if they want to be picklable, they must supply ! a custom __reduce__ implementation under protocols 0 and 1. For new-style classes implemented in Python, the default ! __reduce__ implementation (copy_reg._reduce) works as follows: ! Let D be the class on the object to be pickled. First, find the ! nearest base class that is implemented in C (either as a ! built-in type or as a type defined by an extension class). Call ! this base class B, and the class of the object to be pickled D. ! Unless B is the class 'object', instances of class B must be ! picklable, either by having built-in support (as defined in the ! above three bullet points), or by having a non-default ! __reduce__ implementation. B must not be the same class as D ! (if it were, it would mean that D is not implemented in Python). ! The callable produced by the default __reduce__ is ! copy_reg._reconstructor, and its arguments tuple is ! (D, B, basestate), where basestate is None if B is the builtin ! object class, and basestate is ! basestate = B(obj) ! if B is not the builtin object class. This is geared toward ! pickling subclasses of builtin types, where, for example, ! list(some_list_subclass_instance) produces "the list part" of ! the list subclass instance. ! The object is recreated at unpickling time by ! copy_reg._reconstructor, like so: ! obj = B.__new__(D, basestate) ! B.__init__(obj, basestate) ! Objects using the default __reduce__ implementation can customize ! it by defining __getstate__ and/or __setstate__ methods. These ! work almost the same as described for classic classes above, except ! that if __getstate__ returns an object (of any type) whose value is ! considered false (e.g. None, or a number that is zero, or an empty ! sequence or mapping), this state is not pickled and __setstate__ ! will not be called at all. If __getstate__ exists and returns a ! true value, that value becomes the third element of the tuple ! returned by the default __reduce__, and at unpickling time the ! value is passed to __setstate__. If __getstate__ does not exist, ! but obj.__dict__ exists, then obj.__dict__ becomes the third ! element of the tuple returned by __reduce__, and again at ! unpickling time the value is passed to obj.__setstate__. The ! default __setstate__ is the same as that for classic classes, ! described above. Note that this strategy ignores slots. Instances of new-style *************** *** 415,420 **** this condition. ! XXX Is it the case that "pickling new-style class instances using ! XXX protocols 0 or 1" ignores __getinitargs__? Case 3: pickling new-style class instances using protocol 2 --- 424,431 ---- this condition. ! Note that pickling new-style class instances ignores __getinitargs__ ! if it exists (and under all protocols). __getinitargs__ is ! useful only for classic classes. ! Case 3: pickling new-style class instances using protocol 2 *************** *** 424,433 **** default implementation is used, which allows more efficient pickling of new-style class instances than possible with protocols ! 0 or 1, at the cost of backward incompatibility with Python 2.2. The customization uses three special methods: __getstate__, ! __setstate__ and __getnewargs__. It is fine if a class implements ! one or more but not all of these, as long as it is compatible with ! the default implementations. The __getstate__ method --- 435,447 ---- default implementation is used, which allows more efficient pickling of new-style class instances than possible with protocols ! 0 or 1, at the cost of backward incompatibility with Python 2.2 ! (meaning no more than that a protocol 2 pickle cannot be unpickled ! before Python 2.3). The customization uses three special methods: __getstate__, ! __setstate__ and __getnewargs__ (note that __getinitargs__ is again ! ignored). It is fine if a class implements one or more but not all ! of these, as long as it is compatible with the default ! implementations. The __getstate__ method *************** *** 444,461 **** __setstate__ won't be called at all as part of unpickling. ! If no __getstate__ method exists, a default state is assumed. There are several cases: - For a new-style class that has an instance __dict__ and no __slots__, the default state is self.__dict__. - - For a new-style class that has no instance __dict__ and no - __slots__, the default __state__ is None. - - For a new-style class that has an instance __dict__ and __slots__, the default state is a tuple consisting of two ! dictionaries: the first being self.__dict__, and the second ! being a dictionary mapping slot names to slot values. Only ! slots that have a value are included in the latter. - For a new-style class that has __slots__ and no instance --- 458,475 ---- __setstate__ won't be called at all as part of unpickling. ! If no __getstate__ method exists, a default state is computed. There are several cases: + - For a new-style class that has no instance __dict__ and no + __slots__, the default state is None. + - For a new-style class that has an instance __dict__ and no __slots__, the default state is self.__dict__. - For a new-style class that has an instance __dict__ and __slots__, the default state is a tuple consisting of two ! dictionaries: self.__dict__, and a dictionary mapping slot ! names to slot values. Only slots that have a value are ! included in the latter. - For a new-style class that has __slots__ and no instance *************** *** 466,472 **** The __setstate__ method ! The __setstate__ should take one argument; it will be called ! with the value returned by __getstate__ or with the default ! state described above if no __setstate__ method is defined. If no __setstate__ method exists, a default implementation is --- 480,487 ---- The __setstate__ method ! The __setstate__ method should take one argument; it will be ! called with the value returned by __getstate__ or with the ! default state described above if no __getstate__ method is ! defined. If no __setstate__ method exists, a default implementation is *************** *** 485,492 **** obj = C.__new__(C, *args) ! where args is either the empty tuple, or the tuple returned by ! the __getnewargs__ method, if defined. __getnewargs__ must ! return a tuple. The absence of a __getnewargs__ method is ! equivalent to the existence of one that returns (). --- 500,508 ---- obj = C.__new__(C, *args) ! where C is the class of the pickled object, and args is either ! the empty tuple, or the tuple returned by the __getnewargs__ ! method, if defined. __getnewargs__ must return a tuple. The ! absence of a __getnewargs__ method is equivalent to the existence ! of one that returns (). *************** *** 673,677 **** Pickling and unpickling Python longs takes time quadratic in ! the number of digits, in protocols 1 and 2. Under protocol 2, new opcodes support linear-time pickling and unpickling of longs. --- 689,693 ---- Pickling and unpickling Python longs takes time quadratic in ! the number of digits, in protocols 0 and 1. Under protocol 2, new opcodes support linear-time pickling and unpickling of longs. *************** *** 682,686 **** directly. Under protocols 0 and 1, bools are pickled as integers, using a trick in the representation of the integer in the pickle ! so that an unpickler can recognize that a bool was intended. --- 698,704 ---- directly. Under protocols 0 and 1, bools are pickled as integers, using a trick in the representation of the integer in the pickle ! so that an unpickler can recognize that a bool was intended. That ! trick consumed 4 bytes per bool pickled. The new bool opcodes ! consume 1 byte per bool. From rhettinger@users.sourceforge.net Tue Feb 11 05:43:59 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Mon, 10 Feb 2003 21:43:59 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv19656 Modified Files: pep-0308.txt Log Message: Updated the PEP for GvR. * Out of order evaluation is out of favor. * So are ideas that do not provide for short-circuiting. * (if : else: ) is in vogue. * ?? || is a new contender. * cond(, , ) is viable if implemented as a keyword and has short-circuit behavior. * Added a summary of a few ideas from the last couple hundred posts from comp.lang.python. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** pep-0308.txt 9 Feb 2003 05:12:54 -0000 1.9 --- pep-0308.txt 11 Feb 2003 05:43:56 -0000 1.10 *************** *** 3,7 **** Version: $Revision$ Last-Modified: $Date$ ! Author: Guido van Rossum Status: Draft Type: Standards Track --- 3,7 ---- Version: $Revision$ Last-Modified: $Date$ ! Author: Guido van Rossum and Raymond D. Hettinger Status: Draft Type: Standards Track *************** *** 28,32 **** The proposed syntax is as follows: ! if else This is evaluated like this: --- 28,33 ---- The proposed syntax is as follows: ! (if : else: ) ! This is evaluated like this: *************** *** 41,63 **** Note that at most one of and is ! evaluated. This is called a "shortcut expression"; it is similar to the way the second operand of 'and' / 'or' is only evaluated if the first operand is true / false. - To disambiguate this in the context of other operators, the - "if...else" part in the middle acts like a right-associative - binary operator with a priority lower than that of "or", and - higher than that of "lambda". - - Examples of how this works out: - - x if C else y if D else z <==> x if C else (y if D else z) - x or y if C else z <==> (x or y) if C else z - x if C else y or z <==> x if C else (y or z) - lambda: x if C else y <==> lambda: (x if C else y) - x if C else lambda: y <==> SyntaxError - x if C else y, z <==> (x if C else y), z - x, y if C else z <==> x, (y if C else z) - Note: a common way to emulate an if-then-else expression is: --- 42,49 ---- Note that at most one of and is ! evaluated. This is called a "short-circuit expression"; it is similar to the way the second operand of 'and' / 'or' is only evaluated if the first operand is true / false. Note: a common way to emulate an if-then-else expression is: *************** *** 72,82 **** Alternatives Many C-derived languages use this syntax: ? : ! Eric Raymond even implemented this. I reject this for several ! reasons: the colon already has many uses in Python (even though it ! would actually not be ambiguous, because the question mark requires a matching colon); for people not used to C-derived language, it is hard to understand. --- 58,77 ---- Alternatives + The original version of this PEP proposed the following syntax: + + if else + + The out-of-order arrangement was found to be too uncomfortable + for many of participants in the discussion. + + --- + Many C-derived languages use this syntax: ? : ! Eric Raymond even implemented this. The BDFL rejected this for ! several reasons: the colon already has many uses in Python (even ! though it would actually not be ambiguous, because the question mark requires a matching colon); for people not used to C-derived language, it is hard to understand. *************** *** 94,168 **** --- ! If we could live with adding a new keyword, we could use: ! if then else ! Apart from the problem of introducing a new keyword for a minor ! feature, this also suffers from ambiguity at the start of a ! statement; for example: ! if verbose then sys.stdout.write("hello\n") else None ! could be an syntactically correct expression statement, but starts ! with 'if', which makes the parser believe it is the start of an ! 'if' statement. To resolve this, the syntax would have to require ! parentheses, which makes it uglier. However, this form has the ! advantage of evaluating strictly from left to right (not that that ! is a requirement for being Pythonic -- list comprehensions don't). ! --- ! To deal with the problem of adding a new keyword, this variant has ! been proposed: - if : else ! This has the same ambiguity problem as the previous one (I would ! even say more so), and lacks symmetry. It also begs the question ! why there isn't a colon after the 'else'. But this: ! if : else: ! is even more confusing because it resembles the if statement so ! much. (A solution that *doesn't* resemble the if statement is ! better IMO since it should be obvious at first glance whether ! we're dealing with an if expression or with an if statement. ! Placing the 'if' in the middle somehow satisfies this ! requirement.) ! --- ! Many people suggest adding a new builtin instead of extending the ! syntax of the language, e.g.: ! ifelse(condition, expression1, expression2) ! This won't work the way a syntax extension will because both ! expression1 and expression2 must be evaluated before the function ! is called. There's no way to short-circuit the expression ! evaluation. ! Variations ! It has been proposed to make the 'else' part optional. This would ! be a really bad idea. I showed: ! x = e if C ! to several people. They all thought that if C was false, it would ! leave x unchanged. So don't even think about this one! ! --- ! Another variant proposes to use 'when' instead of 'if': ! when else ! I don't see the advantage of 'when' over 'if'; it adds a new ! keyword which is a major extra hurdle to introduce this. I think ! that using a different keyword suggests that the semantics are ! different than those of an 'if' statement; but they really aren't ! (only the syntax is different). --- 89,232 ---- --- ! Raymond Hettinger proposed a variant that removes the ! arbitrariness: ! ?? || ! The ?? and || are not arbitrary as they strongly suggest testing ! and alternation. Another merit is that that existing operators ! are not overloaded. Having two characters at each step also ! helps visually separate the subordinate expressions. Alas, ! the BDFL prefers the proposed syntax and considers this as ! alternative number one. ! --- ! Many people suggest adding a new builtin instead of extending the ! syntax of the language, e.g.: ! ifelse(, , ) ! This won't work the way a syntax extension will because both ! expression1 and expression2 must be evaluated before the function ! is called. There's no way to short-circuit the expression ! evaluation. ! Summary of the Current State of the Discussion ! Groups are falling into one of five camps: ! 1. Adopt a ternary operator built using punctuation characters. ! It would look something like: ! ?? || ! 2. Adopt a ternary operator built using existing keywords. ! The proposal listed above is the leading example. ! 3. Adopt a ternary operator built using a new keyword. ! The leading contender looks like this: ! cond(, , ) ! 4. Adopt a function without short-circuit behavior: ! cond(, , ) ! 5. Do nothing. + The first two positions are relatively similar. ! Some find that any form of punctuation makes the language more ! cryptic. Others find that punctuation style is appropriate ! for expressions rather than statements and helps avoid a COBOL ! style: 3 plus 4 times 5. ! Adapting existing keywords attempts to improve on punctuation ! through explicit meaning and a more tidy appearance. The downside ! is some loss of the economy-of-expression provided by punctuation ! operators. The other downside is that it creates some degree of ! confusion between the two meanings and two usages of the keywords. ! The third form introduces a new keyword and arranges the arguments ! separated by commas. Adding a new keyword is to be generally avoided. ! But the form is clear, short, and direct. There is a possible ! confusion with function syntax which implies that all the arguments ! are evaluated rather than short-circuited. This idea was presented ! by the BDFL and should be considered a contender for the final vote. ! The exact keyword is still an open question. One proposal was iif(), ! but it looks like a typo and can be confused with if-and-only-if ! which has a different, well-defined mathematical meaning. ! The fourth position is much more conservative. Adding a new ! function, cond(), is trivially easy to implement and fits easily ! within the existing python model. Users of older versions of ! Python will find it trivial to simulate. The downside is that ! it does not provide the sought-after short-circuit ! evaluation (see the discussion below on the need for this). ! The bigger downside is that the BDFL opposes *any* solution that ! does not provide short circuit behavior. ! The last position is doing nothing. Arguments in favor include ! keeping the language simple and concise; maintaining backwards ! compatibility; and that any every use cases can already be already ! expressed in terms of "if" and "else". Lambda expressions are ! an exception as they require the conditional to be factored out ! into a separate function definition. ! The arguments against doing nothing are that the other choices ! allow greater economy of expression and that current practices ! show a propensity for erroneous uses of "and", "or", or one their ! more complex, visually unappealing workarounds. ! It should also be mentioned that most supporters of any of the ! first four positions do not want an imperfect solution ! and would sooner have no change than create a wart to attain ! their desired functionality. ! ! Short-Circuit Behavior ! ! The principal difference between the ternary operator ! and the cond() function is that the latter provides an expression ! form but does not provide short-circuit evaluation. ! ! Short-circuit evaluation is desirable on three occasions: ! ! 1. When an expression has side-effects ! 2. When one or both of the expressions are resource intensive ! 3. When the condition serves as a guard for the validity of the ! expression. ! ! # Example where all three reasons apply ! data = isinstance(source, file) ?? source.readlines() ! || source.split() ! ! 1. readlines() moves the file pointer ! 2. for long sources, both alternatives take time ! 3. split() is only valid for strings and readlines() is only ! valid for file objects. ! ! Supporters of the cond() function point-out that the need for ! short-circuit evaluation is rare. Scanning through existing ! code directories, they found that if/else did not occur often; ! and of those only a few contained expressions that could be ! helped by cond() or a ternary operator; and that most of those ! had no need for short-circuit evaluation. Hence, cond() would ! suffice for most needs and would spare efforts to alter the ! syntax of the language. ! ! More supporting evidence comes from scans of C code ! bases which show that its ternary operator used very rarely ! (as a percentage of lines of code). ! ! A counter point to that analysis is that the availability ! of a ternary operator helped the programmer in every case ! because it spared the need to search for side-effects. ! Further, it would preclude errors arising from distant ! modifications which introduce side-effects. The latter case ! has become more of a reality with the advent of properties ! where even attribute access can be given side-effects. ! ! Still, the point is moot since the BDFL opposes solutions ! which do not provide short-circuit behavior. From rhettinger@users.sourceforge.net Tue Feb 11 06:32:55 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Mon, 10 Feb 2003 22:32:55 -0800 Subject: [Python-checkins] python/nondist/peps pep-0000.txt,1.229,1.230 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv1884 Modified Files: pep-0000.txt Log Message: Add name of updater. Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.229 retrieving revision 1.230 diff -C2 -d -r1.229 -r1.230 *** pep-0000.txt 10 Feb 2003 14:54:10 -0000 1.229 --- pep-0000.txt 11 Feb 2003 06:32:52 -0000 1.230 *************** *** 110,114 **** S 305 CSV File API Montanaro, et al S 307 Extensions to the pickle protocol GvR, Peters ! S 308 If-then-else expression GvR S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore --- 110,114 ---- S 305 CSV File API Montanaro, et al S 307 Extensions to the pickle protocol GvR, Peters ! S 308 If-then-else expression GvR, Hettinger S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore *************** *** 310,314 **** I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters ! S 308 If-then-else expression GvR S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore --- 310,314 ---- I 306 How to Change Python's Grammar Hudson S 307 Extensions to the pickle protocol GvR, Peters ! S 308 If-then-else expression GvR, Hettinger S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore From lemburg@users.sourceforge.net Tue Feb 11 13:19:54 2003 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Tue, 11 Feb 2003 05:19:54 -0800 Subject: [Python-checkins] python/nondist/peps pep-0249.txt,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv23540 Modified Files: pep-0249.txt Log Message: Added note about new datetime module in Python 2.3. Index: pep-0249.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0249.txt,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** pep-0249.txt 13 Nov 2002 21:20:45 -0000 1.8 --- pep-0249.txt 11 Feb 2003 13:19:51 -0000 1.9 *************** *** 572,575 **** --- 572,581 ---- Objects/bufferobject.c in the Python source distribution. + + * Starting with Python 2.3, module authors can also use the object + types defined in the standard datetime module for date/time + processing. However, it should be noted that this does not + expose a C API like mxDateTime does which means that integration + with C based database modules is more difficult. * Here is a sample implementation of the Unix ticks based From montanaro@users.sourceforge.net Tue Feb 11 14:13:28 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:13:28 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv22594 Modified Files: csv.py Log Message: fix bad test of dict keys against fieldnames Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** csv.py 10 Feb 2003 22:45:21 -0000 1.29 --- csv.py 11 Feb 2003 14:13:25 -0000 1.30 *************** *** 86,91 **** dialect="excel", *args): self.fieldnames = fieldnames # list of keys for the dict - self._fnsort = fieldnames[:] - self._fnsort.sort() self.restval = restval # for writing short dicts if extrasaction.lower() not in ("raise", "ignore"): --- 86,89 ---- *************** *** 97,105 **** def _dict_to_list(self, rowdict): ! keys = rowdict.keys() ! keys.sort() ! if keys != self._fnsort: ! if self.extrasaction == "raise": ! raise ValueError, "dict contains fields not in fieldnames" return [rowdict.get(key, self.restval) for key in self.fieldnames] --- 95,102 ---- def _dict_to_list(self, rowdict): ! if self.extrasaction == "raise": ! for k in rowdict.keys(): ! if k not in self.fieldnames: ! raise ValueError, "dict contains fields not in fieldnames" return [rowdict.get(key, self.restval) for key in self.fieldnames] From montanaro@users.sourceforge.net Tue Feb 11 14:14:05 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:14:05 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv23046 Modified Files: test_csv.py Log Message: forgot to make rest->restkey change in test case Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** test_csv.py 10 Feb 2003 15:15:15 -0000 1.28 --- test_csv.py 11 Feb 2003 14:14:02 -0000 1.29 *************** *** 393,397 **** def test_read_long_with_rest(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), ! fieldnames=["f1", "f2"], rest="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) --- 393,397 ---- def test_read_long_with_rest(self): reader = csv.DictReader(StringIO("1,2,abc,4,5,6\r\n"), ! fieldnames=["f1", "f2"], restkey="_rest") self.assertEqual(reader.next(), {"f1": '1', "f2": '2', "_rest": ["abc", "4", "5", "6"]}) From mwh@users.sourceforge.net Tue Feb 11 14:19:58 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:19:58 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.117,1.118 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv26490 Modified Files: whatsnew23.tex Log Message: Add item pertaining to [ 680429 ] __module__ broken for extension classes Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.117 retrieving revision 1.118 diff -C2 -d -r1.117 -r1.118 *** whatsnew23.tex 10 Feb 2003 19:24:50 -0000 1.117 --- whatsnew23.tex 11 Feb 2003 14:19:56 -0000 1.118 *************** *** 1974,1977 **** --- 1974,1986 ---- Expat. + \item If you dynamically allocate type objects in your extension, you + should be aware of a change in the rules rules relating to the + \member{__module__} and \member{__name__} attributes. In summary, + you will want to ensure the type's dictionary contains a + \code{'__module__'} key; making the module name the part of the type + name leading up to the final period will no longer have the desired + effect. For more detail, read the API reference documentation or the + source. + \end{itemize} From mwh@users.sourceforge.net Tue Feb 11 14:24:18 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:24:18 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv28749 Modified Files: libitertools.tex Log Message: Fix so it compiles at least. "make lib" takes a while, doesn't it? Index: libitertools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libitertools.tex,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** libitertools.tex 9 Feb 2003 06:40:57 -0000 1.3 --- libitertools.tex 11 Feb 2003 14:24:13 -0000 1.4 *************** *** 46,50 **** Other tools are being considered for inclusion in future versions of the module. For instance, the function ! \function{chain(\var{it0}, \var{it1}, ...})} would return elements from the first iterator until it was exhausted and then move on to each successive iterator. The module author welcomes suggestions for other --- 46,50 ---- Other tools are being considered for inclusion in future versions of the module. For instance, the function ! \function{chain(\var{it0}, \var{it1}, ...)} would return elements from the first iterator until it was exhausted and then move on to each successive iterator. The module author welcomes suggestions for other From nnorwitz@users.sourceforge.net Tue Feb 11 14:30:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:30:43 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.118,1.119 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv32407/Doc/whatsnew Modified Files: whatsnew23.tex Log Message: Remove duplicate word (rules) Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.118 retrieving revision 1.119 diff -C2 -d -r1.118 -r1.119 *** whatsnew23.tex 11 Feb 2003 14:19:56 -0000 1.118 --- whatsnew23.tex 11 Feb 2003 14:30:39 -0000 1.119 *************** *** 1975,1979 **** \item If you dynamically allocate type objects in your extension, you ! should be aware of a change in the rules rules relating to the \member{__module__} and \member{__name__} attributes. In summary, you will want to ensure the type's dictionary contains a --- 1975,1979 ---- \item If you dynamically allocate type objects in your extension, you ! should be aware of a change in the rules relating to the \member{__module__} and \member{__name__} attributes. In summary, you will want to ensure the type's dictionary contains a From montanaro@users.sourceforge.net Tue Feb 11 14:48:36 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:48:36 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv10178 Modified Files: test_csv.py Log Message: add some leakage tests (I think writerow() leaks) Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** test_csv.py 11 Feb 2003 14:14:02 -0000 1.29 --- test_csv.py 11 Feb 2003 14:48:32 -0000 1.30 *************** *** 6,9 **** --- 6,10 ---- from StringIO import StringIO import csv + import gc class Test_Csv(unittest.TestCase): *************** *** 446,449 **** --- 447,516 ---- expected = ",".join(a)+"\r\n" self.assertEqual(fileobj.getvalue(), expected) + + if hasattr(sys, "gettotalrefcount"): + class TestLeaks(unittest.TestCase): + def test_create_read(self): + deltas = [] + lastrc = sys.gettotalrefcount() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + csv.reader(["a,b,c\r\n"]) + csv.reader(["a,b,c\r\n"]) + csv.reader(["a,b,c\r\n"]) + deltas.append(rc-lastrc) + lastrc = rc + # if csv.reader() leaks, delta should be 3 or more + self.assertEqual(deltas[-1] < 3, True) + + def test_create_write(self): + deltas = [] + lastrc = sys.gettotalrefcount() + s = StringIO() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + csv.writer(s) + csv.writer(s) + csv.writer(s) + deltas.append(rc-lastrc) + lastrc = rc + # if csv.writer() leaks, delta should be 3 or more + self.assertEqual(deltas[-1] < 3, True) + + def test_read(self): + deltas = [] + lastrc = sys.gettotalrefcount() + rows = ["a,b,c\r\n"]*5 + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + rdr = csv.reader(rows) + for row in rdr: + pass + deltas.append(rc-lastrc) + lastrc = rc + # if reader leaks during read, delta should be 5 or more + self.assertEqual(deltas[-1] < 5, True) + + def test_write(self): + deltas = [] + lastrc = sys.gettotalrefcount() + rows = [[1,2,3]]*5 + s = StringIO() + for i in xrange(20): + gc.collect() + self.assertEqual(gc.garbage, []) + rc = sys.gettotalrefcount() + writer = csv.writer(s) + for row in rows: + writer.writerow(row) + deltas.append(rc-lastrc) + lastrc = rc + # if reader leaks during read, delta should be 5 or more + self.assertEqual(deltas[-1] < 5, True) def _testclasses(): From montanaro@users.sourceforge.net Tue Feb 11 14:51:43 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:51:43 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv12310 Modified Files: test_csv.py Log Message: note when leakage tests can't be run Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** test_csv.py 11 Feb 2003 14:48:32 -0000 1.30 --- test_csv.py 11 Feb 2003 14:51:41 -0000 1.31 *************** *** 448,452 **** self.assertEqual(fileobj.getvalue(), expected) ! if hasattr(sys, "gettotalrefcount"): class TestLeaks(unittest.TestCase): def test_create_read(self): --- 448,454 ---- self.assertEqual(fileobj.getvalue(), expected) ! if not hasattr(sys, "gettotalrefcount"): ! print "*** skipping leakage tests ***" ! else: class TestLeaks(unittest.TestCase): def test_create_read(self): From gvanrossum@users.sourceforge.net Tue Feb 11 14:59:21 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 06:59:21 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv16475 Modified Files: pep-0308.txt Log Message: Minor nits. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** pep-0308.txt 11 Feb 2003 05:43:56 -0000 1.10 --- pep-0308.txt 11 Feb 2003 14:59:18 -0000 1.11 *************** *** 8,12 **** Content-Type: text/plain Created: 7-Feb-2003 ! Post-History: 7-Feb-2003 --- 8,12 ---- Content-Type: text/plain Created: 7-Feb-2003 ! Post-History: 7-Feb-2003, 11-Feb-2003 *************** *** 23,26 **** --- 23,33 ---- If the community can't decide, I'll reject the PEP. + After unprecedented community response (very food arguments were + made both pro and con) this PEP has been revised with the help of + Raymond Hettinger. Without going through a complete revision + history, the main changes are a different proposed syntax, an + overview of proposed alternatives, the state of the curent + discussion, and a discussion of short-circuit behavior. + Proposal *************** *** 42,50 **** Note that at most one of and is ! evaluated. This is called a "short-circuit expression"; it is similar ! to the way the second operand of 'and' / 'or' is only evaluated if ! the first operand is true / false. ! Note: a common way to emulate an if-then-else expression is: and or --- 49,57 ---- Note that at most one of and is ! evaluated. This is called a "short-circuit expression"; it is ! similar to the way the second operand of 'and' / 'or' is only ! evaluated if the first operand is true / false. ! A common way to emulate an if-then-else expression is: and or *************** *** 52,57 **** However, this doesn't work the same way: it returns when is false! See FAQ 4.16 for alternatives that ! work -- however, they are pretty ugly and require much more ! effort to understand. --- 59,64 ---- However, this doesn't work the same way: it returns when is false! See FAQ 4.16 for alternatives that ! work -- however, they are pretty ugly and require much more effort ! to understand. *************** *** 63,67 **** The out-of-order arrangement was found to be too uncomfortable ! for many of participants in the discussion. --- --- 70,76 ---- The out-of-order arrangement was found to be too uncomfortable ! for many of participants in the discussion; especially when ! is long, it's easy to miss the conditional while ! skimming. --- *************** *** 73,78 **** Eric Raymond even implemented this. The BDFL rejected this for several reasons: the colon already has many uses in Python (even ! though it would actually not be ambiguous, because the question mark ! requires a matching colon); for people not used to C-derived language, it is hard to understand. --- 82,87 ---- Eric Raymond even implemented this. The BDFL rejected this for several reasons: the colon already has many uses in Python (even ! though it would actually not be ambiguous, because the question ! mark requires a matching colon); for people not used to C-derived language, it is hard to understand. *************** *** 92,103 **** arbitrariness: ! ?? || The ?? and || are not arbitrary as they strongly suggest testing and alternation. Another merit is that that existing operators ! are not overloaded. Having two characters at each step also ! helps visually separate the subordinate expressions. Alas, ! the BDFL prefers the proposed syntax and considers this as ! alternative number one. --- --- 101,112 ---- arbitrariness: ! ?? || The ?? and || are not arbitrary as they strongly suggest testing and alternation. Another merit is that that existing operators ! are not overloaded. Having two characters at each step also helps ! visually separate the subordinate expressions. Alas, the BDFL ! prefers the proposed syntax and considers this alternative "too ! Perlish". --- *************** *** 106,115 **** syntax of the language, e.g.: ! ifelse(, , ) This won't work the way a syntax extension will because both expression1 and expression2 must be evaluated before the function is called. There's no way to short-circuit the expression ! evaluation. --- 115,128 ---- syntax of the language, e.g.: ! cond(, , ) This won't work the way a syntax extension will because both expression1 and expression2 must be evaluated before the function is called. There's no way to short-circuit the expression ! evaluation. It could work if 'cond' (or some other name) were ! made a keyword, but that has all the disadvantages of adding a new ! keyword, plus confusing syntax: it *looks* like a function call so ! a casual reader might expect both and ! to be evaluated. *************** *** 137,143 **** Some find that any form of punctuation makes the language more ! cryptic. Others find that punctuation style is appropriate ! for expressions rather than statements and helps avoid a COBOL ! style: 3 plus 4 times 5. Adapting existing keywords attempts to improve on punctuation --- 150,156 ---- Some find that any form of punctuation makes the language more ! cryptic. Others find that punctuation style is appropriate for ! expressions rather than statements and helps avoid a COBOL style: ! 3 plus 4 times 5. Adapting existing keywords attempts to improve on punctuation *************** *** 148,175 **** The third form introduces a new keyword and arranges the arguments ! separated by commas. Adding a new keyword is to be generally avoided. ! But the form is clear, short, and direct. There is a possible ! confusion with function syntax which implies that all the arguments ! are evaluated rather than short-circuited. This idea was presented ! by the BDFL and should be considered a contender for the final vote. ! The exact keyword is still an open question. One proposal was iif(), ! but it looks like a typo and can be confused with if-and-only-if ! which has a different, well-defined mathematical meaning. The fourth position is much more conservative. Adding a new function, cond(), is trivially easy to implement and fits easily within the existing python model. Users of older versions of ! Python will find it trivial to simulate. The downside is that ! it does not provide the sought-after short-circuit ! evaluation (see the discussion below on the need for this). ! The bigger downside is that the BDFL opposes *any* solution that ! does not provide short circuit behavior. The last position is doing nothing. Arguments in favor include keeping the language simple and concise; maintaining backwards compatibility; and that any every use cases can already be already ! expressed in terms of "if" and "else". Lambda expressions are ! an exception as they require the conditional to be factored out ! into a separate function definition. The arguments against doing nothing are that the other choices --- 161,189 ---- The third form introduces a new keyword and arranges the arguments ! separated by commas. Adding a new keyword is to be generally ! avoided. But the form is clear, short, and direct. There is a ! possible confusion with function syntax which implies that all the ! arguments are evaluated rather than short-circuited. This idea ! was presented by the BDFL and should be considered a contender for ! the final vote. The exact keyword is still an open question. One ! proposal was iif(), but it looks like a typo and can be confused ! with if-and-only-if which has a different, well-defined ! mathematical meaning. The fourth position is much more conservative. Adding a new function, cond(), is trivially easy to implement and fits easily within the existing python model. Users of older versions of ! Python will find it trivial to simulate. The downside is that it ! does not provide the sought-after short-circuit evaluation (see ! the discussion below on the need for this). The bigger downside ! is that the BDFL opposes *any* solution that does not provide ! short circuit behavior. The last position is doing nothing. Arguments in favor include keeping the language simple and concise; maintaining backwards compatibility; and that any every use cases can already be already ! expressed in terms of "if" and "else". Lambda expressions are an ! exception as they require the conditional to be factored out into ! a separate function definition. The arguments against doing nothing are that the other choices *************** *** 179,192 **** It should also be mentioned that most supporters of any of the ! first four positions do not want an imperfect solution ! and would sooner have no change than create a wart to attain ! their desired functionality. Short-Circuit Behavior ! The principal difference between the ternary operator ! and the cond() function is that the latter provides an expression ! form but does not provide short-circuit evaluation. Short-circuit evaluation is desirable on three occasions: --- 193,206 ---- It should also be mentioned that most supporters of any of the ! first four positions do not want an imperfect solution and would ! sooner have no change than create a wart to attain their desired ! functionality. Short-Circuit Behavior ! The principal difference between the ternary operator and the ! cond() function is that the latter provides an expression form but ! does not provide short-circuit evaluation. Short-circuit evaluation is desirable on three occasions: *************** *** 207,232 **** Supporters of the cond() function point-out that the need for ! short-circuit evaluation is rare. Scanning through existing ! code directories, they found that if/else did not occur often; ! and of those only a few contained expressions that could be ! helped by cond() or a ternary operator; and that most of those ! had no need for short-circuit evaluation. Hence, cond() would ! suffice for most needs and would spare efforts to alter the ! syntax of the language. ! More supporting evidence comes from scans of C code ! bases which show that its ternary operator used very rarely ! (as a percentage of lines of code). ! A counter point to that analysis is that the availability ! of a ternary operator helped the programmer in every case ! because it spared the need to search for side-effects. ! Further, it would preclude errors arising from distant ! modifications which introduce side-effects. The latter case ! has become more of a reality with the advent of properties ! where even attribute access can be given side-effects. ! Still, the point is moot since the BDFL opposes solutions ! which do not provide short-circuit behavior. --- 221,246 ---- Supporters of the cond() function point-out that the need for ! short-circuit evaluation is rare. Scanning through existing code ! directories, they found that if/else did not occur often; and of ! those only a few contained expressions that could be helped by ! cond() or a ternary operator; and that most of those had no need ! for short-circuit evaluation. Hence, cond() would suffice for ! most needs and would spare efforts to alter the syntax of the ! language. ! More supporting evidence comes from scans of C code bases which ! show that its ternary operator used very rarely (as a percentage ! of lines of code). ! A counter point to that analysis is that the availability of a ! ternary operator helped the programmer in every case because it ! spared the need to search for side-effects. Further, it would ! preclude errors arising from distant modifications which introduce ! side-effects. The latter case has become more of a reality with ! the advent of properties where even attribute access can be given ! side-effects. ! The BDFL's position is that short-circuit behavior is essential ! for an if-then-else construct to be added to the language. From mal@lemburg.com Tue Feb 11 15:11:42 2003 From: mal@lemburg.com (M.-A. Lemburg) Date: Tue, 11 Feb 2003 16:11:42 +0100 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.275,2.276 ceval.c,2.348,2.349 compile.c,2.273,2.274 In-Reply-To: <3E47696B.4050208@lemburg.com> References: <3E47696B.4050208@lemburg.com> Message-ID: <3E4912AE.8030909@lemburg.com> Just, have you fixed this yet ? I didn't see a checkin related to this. M.-A. Lemburg wrote: > jvr@users.sourceforge.net wrote: > >> Update of /cvsroot/python/python/dist/src/Python >> In directory sc8-pr-cvs1:/tmp/cvs-serv19147/Python >> >> Modified Files: >> bltinmodule.c ceval.c compile.c Log Message: >> patch #683515: "Add unicode support to compile(), eval() and exec" >> Incorporated nnorwitz's comment re. Py__USING_UNICODE. >> >> >> Index: bltinmodule.c >> =================================================================== >> RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v >> retrieving revision 2.275 >> retrieving revision 2.276 >> diff -C2 -d -r2.275 -r2.276 >> *** bltinmodule.c 4 Feb 2003 20:24:43 -0000 2.275 >> --- bltinmodule.c 10 Feb 2003 08:21:07 -0000 2.276 >> *************** >> *** 341,349 **** >> int supplied_flags = 0; >> PyCompilerFlags cf; >> ! if (!PyArg_ParseTuple(args, "sss|ii:compile", &str, &filename, >> &startstr, &supplied_flags, &dont_inherit)) >> return NULL; >> if (strcmp(startstr, "exec") == 0) >> start = Py_file_input; >> --- 341,370 ---- >> int supplied_flags = 0; >> PyCompilerFlags cf; >> + PyObject *result, *cmd, *tmp = NULL; >> ! if (!PyArg_ParseTuple(args, "Oss|ii:compile", &cmd, &filename, >> &startstr, &supplied_flags, &dont_inherit)) >> return NULL; >> + cf.cf_flags = supplied_flags; >> + + #ifdef Py_USING_UNICODE >> + if (PyUnicode_Check(cmd)) { >> + tmp = PyUnicode_AsUTF8String(cmd); >> + if (tmp == NULL) >> + return NULL; >> + cmd = tmp; >> + cf.cf_flags |= PyCF_SOURCE_IS_UTF8; >> + } >> + #endif >> + if (!PyString_Check(cmd)) { >> + PyErr_SetString(PyExc_TypeError, >> + "compile() arg 1 must be a string"); >> + return NULL; >> + } >> + + if (PyString_AsStringAndSize(cmd, &str, NULL)) >> + return NULL; >> + > > > This will break code: the "s" parser marker allows passing in > any buffer compatible object. You'll have to use > PyObject_AsReadBuffer() here to be backward compatible. > -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Feb 11 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ Python UK 2003, Oxford: 49 days left EuroPython 2003, Charleroi, Belgium: 133 days left From gvanrossum@users.sourceforge.net Tue Feb 11 15:53:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 07:53:24 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv15729 Modified Files: pep-0308.txt Log Message: Typo (foo -> good). Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** pep-0308.txt 11 Feb 2003 14:59:18 -0000 1.11 --- pep-0308.txt 11 Feb 2003 15:53:20 -0000 1.12 *************** *** 23,27 **** If the community can't decide, I'll reject the PEP. ! After unprecedented community response (very food arguments were made both pro and con) this PEP has been revised with the help of Raymond Hettinger. Without going through a complete revision --- 23,27 ---- If the community can't decide, I'll reject the PEP. ! After unprecedented community response (very good arguments were made both pro and con) this PEP has been revised with the help of Raymond Hettinger. Without going through a complete revision From jackjansen@users.sourceforge.net Tue Feb 11 16:26:33 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 11 Feb 2003 08:26:33 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE Wlists.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv3354 Modified Files: Wlists.py Log Message: - More int() calls around floating point numbers passed where integers are expected. - Fixed resizing of multi-column lists, somewhat. Index: Wlists.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wlists.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** Wlists.py 30 Nov 2002 00:01:28 -0000 1.13 --- Wlists.py 11 Feb 2003 16:26:26 -0000 1.14 *************** *** 75,79 **** l, t, r, b = self._list.LRect((0,0)) cellheight = b - t ! self._list.LCellSize((width, cellheight)) # reset visRgn self._parentwindow.wid.CalcVis() --- 75,79 ---- l, t, r, b = self._list.LRect((0,0)) cellheight = b - t ! self._list.LCellSize((width/self._cols, cellheight)) # reset visRgn self._parentwindow.wid.CalcVis() *************** *** 457,464 **** else: line2 = "" ! Qd.MoveTo(left + 4, top + ascent) Qd.DrawText(line1, 0, len(line1)) if line2: ! Qd.MoveTo(left + 4, top + ascent + linefeed) Qd.DrawText(line2, 0, len(line2)) Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") --- 457,464 ---- else: line2 = "" ! Qd.MoveTo(int(left + 4), int(top + ascent)) Qd.DrawText(line1, 0, len(line1)) if line2: ! Qd.MoveTo(int(left + 4), int(top + ascent + linefeed)) Qd.DrawText(line2, 0, len(line2)) Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") From gvanrossum@users.sourceforge.net Tue Feb 11 16:25:48 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 08:25:48 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.205,2.206 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv3318 Modified Files: typeobject.c Log Message: Add basic arg sanity checking to wrap_descr_get(). This is called when Python code calls a descriptor's __get__ method. It should translate None to NULL in both argument positions, and insist that at least one of the argument positions is not NULL after this transformation. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.205 retrieving revision 2.206 diff -C2 -d -r2.205 -r2.206 *** typeobject.c 10 Feb 2003 21:31:27 -0000 2.205 --- typeobject.c 11 Feb 2003 16:25:43 -0000 2.206 *************** *** 3434,3437 **** --- 3434,3446 ---- if (!PyArg_ParseTuple(args, "O|O", &obj, &type)) return NULL; + if (obj == Py_None) + obj = NULL; + if (type == Py_None) + type = NULL; + if (type == NULL &&obj == NULL) { + PyErr_SetString(PyExc_TypeError, + "__get__(None, None) is invalid"); + return NULL; + } return (*func)(self, obj, type); } From tim_one@users.sourceforge.net Tue Feb 11 16:40:22 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 08:40:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12156/Lib/test Modified Files: pickletester.py Log Message: Added tests to ensure that list and dict "chunking" are actually getting done. Since this isn't yet implemented in cPickle, the new tests are in TempAbstractPickleTests (which cPickle doesn't run). Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** pickletester.py 4 Feb 2003 21:47:43 -0000 1.44 --- pickletester.py 11 Feb 2003 16:40:16 -0000 1.45 *************** *** 19,22 **** --- 19,30 ---- return False + # Return the number of times opcode code appears in pickle. + def count_opcode(code, pickle): + n = 0 + for op, dummy, dummy in pickletools.genops(pickle): + if op.code == code: + n += 1 + return n + # We can't very well test the extension registry without putting known stuff # in it, but we have to be careful to restore its original state. Code *************** *** 665,669 **** self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness - # XXX Temporary hack, so long as the C implementation of pickle protocol # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests --- 673,676 ---- *************** *** 683,686 **** --- 690,736 ---- self.assertEqual(x.bar, y.bar) + def test_list_chunking(self): + n = 10 # too small to chunk + x = range(n) + for proto in protocols: + s = self.dumps(x, proto) + y = self.loads(s) + self.assertEqual(x, y) + num_appends = count_opcode(pickle.APPENDS, s) + self.assertEqual(num_appends, proto > 0) + + n = 2500 # expect at least two chunks when proto > 0 + x = range(n) + for proto in protocols: + s = self.dumps(x, proto) + y = self.loads(s) + self.assertEqual(x, y) + num_appends = count_opcode(pickle.APPENDS, s) + if proto == 0: + self.assertEqual(num_appends, 0) + else: + self.failUnless(num_appends >= 2) + + def test_dict_chunking(self): + n = 10 # too small to chunk + x = dict.fromkeys(range(n)) + for proto in protocols: + s = self.dumps(x, proto) + y = self.loads(s) + self.assertEqual(x, y) + num_setitems = count_opcode(pickle.SETITEMS, s) + self.assertEqual(num_setitems, proto > 0) + + n = 2500 # expect at least two chunks when proto > 0 + x = dict.fromkeys(range(n)) + for proto in protocols: + s = self.dumps(x, proto) + y = self.loads(s) + self.assertEqual(x, y) + num_setitems = count_opcode(pickle.SETITEMS, s) + if proto == 0: + self.assertEqual(num_setitems, 0) + else: + self.failUnless(num_setitems >= 2) class MyInt(int): From gvanrossum@users.sourceforge.net Tue Feb 11 17:12:53 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 09:12:53 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.206,2.207 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv31417 Modified Files: typeobject.c Log Message: Inline create_specialmethod() -- since METH_CLASS is done differently now, it was only called once, and its existence merely obfuscates the control flow. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.206 retrieving revision 2.207 diff -C2 -d -r2.206 -r2.207 *** typeobject.c 11 Feb 2003 16:25:43 -0000 2.206 --- typeobject.c 11 Feb 2003 17:12:46 -0000 2.207 *************** *** 2495,2512 **** /* Initialize the __dict__ in a type object */ - static PyObject * - create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *)) - { - PyObject *cfunc; - PyObject *result; - - cfunc = PyCFunction_New(meth, NULL); - if (cfunc == NULL) - return NULL; - result = func(cfunc); - Py_DECREF(cfunc); - return result; - } - static int add_methods(PyTypeObject *type, PyMethodDef *meth) --- 2495,2498 ---- *************** *** 2527,2531 **** } else if (meth->ml_flags & METH_STATIC) { ! descr = create_specialmethod(meth, PyStaticMethod_New); } else { --- 2513,2521 ---- } else if (meth->ml_flags & METH_STATIC) { ! PyObject *cfunc = PyCFunction_New(meth, NULL); ! if (cfunc == NULL) ! return -1; ! descr = PyStaticMethod_New(cfunc); ! Py_DECREF(cfunc); } else { From tim_one@users.sourceforge.net Tue Feb 11 17:19:01 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 09:19:01 -0800 Subject: [Python-checkins] python/dist/src/Modules selectmodule.c,2.72,2.73 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv1654/Modules Modified Files: selectmodule.c Log Message: SF bug 684667: Modules/selectmodule.c returns NULL without exception set. select_select() didn't set an exception in the SELECT_USES_HEAP case when malloc() returned NULL. Index: selectmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/selectmodule.c,v retrieving revision 2.72 retrieving revision 2.73 diff -C2 -d -r2.72 -r2.73 *** selectmodule.c 18 Nov 2002 16:02:29 -0000 2.72 --- selectmodule.c 11 Feb 2003 17:18:58 -0000 2.73 *************** *** 249,253 **** if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); ! return NULL; } #endif /* SELECT_USES_HEAP */ --- 249,253 ---- if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); ! return PyErr_NoMemory(); } #endif /* SELECT_USES_HEAP */ From tim_one@users.sourceforge.net Tue Feb 11 18:05:48 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:05:48 -0800 Subject: [Python-checkins] python/dist/src/Modules selectmodule.c,2.59.6.2,2.59.6.3 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv31084/Modules Modified Files: Tag: release22-maint selectmodule.c Log Message: SF bug 684667: Modules/selectmodule.c returns NULL without exception set. Backport of fix from head. Index: selectmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/selectmodule.c,v retrieving revision 2.59.6.2 retrieving revision 2.59.6.3 diff -C2 -d -r2.59.6.2 -r2.59.6.3 *** selectmodule.c 24 Sep 2002 17:24:25 -0000 2.59.6.2 --- selectmodule.c 11 Feb 2003 18:05:44 -0000 2.59.6.3 *************** *** 246,250 **** if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); ! return NULL; } #endif /* SELECT_USES_HEAP */ --- 246,250 ---- if (wfd2obj) PyMem_DEL(wfd2obj); if (efd2obj) PyMem_DEL(efd2obj); ! return PyErr_NoMemory(); } #endif /* SELECT_USES_HEAP */ From gvanrossum@users.sourceforge.net Tue Feb 11 18:43:07 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:43:07 -0800 Subject: [Python-checkins] python/dist/src/Objects classobject.c,2.167,2.168 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv20585 Modified Files: classobject.c Log Message: Refactor instancemethod_descr_get() to (a) be more clear, (b) be safe in the light of weird args, and (c) not to expect None (which is now changed to NULL by slot_tp_descr_get()). Index: classobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/classobject.c,v retrieving revision 2.167 retrieving revision 2.168 diff -C2 -d -r2.167 -r2.168 *** classobject.c 29 Dec 2002 16:33:11 -0000 2.167 --- classobject.c 11 Feb 2003 18:43:00 -0000 2.168 *************** *** 2415,2431 **** static PyObject * ! instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *class) { /* Don't rebind an already bound method, or an unbound method ! of a class that's not a base class of class */ ! if (PyMethod_GET_SELF(meth) != NULL || ! (PyMethod_GET_CLASS(meth) != NULL && ! !PyObject_IsSubclass(class, PyMethod_GET_CLASS(meth)))) { Py_INCREF(meth); return meth; } ! if (obj == Py_None) ! obj = NULL; ! return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, class); } --- 2415,2441 ---- static PyObject * ! instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { /* Don't rebind an already bound method, or an unbound method ! of a class that's not a base class of cls. */ ! ! if (PyMethod_GET_SELF(meth) != NULL) { ! /* Already bound */ Py_INCREF(meth); return meth; } ! /* No, it is an unbound method */ ! if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) { ! /* Do subclass test. If it fails, return meth unchanged. */ ! int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth)); ! if (ok < 0) ! return NULL; ! if (!ok) { ! Py_INCREF(meth); ! return meth; ! } ! } ! /* Bind it to obj */ ! return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls); } From gvanrossum@users.sourceforge.net Tue Feb 11 18:44:51 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:44:51 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.180,1.181 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv20746/Lib/test Modified Files: test_descr.py Log Message: Put proper tests in classmethod_get(). Remove the type argument to descr_check(); it wasn't useful. Change the type argument of the various _get() methods to PyObject * because the call signature of tp_descr_get doesn't guarantee its type. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.180 retrieving revision 1.181 diff -C2 -d -r1.180 -r1.181 *** test_descr.py 10 Feb 2003 21:31:26 -0000 1.180 --- test_descr.py 11 Feb 2003 18:44:42 -0000 1.181 *************** *** 3734,3737 **** --- 3734,3776 ---- veris(type(C.__dict__), type(B.__dict__)) + def meth_class_get(): + # Full coverage of descrobject.c::classmethod_get() + if verbose: print "Testing __get__ method of METH_CLASS C methods..." + # Baseline + arg = [1, 2, 3] + res = {1: None, 2: None, 3: None} + vereq(dict.fromkeys(arg), res) + vereq({}.fromkeys(arg), res) + # Now get the descriptor + descr = dict.__dict__["fromkeys"] + # More baseline using the descriptor directly + vereq(descr.__get__(None, dict)(arg), res) + vereq(descr.__get__({})(arg), res) + # Now check various error cases + try: + descr.__get__(None, None) + except TypeError: + pass + else: + raise TestFailed, "shouldn't have allowed descr.__get__(None, None)" + try: + descr.__get__(42) + except TypeError: + pass + else: + raise TestFailed, "shouldn't have allowed descr.__get__(42)" + try: + descr.__get__(None, 42) + except TypeError: + pass + else: + raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)" + try: + descr.__get__(None, int) + except TypeError: + pass + else: + raise TestFailed, "shouldn't have allowed descr.__get__(None, int)" + def test_main(): *************** *** 3820,3823 **** --- 3859,3863 ---- subclass_right_op() dict_type_with_metaclass() + meth_class_get() if verbose: print "All OK" From gvanrossum@users.sourceforge.net Tue Feb 11 18:45:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:45:15 -0800 Subject: [Python-checkins] python/dist/src/Objects descrobject.c,2.33,2.34 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv20746/Objects Modified Files: descrobject.c Log Message: Put proper tests in classmethod_get(). Remove the type argument to descr_check(); it wasn't useful. Change the type argument of the various _get() methods to PyObject * because the call signature of tp_descr_get doesn't guarantee its type. Index: descrobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/descrobject.c,v retrieving revision 2.33 retrieving revision 2.34 diff -C2 -d -r2.33 -r2.34 *** descrobject.c 29 Dec 2002 16:33:11 -0000 2.33 --- descrobject.c 11 Feb 2003 18:44:39 -0000 2.34 *************** *** 58,65 **** static int ! descr_check(PyDescrObject *descr, PyObject *obj, PyTypeObject *type, ! PyObject **pres) { ! if (obj == NULL || (obj == Py_None && type != Py_None->ob_type)) { Py_INCREF(descr); *pres = (PyObject *)descr; --- 58,64 ---- static int ! descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres) { ! if (obj == NULL) { Py_INCREF(descr); *pres = (PyObject *)descr; *************** *** 80,95 **** static PyObject * ! classmethod_get(PyMethodDescrObject *descr, PyObject *obj, ! PyTypeObject *type) { ! return PyCFunction_New(descr->d_method, (PyObject *)type); } static PyObject * ! method_get(PyMethodDescrObject *descr, PyObject *obj, PyTypeObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, type, &res)) return res; return PyCFunction_New(descr->d_method, obj); --- 79,125 ---- static PyObject * ! classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { ! /* Ensure a valid type. Class methods ignore obj. */ ! if (type == NULL) { ! if (obj != NULL) ! type = (PyObject *)obj->ob_type; ! else { ! /* Wot - no type?! */ ! PyErr_Format(PyExc_TypeError, ! "descriptor '%s' for type '%s' " ! "needs either an object or a type", ! descr_name((PyDescrObject *)descr), ! descr->d_type->tp_name); ! return NULL; ! } ! } ! if (!PyType_Check(type)) { ! PyErr_Format(PyExc_TypeError, ! "descriptor '%s' for type '%s' " ! "needs a type, not a '%s' as arg 2", ! descr_name((PyDescrObject *)descr), ! descr->d_type->tp_name, ! type->ob_type->tp_name); ! return NULL; ! } ! if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) { ! PyErr_Format(PyExc_TypeError, ! "descriptor '%s' for type '%s' " ! "doesn't apply to type '%s'", ! descr_name((PyDescrObject *)descr), ! descr->d_type->tp_name, ! ((PyTypeObject *)type)->tp_name); ! return NULL; ! } ! return PyCFunction_New(descr->d_method, type); } static PyObject * ! method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyCFunction_New(descr->d_method, obj); *************** *** 97,105 **** static PyObject * ! member_get(PyMemberDescrObject *descr, PyObject *obj, PyTypeObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, type, &res)) return res; return PyMember_GetOne((char *)obj, descr->d_member); --- 127,135 ---- static PyObject * ! member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyMember_GetOne((char *)obj, descr->d_member); *************** *** 107,115 **** static PyObject * ! getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyTypeObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, type, &res)) return res; if (descr->d_getset->get != NULL) --- 137,145 ---- static PyObject * ! getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, &res)) return res; if (descr->d_getset->get != NULL) *************** *** 123,131 **** static PyObject * ! wrapper_get(PyWrapperDescrObject *descr, PyObject *obj, PyTypeObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, type, &res)) return res; return PyWrapper_New((PyObject *)descr, obj); --- 153,161 ---- static PyObject * ! wrapper_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; ! if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyWrapper_New((PyObject *)descr, obj); *************** *** 396,403 **** }; static PyTypeObject PyClassMethodDescr_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, ! "special_method_descriptor", sizeof(PyMethodDescrObject), 0, --- 426,434 ---- }; + /* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */ static PyTypeObject PyClassMethodDescr_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, ! "classmethod_descriptor", sizeof(PyMethodDescrObject), 0, *************** *** 412,416 **** 0, /* tp_as_mapping */ 0, /* tp_hash */ ! (ternaryfunc)classmethoddescr_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ --- 443,447 ---- 0, /* tp_as_mapping */ 0, /* tp_hash */ ! (ternaryfunc)classmethoddescr_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ From niemeyer@users.sourceforge.net Tue Feb 11 18:46:22 2003 From: niemeyer@users.sourceforge.net (niemeyer@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:46:22 -0800 Subject: [Python-checkins] python/dist/src/Modules bz2module.c,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv21903/Modules Modified Files: bz2module.c Log Message: Unparenting BZ2File, as discussed in SF patch #661796. * Modules/bz2module.c (BZ2FileObject): Now the structure includes a pointer to a file object, instead of "inheriting" one. Also, some members were copied from the PyFileObject structure to avoid dealing with the internals of that structure from outside fileobject.c. (Util_GetLine,Util_DropReadAhead,Util_ReadAhead,Util_ReadAheadGetLineSkip, BZ2File_write,BZ2File_writelines,BZ2File_init,BZ2File_dealloc, BZ2Comp_dealloc,BZ2Decomp_dealloc): These functions were adapted to the change above. (BZ2File_seek,BZ2File_close): Use PyObject_CallMethod instead of getting the function attribute locally. (BZ2File_notsup): Removed, since it's not necessary anymore to overload truncate(), and readinto() with dummy functions. (BZ2File_methods): Added xreadlines() as an alias to BZ2File_getiter, and removed truncate() and readinto(). (BZ2File_get_newlines,BZ2File_get_closed,BZ2File_get_mode,BZ2File_get_name, BZ2File_getset): Implemented getters for "newlines", "mode", and "name". (BZ2File_members): Implemented "softspace" member. (BZ2File_init): Reworked to create a file instance instead of initializing itself as a file subclass. Also, pass "name" object untouched to the file constructor, and use PyObject_CallFunction instead of building the argument tuple locally. (BZ2File_Type): Set tp_new to PyType_GenericNew, tp_members to BZ2File_members, and tp_getset to BZ2File_getset. (initbz2): Do not set BZ2File_Type.tp_base nor BZ2File_Type.tp_new. * Doc/lib/libbz2.tex Do not mention that BZ2File inherits from the file type. Index: bz2module.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/bz2module.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** bz2module.c 6 Jan 2003 12:41:25 -0000 1.14 --- bz2module.c 11 Feb 2003 18:46:19 -0000 1.15 *************** *** 63,67 **** typedef struct { ! PyFileObject file; BZFILE *fp; int mode; --- 63,81 ---- typedef struct { ! PyObject_HEAD ! PyObject *file; ! ! char* f_buf; /* Allocated readahead buffer */ ! char* f_bufend; /* Points after last occupied position */ ! char* f_bufptr; /* Current buffer position */ ! ! int f_softspace; /* Flag used by 'print' command */ ! ! #ifdef WITH_UNIVERSAL_NEWLINES ! int f_univ_newline; /* Handle any newline convention */ ! int f_newlinetypes; /* Types of newlines seen */ ! int f_skipnextlf; /* Skip next \n */ ! #endif ! BZFILE *fp; int mode; *************** *** 180,184 **** /* This is a hacked version of Python's fileobject.c:get_line(). */ static PyObject * ! Util_GetLine(BZ2FileObject *self, int n) { char c; --- 194,198 ---- /* This is a hacked version of Python's fileobject.c:get_line(). */ static PyObject * ! Util_GetLine(BZ2FileObject *f, int n) { char c; *************** *** 190,196 **** int bzerror; #ifdef WITH_UNIVERSAL_NEWLINES ! int newlinetypes = ((PyFileObject*)self)->f_newlinetypes; ! int skipnextlf = ((PyFileObject*)self)->f_skipnextlf; ! int univ_newline = ((PyFileObject*)self)->f_univ_newline; #endif --- 204,210 ---- int bzerror; #ifdef WITH_UNIVERSAL_NEWLINES ! int newlinetypes = f->f_newlinetypes; ! int skipnextlf = f->f_skipnextlf; ! int univ_newline = f->f_univ_newline; #endif *************** *** 208,213 **** if (univ_newline) { while (1) { ! BZ2_bzRead(&bzerror, self->fp, &c, 1); ! self->pos++; if (bzerror != BZ_OK || buf == end) break; --- 222,227 ---- if (univ_newline) { while (1) { ! BZ2_bzRead(&bzerror, f->fp, &c, 1); ! f->pos++; if (bzerror != BZ_OK || buf == end) break; *************** *** 220,224 **** */ newlinetypes |= NEWLINE_CRLF; ! BZ2_bzRead(&bzerror, self->fp, &c, 1); if (bzerror != BZ_OK) --- 234,238 ---- */ newlinetypes |= NEWLINE_CRLF; ! BZ2_bzRead(&bzerror, f->fp, &c, 1); if (bzerror != BZ_OK) *************** *** 241,256 **** #endif do { ! BZ2_bzRead(&bzerror, self->fp, &c, 1); ! self->pos++; *buf++ = c; } while (bzerror == BZ_OK && c != '\n' && buf != end); Py_END_ALLOW_THREADS #ifdef WITH_UNIVERSAL_NEWLINES ! ((PyFileObject*)self)->f_newlinetypes = newlinetypes; ! ((PyFileObject*)self)->f_skipnextlf = skipnextlf; #endif if (bzerror == BZ_STREAM_END) { ! self->size = self->pos; ! self->mode = MODE_READ_EOF; break; } else if (bzerror != BZ_OK) { --- 255,270 ---- #endif do { ! BZ2_bzRead(&bzerror, f->fp, &c, 1); ! f->pos++; *buf++ = c; } while (bzerror == BZ_OK && c != '\n' && buf != end); Py_END_ALLOW_THREADS #ifdef WITH_UNIVERSAL_NEWLINES ! f->f_newlinetypes = newlinetypes; ! f->f_skipnextlf = skipnextlf; #endif if (bzerror == BZ_STREAM_END) { ! f->size = f->pos; ! f->mode = MODE_READ_EOF; break; } else if (bzerror != BZ_OK) { *************** *** 292,299 **** size_t Util_UnivNewlineRead(int *bzerror, BZFILE *stream, ! char* buf, size_t n, BZ2FileObject *fobj) { char *dst = buf; - PyFileObject *f = (PyFileObject *)fobj; int newlinetypes, skipnextlf; --- 306,312 ---- size_t Util_UnivNewlineRead(int *bzerror, BZFILE *stream, ! char* buf, size_t n, BZ2FileObject *f) { char *dst = buf; int newlinetypes, skipnextlf; *************** *** 360,366 **** /* This is a hacked version of Python's fileobject.c:drop_readahead(). */ static void ! Util_DropReadAhead(BZ2FileObject *self) { - PyFileObject *f = (PyFileObject*)self; if (f->f_buf != NULL) { PyMem_Free(f->f_buf); --- 373,378 ---- /* This is a hacked version of Python's fileobject.c:drop_readahead(). */ static void ! Util_DropReadAhead(BZ2FileObject *f) { if (f->f_buf != NULL) { PyMem_Free(f->f_buf); *************** *** 371,379 **** /* This is a hacked version of Python's fileobject.c:readahead(). */ static int ! Util_ReadAhead(BZ2FileObject *self, int bufsize) { int chunksize; int bzerror; - PyFileObject *f = (PyFileObject*)self; if (f->f_buf != NULL) { --- 383,390 ---- /* This is a hacked version of Python's fileobject.c:readahead(). */ static int ! Util_ReadAhead(BZ2FileObject *f, int bufsize) { int chunksize; int bzerror; if (f->f_buf != NULL) { *************** *** 381,387 **** return 0; else ! Util_DropReadAhead(self); } ! if (self->mode == MODE_READ_EOF) { return -1; } --- 392,398 ---- return 0; else ! Util_DropReadAhead(f); } ! if (f->mode == MODE_READ_EOF) { return -1; } *************** *** 390,403 **** } Py_BEGIN_ALLOW_THREADS ! chunksize = Util_UnivNewlineRead(&bzerror, self->fp, f->f_buf, ! bufsize, self); Py_END_ALLOW_THREADS ! self->pos += chunksize; if (bzerror == BZ_STREAM_END) { ! self->size = self->pos; ! self->mode = MODE_READ_EOF; } else if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); ! Util_DropReadAhead(self); return -1; } --- 401,414 ---- } Py_BEGIN_ALLOW_THREADS ! chunksize = Util_UnivNewlineRead(&bzerror, f->fp, f->f_buf, ! bufsize, f); Py_END_ALLOW_THREADS ! f->pos += chunksize; if (bzerror == BZ_STREAM_END) { ! f->size = f->pos; ! f->mode = MODE_READ_EOF; } else if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); ! Util_DropReadAhead(f); return -1; } *************** *** 410,416 **** * fileobject.c:readahead_get_line_skip(). */ static PyStringObject * ! Util_ReadAheadGetLineSkip(BZ2FileObject *bf, int skip, int bufsize) { - PyFileObject *f = (PyFileObject*)bf; PyStringObject* s; char *bufptr; --- 421,426 ---- * fileobject.c:readahead_get_line_skip(). */ static PyStringObject * ! Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize) { PyStringObject* s; char *bufptr; *************** *** 419,423 **** if (f->f_buf == NULL) ! if (Util_ReadAhead(bf, bufsize) < 0) return NULL; --- 429,433 ---- if (f->f_buf == NULL) ! if (Util_ReadAhead(f, bufsize) < 0) return NULL; *************** *** 437,447 **** f->f_bufptr = bufptr; if (bufptr == f->f_bufend) ! Util_DropReadAhead(bf); } else { bufptr = f->f_bufptr; buf = f->f_buf; f->f_buf = NULL; /* Force new readahead buffer */ ! s = Util_ReadAheadGetLineSkip( ! bf, skip+len, bufsize + (bufsize>>2) ); if (s == NULL) { PyMem_Free(buf); --- 447,457 ---- f->f_bufptr = bufptr; if (bufptr == f->f_bufend) ! Util_DropReadAhead(f); } else { bufptr = f->f_bufptr; buf = f->f_buf; f->f_buf = NULL; /* Force new readahead buffer */ ! s = Util_ReadAheadGetLineSkip(f, skip+len, ! bufsize + (bufsize>>2)); if (s == NULL) { PyMem_Free(buf); *************** *** 744,747 **** --- 754,764 ---- } + PyDoc_STRVAR(BZ2File_xreadlines__doc__, + "xreadlines() -> self\n\ + \n\ + For backward compatibility. BZ2File objects now include the performance\n\ + optimizations previously implemented in the xreadlines module.\n\ + "); + PyDoc_STRVAR(BZ2File_write__doc__, "write(data) -> None\n\ *************** *** 779,783 **** } ! PyFile_SoftSpace((PyObject*)self, 0); Py_BEGIN_ALLOW_THREADS --- 796,800 ---- } ! self->f_softspace = 0; Py_BEGIN_ALLOW_THREADS *************** *** 885,889 **** } ! PyFile_SoftSpace((PyObject*)self, 0); /* Since we are releasing the global lock, the --- 902,906 ---- } ! self->f_softspace = 0; /* Since we are releasing the global lock, the *************** *** 944,948 **** int bzerror; int rewind = 0; - PyObject *func; PyObject *ret = NULL; --- 961,964 ---- *************** *** 1013,1028 **** if (rewind) { BZ2_bzReadClose(&bzerror, self->fp); - func = Py_FindMethod(PyFile_Type.tp_methods, (PyObject*)self, - "seek"); if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); goto cleanup; } ! if (!func) { ! PyErr_SetString(PyExc_RuntimeError, ! "can't find file.seek method"); ! goto cleanup; ! } ! ret = PyObject_CallFunction(func, "(i)", 0); if (!ret) goto cleanup; --- 1029,1037 ---- if (rewind) { BZ2_bzReadClose(&bzerror, self->fp); if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); goto cleanup; } ! ret = PyObject_CallMethod(self->file, "seek", "(i)", 0); if (!ret) goto cleanup; *************** *** 1030,1035 **** ret = NULL; self->pos = 0; ! self->fp = BZ2_bzReadOpen(&bzerror, ! PyFile_AsFile((PyObject*)self), 0, 0, NULL, 0); if (bzerror != BZ_OK) { --- 1039,1043 ---- ret = NULL; self->pos = 0; ! self->fp = BZ2_bzReadOpen(&bzerror, PyFile_AsFile(self->file), 0, 0, NULL, 0); if (bzerror != BZ_OK) { *************** *** 1102,1116 **** } - PyDoc_STRVAR(BZ2File_notsup__doc__, - "Operation not supported.\n\ - "); - - static PyObject * - BZ2File_notsup(BZ2FileObject *self, PyObject *args) - { - PyErr_SetString(PyExc_IOError, "operation not supported"); - return NULL; - } - PyDoc_STRVAR(BZ2File_close__doc__, "close() -> None or (perhaps) an integer\n\ --- 1110,1113 ---- *************** *** 1124,1128 **** BZ2File_close(BZ2FileObject *self) { - PyObject *file_close; PyObject *ret = NULL; int bzerror = BZ_OK; --- 1121,1124 ---- *************** *** 1140,1173 **** } self->mode = MODE_CLOSED; ! file_close = Py_FindMethod(PyFile_Type.tp_methods, (PyObject*)self, ! "close"); ! if (!file_close) { ! PyErr_SetString(PyExc_RuntimeError, ! "can't find file.close method"); ! goto cleanup; ! } ! ret = PyObject_CallObject(file_close, NULL); if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); Py_XDECREF(ret); ret = NULL; - goto cleanup; } - cleanup: RELEASE_LOCK(self); return ret; } static PyMethodDef BZ2File_methods[] = { {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, - {"truncate", (PyCFunction)BZ2File_notsup, METH_VARARGS, BZ2File_notsup__doc__}, - {"readinto", (PyCFunction)BZ2File_notsup, METH_VARARGS, BZ2File_notsup__doc__}, {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, {NULL, NULL} /* sentinel */ --- 1136,1161 ---- } self->mode = MODE_CLOSED; ! ret = PyObject_CallMethod(self->file, "close", NULL); if (bzerror != BZ_OK) { Util_CatchBZ2Error(bzerror); Py_XDECREF(ret); ret = NULL; } RELEASE_LOCK(self); return ret; } + static PyObject *BZ2File_getiter(BZ2FileObject *self); + static PyMethodDef BZ2File_methods[] = { {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, + {"xreadlines", (PyCFunction)BZ2File_getiter, METH_VARARGS, BZ2File_xreadlines__doc__}, {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, {NULL, NULL} /* sentinel */ *************** *** 1176,1179 **** --- 1164,1247 ---- /* ===================================================================== */ + /* Getters and setters of BZ2File. */ + + #ifdef WITH_UNIVERSAL_NEWLINES + /* This is a hacked version of Python's fileobject.c:get_newlines(). */ + static PyObject * + BZ2File_get_newlines(BZ2FileObject *self, void *closure) + { + switch (self->f_newlinetypes) { + case NEWLINE_UNKNOWN: + Py_INCREF(Py_None); + return Py_None; + case NEWLINE_CR: + return PyString_FromString("\r"); + case NEWLINE_LF: + return PyString_FromString("\n"); + case NEWLINE_CR|NEWLINE_LF: + return Py_BuildValue("(ss)", "\r", "\n"); + case NEWLINE_CRLF: + return PyString_FromString("\r\n"); + case NEWLINE_CR|NEWLINE_CRLF: + return Py_BuildValue("(ss)", "\r", "\r\n"); + case NEWLINE_LF|NEWLINE_CRLF: + return Py_BuildValue("(ss)", "\n", "\r\n"); + case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF: + return Py_BuildValue("(sss)", "\r", "\n", "\r\n"); + default: + PyErr_Format(PyExc_SystemError, + "Unknown newlines value 0x%x\n", + self->f_newlinetypes); + return NULL; + } + } + #endif + + static PyObject * + BZ2File_get_closed(BZ2FileObject *self, void *closure) + { + return PyInt_FromLong(self->mode == MODE_CLOSED); + } + + static PyObject * + BZ2File_get_mode(BZ2FileObject *self, void *closure) + { + return PyObject_GetAttrString(self->file, "mode"); + } + + static PyObject * + BZ2File_get_name(BZ2FileObject *self, void *closure) + { + return PyObject_GetAttrString(self->file, "name"); + } + + static PyGetSetDef BZ2File_getset[] = { + {"closed", (getter)BZ2File_get_closed, NULL, + "True if the file is closed"}, + #ifdef WITH_UNIVERSAL_NEWLINES + {"newlines", (getter)BZ2File_get_newlines, NULL, + "end-of-line convention used in this file"}, + #endif + {"mode", (getter)BZ2File_get_mode, NULL, + "file mode ('r', 'w', or 'U')"}, + {"name", (getter)BZ2File_get_name, NULL, + "file name"}, + {NULL} /* Sentinel */ + }; + + + /* ===================================================================== */ + /* Members of BZ2File_Type. */ + + #undef OFF + #define OFF(x) offsetof(BZ2FileObject, x) + + static PyMemberDef BZ2File_members[] = { + {"softspace", T_INT, OFF(f_softspace), 0, + "flag indicating that a space needs to be printed; used by print"}, + {NULL} /* Sentinel */ + }; + + /* ===================================================================== */ /* Slot definitions for BZ2File_Type. */ *************** *** 1181,1188 **** BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs) { - PyObject *file_args = NULL; static char *kwlist[] = {"filename", "mode", "buffering", "compresslevel", 0}; ! char *name = NULL; char *mode = "r"; int buffering = -1; --- 1249,1255 ---- BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"filename", "mode", "buffering", "compresslevel", 0}; ! PyObject *name; char *mode = "r"; int buffering = -1; *************** *** 1190,1200 **** int bzerror; int mode_char = 0; - int univ_newline = 0; self->size = -1; ! if (!PyArg_ParseTupleAndKeywords(args, kwargs, "et|sii:BZ2File", ! kwlist, Py_FileSystemDefaultEncoding, ! &name, &mode, &buffering, &compresslevel)) return -1; --- 1257,1265 ---- int bzerror; int mode_char = 0; self->size = -1; ! if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|sii:BZ2File", ! kwlist, &name, &mode, &buffering, &compresslevel)) return -1; *************** *** 1220,1224 **** case 'U': ! univ_newline = 1; break; --- 1285,1289 ---- case 'U': ! self->f_univ_newline = 1; break; *************** *** 1237,1247 **** } ! if (mode_char == 'r') ! mode = univ_newline ? "rbU" : "rb"; ! else ! mode = univ_newline ? "wbU" : "wb"; ! file_args = Py_BuildValue("(ssi)", name, mode, buffering); ! if (!file_args) return -1; --- 1302,1310 ---- } ! mode = (mode_char == 'r') ? "rb" : "wb"; ! self->file = PyObject_CallFunction((PyObject*)&PyFile_Type, "(Osi)", ! name, mode, buffering); ! if (self->file == NULL) return -1; *************** *** 1249,1255 **** * instead of returning */ - if (PyFile_Type.tp_init((PyObject *)self, file_args, NULL) < 0) - goto error; - #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); --- 1312,1315 ---- *************** *** 1260,1268 **** if (mode_char == 'r') self->fp = BZ2_bzReadOpen(&bzerror, ! PyFile_AsFile((PyObject*)self), 0, 0, NULL, 0); else self->fp = BZ2_bzWriteOpen(&bzerror, ! PyFile_AsFile((PyObject*)self), compresslevel, 0, 0); --- 1320,1328 ---- if (mode_char == 'r') self->fp = BZ2_bzReadOpen(&bzerror, ! PyFile_AsFile(self->file), 0, 0, NULL, 0); else self->fp = BZ2_bzWriteOpen(&bzerror, ! PyFile_AsFile(self->file), compresslevel, 0, 0); *************** *** 1274,1288 **** self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; - Py_XDECREF(file_args); - PyMem_Free(name); return 0; error: #ifdef WITH_THREAD if (self->lock) PyThread_free_lock(self->lock); #endif - Py_XDECREF(file_args); - PyMem_Free(name); return -1; } --- 1334,1345 ---- self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; return 0; error: + Py_DECREF(self->file); #ifdef WITH_THREAD if (self->lock) PyThread_free_lock(self->lock); #endif return -1; } *************** *** 1307,1311 **** } Util_DropReadAhead(self); ! ((PyObject*)self)->ob_type->tp_free((PyObject *)self); } --- 1364,1369 ---- } Util_DropReadAhead(self); ! Py_DECREF(self->file); ! self->ob_type->tp_free((PyObject *)self); } *************** *** 1400,1405 **** (iternextfunc)BZ2File_iternext, /*tp_iternext*/ BZ2File_methods, /*tp_methods*/ ! 0, /*tp_members*/ ! 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ --- 1458,1463 ---- (iternextfunc)BZ2File_iternext, /*tp_iternext*/ BZ2File_methods, /*tp_methods*/ ! BZ2File_members, /*tp_members*/ ! BZ2File_getset, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ *************** *** 1409,1413 **** (initproc)BZ2File_init, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ ! 0, /*tp_new*/ _PyObject_Del, /*tp_free*/ 0, /*tp_is_gc*/ --- 1467,1471 ---- (initproc)BZ2File_init, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ ! PyType_GenericNew, /*tp_new*/ _PyObject_Del, /*tp_free*/ 0, /*tp_is_gc*/ *************** *** 1619,1623 **** #endif BZ2_bzCompressEnd(&self->bzs); ! ((PyObject*)self)->ob_type->tp_free((PyObject *)self); } --- 1677,1681 ---- #endif BZ2_bzCompressEnd(&self->bzs); ! self->ob_type->tp_free((PyObject *)self); } *************** *** 1683,1686 **** --- 1741,1745 ---- /* Members of BZ2Decomp. */ + #undef OFF #define OFF(x) offsetof(BZ2DecompObject, x) *************** *** 1837,1841 **** Py_XDECREF(self->unused_data); BZ2_bzDecompressEnd(&self->bzs); ! ((PyObject*)self)->ob_type->tp_free((PyObject *)self); } --- 1896,1900 ---- Py_XDECREF(self->unused_data); BZ2_bzDecompressEnd(&self->bzs); ! self->ob_type->tp_free((PyObject *)self); } *************** *** 2088,2094 **** BZ2File_Type.ob_type = &PyType_Type; - BZ2File_Type.tp_base = &PyFile_Type; - BZ2File_Type.tp_new = PyFile_Type.tp_new; - BZ2Comp_Type.ob_type = &PyType_Type; BZ2Decomp_Type.ob_type = &PyType_Type; --- 2147,2150 ---- From niemeyer@users.sourceforge.net Tue Feb 11 18:46:23 2003 From: niemeyer@users.sourceforge.net (niemeyer@users.sourceforge.net) Date: Tue, 11 Feb 2003 10:46:23 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libbz2.tex,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21903/Doc/lib Modified Files: libbz2.tex Log Message: Unparenting BZ2File, as discussed in SF patch #661796. * Modules/bz2module.c (BZ2FileObject): Now the structure includes a pointer to a file object, instead of "inheriting" one. Also, some members were copied from the PyFileObject structure to avoid dealing with the internals of that structure from outside fileobject.c. (Util_GetLine,Util_DropReadAhead,Util_ReadAhead,Util_ReadAheadGetLineSkip, BZ2File_write,BZ2File_writelines,BZ2File_init,BZ2File_dealloc, BZ2Comp_dealloc,BZ2Decomp_dealloc): These functions were adapted to the change above. (BZ2File_seek,BZ2File_close): Use PyObject_CallMethod instead of getting the function attribute locally. (BZ2File_notsup): Removed, since it's not necessary anymore to overload truncate(), and readinto() with dummy functions. (BZ2File_methods): Added xreadlines() as an alias to BZ2File_getiter, and removed truncate() and readinto(). (BZ2File_get_newlines,BZ2File_get_closed,BZ2File_get_mode,BZ2File_get_name, BZ2File_getset): Implemented getters for "newlines", "mode", and "name". (BZ2File_members): Implemented "softspace" member. (BZ2File_init): Reworked to create a file instance instead of initializing itself as a file subclass. Also, pass "name" object untouched to the file constructor, and use PyObject_CallFunction instead of building the argument tuple locally. (BZ2File_Type): Set tp_new to PyType_GenericNew, tp_members to BZ2File_members, and tp_getset to BZ2File_getset. (initbz2): Do not set BZ2File_Type.tp_base nor BZ2File_Type.tp_new. * Doc/lib/libbz2.tex Do not mention that BZ2File inherits from the file type. Index: libbz2.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libbz2.tex,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** libbz2.tex 25 Nov 2002 18:51:43 -0000 1.5 --- libbz2.tex 11 Feb 2003 18:46:20 -0000 1.6 *************** *** 24,29 **** \item \class{BZ2File} class offers an optimized line iteration using the readahead algorithm borrowed from file objects; - \item \class{BZ2File} class inherits from the builtin file type - (\code{issubclass(BZ2File, file)} is \code{True}); \item Sequential (de)compression supported by \class{BZ2Compressor} and \class{BZ2Decompressor} classes; --- 24,27 ---- From rhettinger@users.sourceforge.net Tue Feb 11 19:48:23 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 11 Feb 2003 11:48:23 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv20103 Modified Files: pep-0308.txt Log Message: Several people requested that the parenthesis requirement be emphasized. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** pep-0308.txt 11 Feb 2003 15:53:20 -0000 1.12 --- pep-0308.txt 11 Feb 2003 19:48:20 -0000 1.13 *************** *** 37,42 **** (if : else: ) ! ! This is evaluated like this: - First, is evaluated. --- 37,43 ---- (if : else: ) ! Note that the enclosing parethesis are not optional. ! ! The resulting expression is evaluated like this: - First, is evaluated. From gvanrossum@users.sourceforge.net Tue Feb 11 20:05:55 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 12:05:55 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.143,1.144 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv28976 Modified Files: setup.py Log Message: Add compilation instructions for xxmodule.c. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.143 retrieving revision 1.144 diff -C2 -d -r1.143 -r1.144 *** setup.py 5 Feb 2003 15:16:17 -0000 1.143 --- setup.py 11 Feb 2003 20:05:50 -0000 1.144 *************** *** 1000,1003 **** --- 1000,1007 ---- self.extensions.append(ext) + ## # Uncomment these lines if you want to play with xxmodule.c + ## ext = Extension('xx', ['xxmodule.c']) + ## self.extensions.append(ext) + # XXX handle these, but how to detect? # *** Uncomment and edit for PIL (TkImaging) extension only: From gvanrossum@users.sourceforge.net Tue Feb 11 20:38:32 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 12:38:32 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.207,2.208 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv11994 Modified Files: typeobject.c Log Message: Fix from SF #681367: inherit tp_as_buffer. This only applies to C types -- Python types already inherited this. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.207 retrieving revision 2.208 diff -C2 -d -r2.207 -r2.208 *** typeobject.c 11 Feb 2003 17:12:46 -0000 2.207 --- typeobject.c 11 Feb 2003 20:38:29 -0000 2.208 *************** *** 2916,2919 **** --- 2916,2921 ---- if (type->tp_as_mapping == NULL) type->tp_as_mapping = base->tp_as_mapping; + if (type->tp_as_buffer == NULL) + type->tp_as_buffer = base->tp_as_buffer; } From gvanrossum@users.sourceforge.net Tue Feb 11 20:40:04 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 12:40:04 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.650,1.651 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv12567 Modified Files: NEWS Log Message: Fix from SF #681367: inherit tp_as_buffer. This only applies to C types -- Python types already inherited this. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.650 retrieving revision 1.651 diff -C2 -d -r1.650 -r1.651 *** NEWS 10 Feb 2003 10:06:18 -0000 1.650 --- NEWS 11 Feb 2003 20:39:59 -0000 1.651 *************** *** 259,262 **** --- 259,266 ---- ----- + - A C type that inherits from a base type that defines tp_as_buffer + will now inherit the tp_as_buffer pointer if it doesn't define one. + (SF #681367) + - The PyArg_Parse functions now issue a DeprecationWarning if a float argument is provided when an integer is specified (this affects the 'b', From tim_one@users.sourceforge.net Tue Feb 11 21:06:48 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 13:06:48 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.149,1.150 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv25679/python/Lib Modified Files: pickle.py Log Message: Implemented list batching in cPickle. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.149 retrieving revision 1.150 diff -C2 -d -r1.149 -r1.150 *** pickle.py 9 Feb 2003 17:19:41 -0000 1.149 --- pickle.py 11 Feb 2003 21:06:13 -0000 1.150 *************** *** 613,616 **** --- 613,617 ---- dispatch[ListType] = save_list + # Keep in synch with cPickle's BATCHSIZE. _BATCHSIZE = 1000 From tim_one@users.sourceforge.net Tue Feb 11 21:06:53 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 13:06:53 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.45,1.46 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25679/python/Lib/test Modified Files: pickletester.py Log Message: Implemented list batching in cPickle. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** pickletester.py 11 Feb 2003 16:40:16 -0000 1.45 --- pickletester.py 11 Feb 2003 21:06:15 -0000 1.46 *************** *** 673,693 **** self.produce_global_ext(0x12abcdef, pickle.EXT4) # check endianness - # XXX Temporary hack, so long as the C implementation of pickle protocol - # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests - # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests - # XXX along with the references to it in test_pickle.py. - class TempAbstractPickleTests(unittest.TestCase): - - def test_newobj_list_slots(self): - x = SlotList([1, 2, 3]) - x.foo = 42 - x.bar = "hello" - s = self.dumps(x, 2) - y = self.loads(s) - self.assertEqual(list(x), list(y)) - self.assertEqual(x.__dict__, y.__dict__) - self.assertEqual(x.foo, y.foo) - self.assertEqual(x.bar, y.bar) - def test_list_chunking(self): n = 10 # too small to chunk --- 673,676 ---- *************** *** 711,714 **** --- 694,714 ---- else: self.failUnless(num_appends >= 2) + + # XXX Temporary hack, so long as the C implementation of pickle protocol + # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests + # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests + # XXX along with the references to it in test_pickle.py. + class TempAbstractPickleTests(unittest.TestCase): + + def test_newobj_list_slots(self): + x = SlotList([1, 2, 3]) + x.foo = 42 + x.bar = "hello" + s = self.dumps(x, 2) + y = self.loads(s) + self.assertEqual(list(x), list(y)) + self.assertEqual(x.__dict__, y.__dict__) + self.assertEqual(x.foo, y.foo) + self.assertEqual(x.bar, y.bar) def test_dict_chunking(self): From tim_one@users.sourceforge.net Tue Feb 11 21:07:01 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 13:07:01 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.127,2.128 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25679/python/Modules Modified Files: cPickle.c Log Message: Implemented list batching in cPickle. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.127 retrieving revision 2.128 diff -C2 -d -r2.127 -r2.128 *** cPickle.c 5 Feb 2003 03:53:10 -0000 2.127 --- cPickle.c 11 Feb 2003 21:06:20 -0000 2.128 *************** *** 88,91 **** --- 88,96 ---- #define FALSE "I00\n" + /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements + * batch_{list, dict} pump out before doing APPENDS/SETITEMS. + */ + #define BATCHSIZE 1000 + static char MARKv = MARK; *************** *** 1615,1646 **** } static int save_list(Picklerobject *self, PyObject *args) { ! PyObject *element = 0; ! int s_len, len, i, using_appends, res = -1; char s[3]; - static char append = APPEND, appends = APPENDS; if (self->fast && !fast_save_enter(self, args)) goto finally; if (self->bin) { s[0] = EMPTY_LIST; ! s_len = 1; } else { s[0] = MARK; s[1] = LIST; ! s_len = 2; } ! if ((len = PyList_Size(args)) < 0) goto finally; ! if (self->write_func(self, s, s_len) < 0) goto finally; if (len == 0) { if (put(self, args) < 0) --- 1620,1736 ---- } + /* iter is an iterator giving items, and we batch up chunks of + * MARK item item ... item APPENDS + * opcode sequences. Calling code should have arranged to first create an + * empty list, or list-like object, for the APPENDS to operate on. + * Returns 0 on success, <0 on error. + */ + static int + batch_list(Picklerobject *self, PyObject *iter) + { + PyObject *obj; + PyObject *slice[BATCHSIZE]; + int i, n; + + static char append = APPEND; + static char appends = APPENDS; + + assert(iter != NULL); + + if (self->proto == 0) { + /* APPENDS isn't available; do one at a time. */ + for (;;) { + obj = PyIter_Next(iter); + if (obj == NULL) { + if (PyErr_Occurred()) + return -1; + break; + } + i = save(self, obj, 0); + Py_DECREF(obj); + if (i < 0) + return -1; + if (self->write_func(self, &append, 1) < 0) + return -1; + + } + return 0; + } + + /* proto > 0: write in batches of BATCHSIZE. */ + do { + /* Get next group of (no more than) BATCHSIZE elements. */ + for (n = 0; n < BATCHSIZE; ++n) { + obj = PyIter_Next(iter); + if (obj == NULL) { + if (PyErr_Occurred()) + goto BatchFailed; + break; + } + slice[n] = obj; + } + + if (n > 1) { + /* Pump out MARK, slice[0:n], APPENDS. */ + if (self->write_func(self, &MARKv, 1) < 0) + goto BatchFailed; + for (i = 0; i < n; ++i) { + if (save(self, slice[i], 0) < 0) + goto BatchFailed; + } + if (self->write_func(self, &appends, 1) < 0) + goto BatchFailed; + } + else if (n == 1) { + if (save(self, slice[0], 0) < 0) + goto BatchFailed; + if (self->write_func(self, &append, 1) < 0) + goto BatchFailed; + } + + for (i = 0; i < n; ++i) { + Py_DECREF(slice[i]); + } + }while (n == BATCHSIZE); + return 0; + + BatchFailed: + while (--n >= 0) { + Py_DECREF(slice[n]); + } + return -1; + } + static int save_list(Picklerobject *self, PyObject *args) { ! int res = -1; char s[3]; + int len; + PyObject *iter; if (self->fast && !fast_save_enter(self, args)) goto finally; + /* Create an empty list. */ if (self->bin) { s[0] = EMPTY_LIST; ! len = 1; } else { s[0] = MARK; s[1] = LIST; ! len = 2; } ! if (self->write_func(self, s, len) < 0) goto finally; ! /* Get list length, and bow out early if empty. */ ! if ((len = PyList_Size(args)) < 0) goto finally; + /* Memoize. */ if (len == 0) { if (put(self, args) < 0) *************** *** 1652,1678 **** } ! if ((using_appends = (self->bin && (len > 1)))) ! if (self->write_func(self, &MARKv, 1) < 0) ! goto finally; ! ! for (i = 0; i < len; i++) { ! if (!( element = PyList_GET_ITEM((PyListObject *)args, i))) ! goto finally; ! ! if (save(self, element, 0) < 0) ! goto finally; ! ! if (!using_appends) { ! if (self->write_func(self, &append, 1) < 0) ! goto finally; ! } ! } ! ! if (using_appends) { ! if (self->write_func(self, &appends, 1) < 0) ! goto finally; ! } ! ! res = 0; finally: --- 1742,1751 ---- } ! /* Materialize the list elements. */ ! iter = PyObject_GetIter(args); ! if (iter == NULL) ! goto finally; ! res = batch_list(self, iter); ! Py_DECREF(iter); finally: From gvanrossum@users.sourceforge.net Tue Feb 11 21:19:14 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 13:19:14 -0800 Subject: [Python-checkins] python/dist/src/Modules xxmodule.c,2.33,2.34 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv32006 Modified Files: xxmodule.c Log Message: Add Str, a subclass of str. Index: xxmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/xxmodule.c,v retrieving revision 2.33 retrieving revision 2.34 diff -C2 -d -r2.33 -r2.34 *** xxmodule.c 29 Dec 2002 17:16:49 -0000 2.33 --- xxmodule.c 11 Feb 2003 21:19:11 -0000 2.34 *************** *** 212,215 **** --- 212,268 ---- + /* ---------- */ + + static PyTypeObject Str_Type = { + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xxmodule.Str", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + &PyString_Type, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + }; + + + /* ---------- */ + + /* List of functions defined in the module */ *************** *** 253,255 **** --- 306,313 ---- Py_INCREF(ErrorObject); PyModule_AddObject(m, "error", ErrorObject); + + /* Add Str */ + if (PyType_Ready(&Str_Type) < 0) + return; + PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); } From tim_one@users.sourceforge.net Tue Feb 11 21:24:03 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 13:24:03 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv3280/nondist/peps Modified Files: pep-0307.txt Log Message: Implemented list batching in cPickle. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** pep-0307.txt 11 Feb 2003 04:50:59 -0000 1.27 --- pep-0307.txt 11 Feb 2003 21:23:59 -0000 1.28 *************** *** 719,722 **** --- 719,736 ---- + Pickling of large lists and dicts + + Protocol 1 pickles large lists and dicts "in one piece", which + minimizes pickle size, but requires that unpickling create a temp + object as large as the object being unpickled. Part of the + protocol 2 changes break large lists and dicts into pieces of no + more than 1000 elements each, so that unpickling needn't create + a temp object larger than needed to hold 1000 elements. This + isn't part of protocol 2, however: the opcodes produced are still + part of protocol 1. __reduce__ implementations that return the + optional new listitems or dictitems iterators also benefit from + this unpickling temp-space optimization. + + Copyright From gvanrossum@users.sourceforge.net Tue Feb 11 22:34:55 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 14:34:55 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv7259 Modified Files: pep-0308.txt Log Message: I just thought of something: now the syntax looks like if C:E1 else:E2, we can also allow one or more elif parts. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** pep-0308.txt 11 Feb 2003 19:48:20 -0000 1.13 --- pep-0308.txt 11 Feb 2003 22:34:52 -0000 1.14 *************** *** 49,52 **** --- 49,59 ---- result of the whole thing. + A natural extension of this syntax is to allow one or more 'elif' + parts: + + (if : elif : ... else: ) + + This will be implemented if the proposal is accepted. + Note that at most one of and is evaluated. This is called a "short-circuit expression"; it is From tim_one@users.sourceforge.net Tue Feb 11 22:43:26 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 14:43:26 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.150,1.151 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv10788/python/Lib Modified Files: pickle.py Log Message: Implemented batching for dicts in cPickle. This is after two failed attempts to merge the C list-batch and dict-batch code -- they worked, but it was a godawful mess to read. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.150 retrieving revision 1.151 diff -C2 -d -r1.150 -r1.151 *** pickle.py 11 Feb 2003 21:06:13 -0000 1.150 --- pickle.py 11 Feb 2003 22:43:23 -0000 1.151 *************** *** 613,617 **** dispatch[ListType] = save_list ! # Keep in synch with cPickle's BATCHSIZE. _BATCHSIZE = 1000 --- 613,618 ---- dispatch[ListType] = save_list ! # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets ! # out of synch, though. _BATCHSIZE = 1000 From tim_one@users.sourceforge.net Tue Feb 11 22:43:26 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 14:43:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.46,1.47 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv10788/python/Lib/test Modified Files: pickletester.py Log Message: Implemented batching for dicts in cPickle. This is after two failed attempts to merge the C list-batch and dict-batch code -- they worked, but it was a godawful mess to read. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** pickletester.py 11 Feb 2003 21:06:15 -0000 1.46 --- pickletester.py 11 Feb 2003 22:43:24 -0000 1.47 *************** *** 695,715 **** self.failUnless(num_appends >= 2) - # XXX Temporary hack, so long as the C implementation of pickle protocol - # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests - # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests - # XXX along with the references to it in test_pickle.py. - class TempAbstractPickleTests(unittest.TestCase): - - def test_newobj_list_slots(self): - x = SlotList([1, 2, 3]) - x.foo = 42 - x.bar = "hello" - s = self.dumps(x, 2) - y = self.loads(s) - self.assertEqual(list(x), list(y)) - self.assertEqual(x.__dict__, y.__dict__) - self.assertEqual(x.foo, y.foo) - self.assertEqual(x.bar, y.bar) - def test_dict_chunking(self): n = 10 # too small to chunk --- 695,698 ---- *************** *** 733,736 **** --- 716,736 ---- else: self.failUnless(num_setitems >= 2) + + # XXX Temporary hack, so long as the C implementation of pickle protocol + # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests + # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests + # XXX along with the references to it in test_pickle.py. + class TempAbstractPickleTests(unittest.TestCase): + + def test_newobj_list_slots(self): + x = SlotList([1, 2, 3]) + x.foo = 42 + x.bar = "hello" + s = self.dumps(x, 2) + y = self.loads(s) + self.assertEqual(list(x), list(y)) + self.assertEqual(x.__dict__, y.__dict__) + self.assertEqual(x.foo, y.foo) + self.assertEqual(x.bar, y.bar) class MyInt(int): From tim_one@users.sourceforge.net Tue Feb 11 22:43:27 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 14:43:27 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.128,2.129 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv10788/python/Modules Modified Files: cPickle.c Log Message: Implemented batching for dicts in cPickle. This is after two failed attempts to merge the C list-batch and dict-batch code -- they worked, but it was a godawful mess to read. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.128 retrieving revision 2.129 diff -C2 -d -r2.128 -r2.129 *** cPickle.c 11 Feb 2003 21:06:20 -0000 2.128 --- cPickle.c 11 Feb 2003 22:43:24 -0000 2.129 *************** *** 89,93 **** /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements ! * batch_{list, dict} pump out before doing APPENDS/SETITEMS. */ #define BATCHSIZE 1000 --- 89,95 ---- /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements ! * batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will ! * break if this gets out of synch with pickle.py, but it's unclear that ! * would help anything either. */ #define BATCHSIZE 1000 *************** *** 1710,1714 **** PyObject *iter; - if (self->fast && !fast_save_enter(self, args)) goto finally; --- 1712,1715 ---- *************** *** 1757,1772 **** static int save_dict(Picklerobject *self, PyObject *args) { ! PyObject *key = 0, *value = 0; ! int i, len, res = -1, using_setitems; char s[3]; ! ! static char setitem = SETITEM, setitems = SETITEMS; if (self->fast && !fast_save_enter(self, args)) goto finally; if (self->bin) { s[0] = EMPTY_DICT; --- 1758,1878 ---- + /* iter is an iterator giving (key, value) pairs, and we batch up chunks of + * MARK key value ... key value SETITEMS + * opcode sequences. Calling code should have arranged to first create an + * empty dict, or dict-like object, for the SETITEMS to operate on. + * Returns 0 on success, <0 on error. + * + * This is very much like batch_list(). The difference between saving + * elements directly, and picking apart two-tuples, is so long-winded at + * the C level, though, that attempts to combine these routines were too + * ugly to bear. + */ + static int + batch_dict(Picklerobject *self, PyObject *iter) + { + PyObject *p; + PyObject *slice[BATCHSIZE]; + int i, n; + + static char setitem = SETITEM; + static char setitems = SETITEMS; + + assert(iter != NULL); + + if (self->proto == 0) { + /* SETITEMS isn't available; do one at a time. */ + for (;;) { + p = PyIter_Next(iter); + if (p == NULL) { + if (PyErr_Occurred()) + return -1; + break; + } + if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) { + PyErr_SetString(PyExc_TypeError, "dict items " + "iterator must return 2-tuples"); + return -1; + } + i = save(self, PyTuple_GET_ITEM(p, 0), 0); + if (i >= 0) + i = save(self, PyTuple_GET_ITEM(p, 1), 0); + Py_DECREF(p); + if (i < 0) + return -1; + if (self->write_func(self, &setitem, 1) < 0) + return -1; + + } + return 0; + } + + /* proto > 0: write in batches of BATCHSIZE. */ + do { + /* Get next group of (no more than) BATCHSIZE elements. */ + for (n = 0; n < BATCHSIZE; ++n) { + p = PyIter_Next(iter); + if (p == NULL) { + if (PyErr_Occurred()) + goto BatchFailed; + break; + } + if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) { + PyErr_SetString(PyExc_TypeError, "dict items " + "iterator must return 2-tuples"); + goto BatchFailed; + } + slice[n] = p; + } + + if (n > 1) { + /* Pump out MARK, slice[0:n], SETITEMS. */ + if (self->write_func(self, &MARKv, 1) < 0) + goto BatchFailed; + for (i = 0; i < n; ++i) { + p = slice[i]; + if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0) + goto BatchFailed; + if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0) + goto BatchFailed; + } + if (self->write_func(self, &setitems, 1) < 0) + goto BatchFailed; + } + else if (n == 1) { + p = slice[0]; + if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0) + goto BatchFailed; + if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0) + goto BatchFailed; + if (self->write_func(self, &setitem, 1) < 0) + goto BatchFailed; + } + + for (i = 0; i < n; ++i) { + Py_DECREF(slice[i]); + } + }while (n == BATCHSIZE); + return 0; + + BatchFailed: + while (--n >= 0) { + Py_DECREF(slice[n]); + } + return -1; + } + static int save_dict(Picklerobject *self, PyObject *args) { ! int res = -1; char s[3]; ! int len; ! PyObject *iter; if (self->fast && !fast_save_enter(self, args)) goto finally; + /* Create an empty dict. */ if (self->bin) { s[0] = EMPTY_DICT; *************** *** 1782,1785 **** --- 1888,1892 ---- goto finally; + /* Get dict size, and bow out early if empty. */ if ((len = PyDict_Size(args)) < 0) goto finally; *************** *** 1794,1821 **** } ! if ((using_setitems = (self->bin && (PyDict_Size(args) > 1)))) ! if (self->write_func(self, &MARKv, 1) < 0) ! goto finally; ! ! i = 0; ! while (PyDict_Next(args, &i, &key, &value)) { ! if (save(self, key, 0) < 0) ! goto finally; ! ! if (save(self, value, 0) < 0) ! goto finally; ! ! if (!using_setitems) { ! if (self->write_func(self, &setitem, 1) < 0) ! goto finally; ! } ! } ! ! if (using_setitems) { ! if (self->write_func(self, &setitems, 1) < 0) ! goto finally; ! } ! ! res = 0; finally: --- 1901,1910 ---- } ! /* Materialize the dict items. */ ! iter = PyObject_CallMethod(args, "iteritems", "()"); ! if (iter == NULL) ! goto finally; ! res = batch_dict(self, iter); ! Py_DECREF(iter); finally: From nnorwitz@users.sourceforge.net Tue Feb 11 23:06:12 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 11 Feb 2003 15:06:12 -0800 Subject: [Python-checkins] python/dist/src/Objects unicodeobject.c,2.181,2.182 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv25791/Objects Modified Files: unicodeobject.c Log Message: Add more missing PyErr_NoMemory() after failled memory allocs Index: unicodeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/unicodeobject.c,v retrieving revision 2.181 retrieving revision 2.182 diff -C2 -d -r2.181 -r2.182 *** unicodeobject.c 9 Feb 2003 23:42:56 -0000 2.181 --- unicodeobject.c 11 Feb 2003 23:05:37 -0000 2.182 *************** *** 6662,6666 **** _Py_ForgetReference((PyObject *)pnew); PyObject_Del(pnew); ! return NULL; } Py_UNICODE_COPY(pnew->str, tmp->str, n+1); --- 6662,6666 ---- _Py_ForgetReference((PyObject *)pnew); PyObject_Del(pnew); ! return PyErr_NoMemory(); } Py_UNICODE_COPY(pnew->str, tmp->str, n+1); From jackjansen@users.sourceforge.net Tue Feb 11 23:15:36 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 11 Feb 2003 15:15:36 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE InstallManager.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv30069 Added Files: InstallManager.py Log Message: An install manager window for the IDE and standalone use. Unfinished. --- NEW FILE: InstallManager.py --- import W import Wapplication from Carbon import Evt import EasyDialogs import FrameWork import sys import string import os import pimp ELIPSES = '...' class InstallManager(Wapplication.Application): def __init__(self): self.preffilepath = os.path.join("Python", "Python Install Manager Prefs") Wapplication.Application.__init__(self, 'Pimp') from Carbon import AE from Carbon import AppleEvents AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication, self.quitevent) if 0: import PyConsole # With -D option (OSX command line only) keep stderr, for debugging the IDE # itself. debug_stderr = None if len(sys.argv) >= 2 and sys.argv[1] == '-D': debug_stderr = sys.stderr del sys.argv[1] PyConsole.installoutput() PyConsole.installconsole() if debug_stderr: sys.stderr = debug_stderr self.opendoc(None) self.mainloop() def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') ## openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') ## openbynameitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openbyname') FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') ## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') FrameWork.Separator(m) m = Wapplication.Menu(self.menubar, "Edit") undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") FrameWork.Separator(m) cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") FrameWork.MenuItem(m, "Clear", None, "clear") FrameWork.Separator(m) selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") m = Wapplication.Menu(self.menubar, "Package") runitem = FrameWork.MenuItem(m, "Install", "I", 'install') homepageitem = FrameWork.MenuItem(m, "Visit Homepage", None, 'homepage') self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') self.makeopenwindowsmenu() self._menustocheck = [closeitem, saveasitem, undoitem, cutitem, copyitem, pasteitem, selallitem, runitem, homepageitem] def quitevent(self, theAppleEvent, theReply): from Carbon import AE AE.AEInteractWithUser(50000000) self._quit() def ignoreevent(self, theAppleEvent, theReply): pass def opendocsevent(self, theAppleEvent, theReply): W.SetCursor('watch') import aetools parameters, args = aetools.unpackevent(theAppleEvent) docs = parameters['----'] if type(docs) <> type([]): docs = [docs] for doc in docs: fsr, a = doc.FSResolveAlias(None) path = fsr.as_pathname() path = urllib.pathname2url(path) self.opendoc(path) def opendoc(self, url): PackageBrowser(url) def getabouttext(self): return "About Python Install Manager"+ELIPSES def do_about(self, id, item, window, event): EasyDialogs.Message("Python Install Manager") def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) if filename: filename = urllib.pathname2url(filename) self.opendoc(filename) def domenu_openbyname(self, *args): url = EasyDialogs.AskString("Open URL:", ok="Open") if url: self.opendoc(url) def makeopenwindowsmenu(self): for i in range(len(self.openwindowsmenu.items)): self.openwindowsmenu.menu.DeleteMenuItem(1) self.openwindowsmenu.items = [] windows = [] self._openwindows = {} for window in self._windows.keys(): title = window.GetWTitle() if not title: title = "" windows.append((title, window)) windows.sort() for title, window in windows: shortcut = None item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) self._openwindows[item.item] = window self._openwindowscheckmark = 0 self.checkopenwindowsmenu() def domenu_openwindows(self, id, item, window, event): w = self._openwindows[item] w.ShowWindow() w.SelectWindow() def domenu_quit(self): self._quit() def domenu_save(self, *args): print "Save" def _quit(self): ## import PyConsole, PyEdit for window in self._windows.values(): try: rv = window.close() # ignore any errors while quitting except: rv = 0 # (otherwise, we can get stuck!) if rv and rv > 0: return ## try: ## PyConsole.console.writeprefs() ## PyConsole.output.writeprefs() ## PyEdit.searchengine.writeprefs() ## except: ## # Write to __stderr__ so the msg end up in Console.app and has ## # at least _some_ chance of getting read... ## # But: this is a workaround for way more serious problems with ## # the Python 2.2 Jaguar addon. ## sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") self.quitting = 1 class PimpInterface: def setuppimp(self, url): self.pimpprefs = pimp.PimpPreferences() self.pimpdb = pimp.PimpDatabase(self.pimpprefs) if not url: url = self.pimpprefs.pimpDatabase self.pimpdb.appendURL(url) def getbrowserdata(self): self.packages = self.pimpdb.list() rv = [] for pkg in self.packages: name = pkg.fullname() status, _ = pkg.installed() description = pkg.description() rv.append((status, name, description)) return rv def getstatus(self, number): pkg = self.packages[number] return pkg.installed() class PackageBrowser(PimpInterface): def __init__(self, url = None): self.ic = None self.setuppimp(url) self.setupwidgets() self.updatestatus() def setupwidgets(self): self.w = W.Window((580, 400), "Python Install Manager", minsize = (300, 200), tabbable = 0) ## self.w.divline = W.HorizontalLine((0, 20, 0, 0)) self.w.titlebar = W.TextBox((4, 4, 40, 12), 'Packages:') data = self.getbrowserdata() self.w.packagebrowser = W.MultiList((4, 20, 0, -70), data, self.listhit, cols=3) self.w.installed_l = W.TextBox((4, -66, 60, 12), 'Installed:') self.w.installed = W.TextBox((64, -66, 0, 12), '') self.w.message_l = W.TextBox((4, -48, 60, 12), 'Status:') self.w.message = W.TextBox((64, -48, 0, 12), '') self.w.homepage_button = W.Button((4, -28, 96, 18), 'View homepage', self.do_homepage) self.w.verbose_button = W.CheckBox((-204, -26, 60, 18), 'Verbose') self.w.force_button = W.CheckBox((-140, -26, 60, 18), 'Force', self.updatestatus) self.w.install_button = W.Button((-76, -28, 56, 18), 'Install', self.do_install) self.w.open() def updatestatus(self): sel = self.w.packagebrowser.getselection() if len(sel) != 1: self.w.installed.set('') self.w.message.set('') self.w.install_button.enable(0) self.w.homepage_button.enable(0) self.w.verbose_button.enable(0) self.w.force_button.enable(0) else: sel = sel[0] installed, message = self.getstatus(sel) self.w.installed.set(installed) self.w.message.set(message) self.w.install_button.enable(installed != "yes" or self.w.force_button.get()) self.w.homepage_button.enable(not not self.packages[sel].homepage()) self.w.verbose_button.enable(1) self.w.force_button.enable(1) def listhit(self, *args, **kwargs): self.updatestatus() def do_install(self): print "INSTALL" def do_homepage(self): sel = self.w.packagebrowser.getselection()[0] if not self.ic: import ic self.ic = ic.IC() self.ic.launchurl(self.packages[sel].homepage()) if __name__ == '__main__': InstallManager() From nnorwitz@users.sourceforge.net Tue Feb 11 23:05:44 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 11 Feb 2003 15:05:44 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.283,2.284 _tkinter.c,1.148,1.149 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25791/Modules Modified Files: posixmodule.c _tkinter.c Log Message: Add more missing PyErr_NoMemory() after failled memory allocs Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.283 retrieving revision 2.284 diff -C2 -d -r2.283 -r2.284 *** posixmodule.c 10 Feb 2003 03:10:43 -0000 2.283 --- posixmodule.c 11 Feb 2003 23:05:39 -0000 2.284 *************** *** 2252,2256 **** if (argvlist == NULL) { PyMem_Free(path); ! return NULL; } for (i = 0; i < argc; i++) { --- 2252,2256 ---- if (argvlist == NULL) { PyMem_Free(path); ! return PyErr_NoMemory(); } for (i = 0; i < argc; i++) { *************** *** 2481,2485 **** if (argvlist == NULL) { PyMem_Free(path); ! return NULL; } for (i = 0; i < argc; i++) { --- 2481,2485 ---- if (argvlist == NULL) { PyMem_Free(path); ! return PyErr_NoMemory(); } for (i = 0; i < argc; i++) { Index: _tkinter.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_tkinter.c,v retrieving revision 1.148 retrieving revision 1.149 diff -C2 -d -r1.148 -r1.149 *** _tkinter.c 22 Jan 2003 09:17:38 -0000 1.148 --- _tkinter.c 11 Feb 2003 23:05:40 -0000 1.149 *************** *** 2051,2055 **** data = PyMem_NEW(PythonCmd_ClientData, 1); if (!data) ! return NULL; Py_XINCREF(self); Py_XINCREF(func); --- 2051,2055 ---- data = PyMem_NEW(PythonCmd_ClientData, 1); if (!data) ! return PyErr_NoMemory(); Py_XINCREF(self); Py_XINCREF(func); From nnorwitz@users.sourceforge.net Tue Feb 11 23:19:40 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 11 Feb 2003 15:19:40 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.216.4.8,2.216.4.9 _tkinter.c,1.121.6.1,1.121.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv31828/Modules Modified Files: Tag: release22-maint posixmodule.c _tkinter.c Log Message: Backport: Add more missing PyErr_NoMemory() after failled memory allocs Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.216.4.8 retrieving revision 2.216.4.9 diff -C2 -d -r2.216.4.8 -r2.216.4.9 *** posixmodule.c 23 Aug 2002 16:27:40 -0000 2.216.4.8 --- posixmodule.c 11 Feb 2003 23:19:32 -0000 2.216.4.9 *************** *** 1511,1515 **** argvlist = PyMem_NEW(char *, argc+1); if (argvlist == NULL) ! return NULL; for (i = 0; i < argc; i++) { if (!PyArg_Parse((*getitem)(argv, i), "s", &argvlist[i])) { --- 1511,1515 ---- argvlist = PyMem_NEW(char *, argc+1); if (argvlist == NULL) ! return PyErr_NoMemory(); for (i = 0; i < argc; i++) { if (!PyArg_Parse((*getitem)(argv, i), "s", &argvlist[i])) { *************** *** 1707,1711 **** argvlist = PyMem_NEW(char *, argc+1); if (argvlist == NULL) ! return NULL; for (i = 0; i < argc; i++) { if (!PyArg_Parse((*getitem)(argv, i), "s", &argvlist[i])) { --- 1707,1711 ---- argvlist = PyMem_NEW(char *, argc+1); if (argvlist == NULL) ! return PyErr_NoMemory(); for (i = 0; i < argc; i++) { if (!PyArg_Parse((*getitem)(argv, i), "s", &argvlist[i])) { Index: _tkinter.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_tkinter.c,v retrieving revision 1.121.6.1 retrieving revision 1.121.6.2 diff -C2 -d -r1.121.6.1 -r1.121.6.2 *** _tkinter.c 28 Jan 2002 15:14:57 -0000 1.121.6.1 --- _tkinter.c 11 Feb 2003 23:19:35 -0000 1.121.6.2 *************** *** 1347,1351 **** data = PyMem_NEW(PythonCmd_ClientData, 1); if (!data) ! return NULL; Py_XINCREF(self); Py_XINCREF(func); --- 1347,1351 ---- data = PyMem_NEW(PythonCmd_ClientData, 1); if (!data) ! return PyErr_NoMemory(); Py_XINCREF(self); Py_XINCREF(func); From nnorwitz@users.sourceforge.net Tue Feb 11 23:20:09 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 11 Feb 2003 15:20:09 -0800 Subject: [Python-checkins] python/dist/src/Objects unicodeobject.c,2.124.6.19,2.124.6.20 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv31828/Objects Modified Files: Tag: release22-maint unicodeobject.c Log Message: Backport: Add more missing PyErr_NoMemory() after failled memory allocs Index: unicodeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/unicodeobject.c,v retrieving revision 2.124.6.19 retrieving revision 2.124.6.20 diff -C2 -d -r2.124.6.19 -r2.124.6.20 *** unicodeobject.c 2 Jan 2003 22:08:39 -0000 2.124.6.19 --- unicodeobject.c 11 Feb 2003 23:19:29 -0000 2.124.6.20 *************** *** 5877,5881 **** _Py_ForgetReference((PyObject *)pnew); PyObject_DEL(pnew); ! return NULL; } Py_UNICODE_COPY(pnew->str, tmp->str, n+1); --- 5877,5881 ---- _Py_ForgetReference((PyObject *)pnew); PyObject_DEL(pnew); ! return PyErr_NoMemory(); } Py_UNICODE_COPY(pnew->str, tmp->str, n+1); From jackjansen@users.sourceforge.net Tue Feb 11 22:41:02 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 11 Feb 2003 14:41:02 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv9362 Modified Files: pimp.py Log Message: Changed database format to make fields adhere to PEP 241 where applicable, and use a similar naming scheme for other fields. This has drastically changed the structure, as the PEP241 names aren't identifiers. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** pimp.py 10 Feb 2003 16:08:17 -0000 1.6 --- pimp.py 11 Feb 2003 22:40:59 -0000 1.7 *************** *** 29,32 **** --- 29,34 ---- NO_EXECUTE=0 + PIMP_VERSION="0.1" + DEFAULT_FLAVORORDER=['source', 'binary'] DEFAULT_DOWNLOADDIR='/tmp' *************** *** 142,150 **** # Test here for Pimp version, etc if not included: ! self._version = dict.get('version', '0.1') ! self._maintainer = dict.get('maintainer', '') ! self._description = dict.get('description', '') ! self._appendPackages(dict['packages']) ! others = dict.get('include', []) for url in others: self.appendURL(url, included=1) --- 144,155 ---- # Test here for Pimp version, etc if not included: ! self._version = dict.get('Version', '0.1') ! if self._version != PIMP_VERSION: ! sys.stderr.write("Warning: database version %s does not match %s\n" ! % (self._version, PIMP_VERSION)) ! self._maintainer = dict.get('Maintainer', '') ! self._description = dict.get('Description', '') ! self._appendPackages(dict['Packages']) ! others = dict.get('Include', []) for url in others: self.appendURL(url, included=1) *************** *** 156,160 **** for p in packages: ! pkg = PimpPackage(self, **dict(p)) self._packages.append(pkg) --- 161,165 ---- for p in packages: ! pkg = PimpPackage(self, dict(p)) self._packages.append(pkg) *************** *** 169,173 **** rv = [] for pkg in self._packages: ! rv.append(_fmtpackagename(pkg)) return rv --- 174,178 ---- rv = [] for pkg in self._packages: ! rv.append(pkg.fullname()) return rv *************** *** 182,189 **** packages.append(pkg.dump()) dict = { ! 'version': self._version, ! 'maintainer': self._maintainer, ! 'description': self._description, ! 'packages': packages } plist = plistlib.Plist(**dict) --- 187,194 ---- packages.append(pkg.dump()) dict = { ! 'Version': self._version, ! 'Maintainer': self._maintainer, ! 'Description': self._description, ! 'Packages': packages } plist = plistlib.Plist(**dict) *************** *** 216,284 **** flavor = None else: ! name = ident['name'] ! version = ident.get('version') ! flavor = ident.get('flavor') found = None for p in self._packages: ! if name == p.name and \ ! (not version or version == p.version) and \ ! (not flavor or flavor == p.flavor): if not found or found < p: found = p return found class PimpPackage: """Class representing a single package.""" ! def __init__(self, db, name, ! version=None, ! flavor=None, ! description=None, ! longdesc=None, ! downloadURL=None, ! installTest=None, ! prerequisites=None, ! preInstall=None, ! postInstall=None, ! MD5Sum=None): self._db = db ! self.name = name ! self.version = version ! self.flavor = flavor ! self.description = description ! self.longdesc = longdesc ! self.downloadURL = downloadURL ! self._installTest = installTest ! self._prerequisites = prerequisites ! self._preInstall = preInstall ! self._postInstall = postInstall ! self._MD5Sum = MD5Sum def dump(self): """Return a dict object containing the information on the package.""" ! dict = { ! 'name': self.name, ! } ! if self.version: ! dict['version'] = self.version ! if self.flavor: ! dict['flavor'] = self.flavor ! if self.description: ! dict['description'] = self.description ! if self.longdesc: ! dict['longdesc'] = self.longdesc ! if self.downloadURL: ! dict['downloadURL'] = self.downloadURL ! if self._installTest: ! dict['installTest'] = self._installTest ! if self._prerequisites: ! dict['prerequisites'] = self._prerequisites ! if self._preInstall: ! dict['preInstall'] = self._preInstall ! if self._postInstall: ! dict['postInstall'] = self._postInstall ! if self._MD5Sum: ! dict['MD5Sum'] = self._MD5Sum ! return dict def __cmp__(self, other): --- 221,291 ---- flavor = None else: ! name = ident['Name'] ! version = ident.get('Version') ! flavor = ident.get('Flavor') found = None for p in self._packages: ! if name == p.name() and \ ! (not version or version == p.version()) and \ ! (not flavor or flavor == p.flavor()): if not found or found < p: found = p return found + ALLOWED_KEYS = [ + "Name", + "Version", + "Flavor", + "Description", + "Home-page", + "Download-URL", + "Install-test", + "Install-command", + "Pre-install-command", + "Post-install-command", + "Prerequisites", + "MD5Sum" + ] + class PimpPackage: """Class representing a single package.""" ! def __init__(self, db, dict): self._db = db ! name = dict["Name"] ! for k in dict.keys(): ! if not k in ALLOWED_KEYS: ! sys.stderr.write("Warning: %s: unknown key %s\n" % (name, k)) ! self._dict = dict ! ! def __getitem__(self, key): ! return self._dict[key] + def name(self): return self._dict['Name'] + def version(self): return self._dict['Version'] + def flavor(self): return self._dict['Flavor'] + def description(self): return self._dict['Description'] + def homepage(self): return self._dict['Home-page'] + def downloadURL(self): return self._dict['Download-URL'] + + def fullname(self): + """Return the full name "name-version-flavor" of a package. + + If the package is a pseudo-package, something that cannot be + installed through pimp, return the name in (parentheses).""" + + rv = self._dict['Name'] + if self._dict.has_key('Version'): + rv = rv + '-%s' % self._dict['Version'] + if self._dict.has_key('Flavor'): + rv = rv + '-%s' % self._dict['Flavor'] + if not self._dict.get('Download-URL'): + # Pseudo-package, show in parentheses + rv = '(%s)' % rv + return rv + def dump(self): """Return a dict object containing the information on the package.""" ! return self._dict def __cmp__(self, other): *************** *** 287,295 **** if not isinstance(other, PimpPackage): return cmp(id(self), id(other)) ! if self.name != other.name: ! return cmp(self.name, other.name) ! if self.version != other.version: ! return -cmp(self.version, other.version) ! return self._db.preferences.compareFlavors(self.flavor, other.flavor) def installed(self): --- 294,302 ---- if not isinstance(other, PimpPackage): return cmp(id(self), id(other)) ! if self.name() != other.name(): ! return cmp(self.name(), other.name()) ! if self.version() != other.version(): ! return -cmp(self.version(), other.version()) ! return self._db.preferences.compareFlavors(self.flavor(), other.flavor()) def installed(self): *************** *** 308,312 **** "sys": sys, } ! installTest = self._installTest.strip() + '\n' try: exec installTest in namespace --- 315,319 ---- "sys": sys, } ! installTest = self._dict['Install-test'].strip() + '\n' try: exec installTest in namespace *************** *** 320,324 **** return "bad", str(arg) except: - print 'TEST:', repr(self._installTest) return "bad", "Package install test got exception" return "yes", "" --- 327,330 ---- *************** *** 334,351 **** rv = [] ! if not self.downloadURL: return [(None, "This package needs to be installed manually")] ! if not self._prerequisites: return [] ! for item in self._prerequisites: if type(item) == str: pkg = None descr = str(item) else: ! pkg = self._db.find(item) if not pkg: ! descr = "Requires unknown %s"%_fmtpackagename(item) else: ! descr = pkg.description rv.append((pkg, descr)) return rv --- 340,362 ---- rv = [] ! if not self._dict['Download-URL']: return [(None, "This package needs to be installed manually")] ! if not self._dict['Prerequisites']: return [] ! for item in self._dict['Prerequisites']: if type(item) == str: pkg = None descr = str(item) else: ! name = item['Name'] ! if item.has_key('Version'): ! name = name + '-' + item['Version'] ! if item.has_key('Flavor'): ! name = name + '-' + item['Flavor'] ! pkg = self._db.find(name) if not pkg: ! descr = "Requires unknown %s"%name else: ! descr = pkg.description() rv.append((pkg, descr)) return rv *************** *** 381,385 **** """ ! scheme, loc, path, query, frag = urlparse.urlsplit(self.downloadURL) path = urllib.url2pathname(path) filename = os.path.split(path)[1] --- 392,396 ---- """ ! scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL']) path = urllib.url2pathname(path) filename = os.path.split(path)[1] *************** *** 391,395 **** "curl", "--output", self.archiveFilename, ! self.downloadURL): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: --- 402,406 ---- "curl", "--output", self.archiveFilename, ! self._dict['Download-URL']): return "download command failed" if not os.path.exists(self.archiveFilename) and not NO_EXECUTE: *************** *** 403,412 **** if not os.path.exists(self.archiveFilename): return 0 ! if not self._MD5Sum: ! sys.stderr.write("Warning: no MD5Sum for %s\n" % _fmtpackagename(self)) return 1 data = open(self.archiveFilename, 'rb').read() checksum = md5.new(data).hexdigest() ! return checksum == self._MD5Sum def unpackSinglePackage(self, output=None): --- 414,423 ---- if not os.path.exists(self.archiveFilename): return 0 ! if not self._dict['MD5Sum']: ! sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 data = open(self.archiveFilename, 'rb').read() checksum = md5.new(data).hexdigest() ! return checksum == self._dict['MD5Sum'] def unpackSinglePackage(self, output=None): *************** *** 434,455 **** will receive a log of what happened.""" ! if not self.downloadURL: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = self.downloadSinglePackage(output) if msg: ! return "download %s: %s" % (_fmtpackagename(self), msg) msg = self.unpackSinglePackage(output) if msg: ! return "unpack %s: %s" % (_fmtpackagename(self), msg) ! if self._preInstall: ! if self._cmd(output, self._buildDirname, self._preInstall): return "pre-install %s: running \"%s\" failed" % \ ! (_fmtpackagename(self), self._preInstall) ! if self._cmd(output, self._buildDirname, sys.executable, "setup.py install"): ! return "install %s: running \"setup.py install\" failed" % _fmtpackagename(self) ! if self._postInstall: ! if self._cmd(output, self._buildDirname, self._postInstall): return "post-install %s: running \"%s\" failed" % \ ! (_fmtpackagename(self), self._postInstall) return None --- 445,469 ---- will receive a log of what happened.""" ! if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = self.downloadSinglePackage(output) if msg: ! return "download %s: %s" % (self.fullname(), msg) msg = self.unpackSinglePackage(output) if msg: ! return "unpack %s: %s" % (self.fullname(), msg) ! if self._dict.has_key('Pre-install-command'): ! if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ ! (self.fullname(), self._dict['Pre-install-command']) ! installcmd = self._dict.get('Install-command') ! if not installcmd: ! installcmd = '"%s" setup.py install' % sys.executable ! if self._cmd(output, self._buildDirname, installcmd): ! return "install %s: running \"%s\" failed" % self.fullname() ! if self._dict.has_key('Post-install-command'): ! if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): return "post-install %s: running \"%s\" failed" % \ ! (self.fullname(), self._dict['Post-install-command']) return None *************** *** 525,545 **** - def _fmtpackagename(dict): - """Return the full name "name-version-flavor" of a package. - - If the package is a pseudo-package, something that cannot be - installed through pimp, return the name in (parentheses).""" - - if isinstance(dict, PimpPackage): - dict = dict.dump() - rv = dict['name'] - if dict.has_key('version'): - rv = rv + '-%s' % dict['version'] - if dict.has_key('flavor'): - rv = rv + '-%s' % dict['flavor'] - if not dict.get('downloadURL'): - # Pseudo-package, show in parentheses - rv = '(%s)' % rv - return rv def _run(mode, verbose, force, args): --- 539,542 ---- *************** *** 561,572 **** pkg = db.find(pkgname) if pkg: ! description = pkg.description ! pkgname = _fmtpackagename(pkg) else: description = 'Error: no such package' print "%-20.20s\t%s" % (pkgname, description) if verbose: ! print "\tHome page:\t", pkg.longdesc ! print "\tDownload URL:\t", pkg.downloadURL elif mode =='status': if not args: --- 558,569 ---- pkg = db.find(pkgname) if pkg: ! description = pkg.description() ! pkgname = pkg.fullname() else: description = 'Error: no such package' print "%-20.20s\t%s" % (pkgname, description) if verbose: ! print "\tHome page:\t", pkg.homepage() ! print "\tDownload URL:\t", pkg.downloadURL() elif mode =='status': if not args: *************** *** 578,582 **** if pkg: status, msg = pkg.installed() ! pkgname = _fmtpackagename(pkg) else: status = 'error' --- 575,579 ---- if pkg: status, msg = pkg.installed() ! pkgname = pkg.fullname() else: status = 'error' *************** *** 589,593 **** pkg = '' else: ! pkg = _fmtpackagename(pkg) print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg) elif mode == 'install': --- 586,590 ---- pkg = '' else: ! pkg = pkg.fullname() print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg) elif mode == 'install': From rhettinger@users.sourceforge.net Wed Feb 12 01:38:28 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 11 Feb 2003 17:38:28 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv18838 Modified Files: pep-0308.txt Log Message: * Add Holger's new, well-received idea. * Fixed typo. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** pep-0308.txt 11 Feb 2003 22:34:52 -0000 1.14 --- pep-0308.txt 12 Feb 2003 01:38:25 -0000 1.15 *************** *** 37,41 **** (if : else: ) ! Note that the enclosing parethesis are not optional. The resulting expression is evaluated like this: --- 37,41 ---- (if : else: ) ! Note that the enclosing parentheses are not optional. The resulting expression is evaluated like this: *************** *** 81,84 **** --- 81,97 ---- is long, it's easy to miss the conditional while skimming. + + --- + + Holger Krekel proposed a new, minimally invasive variant: + + and else + + The concept behind it is that a nearly complete ternary operator + already exists with and/or and this proposal is the least invasive + change that makes it complete. Many respondants on the + newsgroup found this to be the most pleasing alternative. + However, a couple of respondants were able to post examples + that were mentally difficult to parse. --- From montanaro@users.sourceforge.net Wed Feb 12 02:43:16 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 18:43:16 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv7958 Modified Files: csv.py Log Message: suppress blank returns Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** csv.py 11 Feb 2003 14:13:25 -0000 1.30 --- csv.py 12 Feb 2003 02:43:14 -0000 1.31 *************** *** 71,74 **** --- 71,79 ---- def next(self): row = self.reader.next() + # unlike the basic reader, we prefer not to return blanks, + # because we will typically wind up with a dict full of None + # values + while row == []: + row = self.reader.next() d = dict(zip(self.fieldnames, row)) lf = len(self.fieldnames) From montanaro@users.sourceforge.net Wed Feb 12 02:44:45 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 11 Feb 2003 18:44:45 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv8545 Modified Files: test_csv.py Log Message: add test case for DictReader encountering empty lists from csv.reader. fix test_write to avoid StringIO's list append behavior. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** test_csv.py 11 Feb 2003 14:51:41 -0000 1.31 --- test_csv.py 12 Feb 2003 02:44:42 -0000 1.32 *************** *** 408,411 **** --- 408,420 ---- "6": 'DEFAULT'}) + def test_read_with_blanks(self): + reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n", + "1,2,abc,4,5,6\r\n"], + fieldnames="1 2 3 4 5 6".split()) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + self.assertEqual(reader.next(), {"1": '1', "2": '2', "3": 'abc', + "4": '4', "5": '5', "6": '6'}) + class TestArrayWrites(unittest.TestCase): def test_int_write(self): *************** *** 503,507 **** lastrc = sys.gettotalrefcount() rows = [[1,2,3]]*5 ! s = StringIO() for i in xrange(20): gc.collect() --- 512,519 ---- lastrc = sys.gettotalrefcount() rows = [[1,2,3]]*5 ! class NUL: ! def write(s, *args): ! pass ! s = NUL() for i in xrange(20): gc.collect() From gvanrossum@users.sourceforge.net Wed Feb 12 03:30:36 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:30:36 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.115,2.116 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv26151/Objects Modified Files: abstract.c Log Message: SF #532767: isinstance(x, X) should work when x is a proxy for an X instance, as long as x.__class__ is X or a subclass thereof. Did a little cleanup of PyObject_IsInstance() too. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.115 retrieving revision 2.116 diff -C2 -d -r2.115 -r2.116 *** abstract.c 10 Feb 2003 16:05:43 -0000 2.115 --- abstract.c 12 Feb 2003 03:30:34 -0000 2.116 *************** *** 2041,2044 **** --- 2041,2050 ---- int retval = 0; + if (__class__ == NULL) { + __class__ = PyString_FromString("__class__"); + if (__class__ == NULL) + return -1; + } + if (PyClass_Check(cls) && PyInstance_Check(inst)) { PyObject *inclass = *************** *** 2048,2051 **** --- 2054,2070 ---- else if (PyType_Check(cls)) { retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); + if (retval == 0) { + PyObject *c = PyObject_GetAttr(inst, __class__); + if (c == NULL) { + PyErr_Clear(); + } + else { + if (c != inst->ob_type && PyType_Check(c)) + retval = PyType_IsSubtype( + (PyTypeObject *)c, + (PyTypeObject *)cls); + Py_DECREF(c); + } + } } else if (PyTuple_Check(cls)) { *************** *** 2061,2065 **** break; } - return retval; } else { --- 2080,2083 ---- *************** *** 2068,2076 **** " or tuple of classes and types")) return -1; - if (__class__ == NULL) { - __class__ = PyString_FromString("__class__"); - if (__class__ == NULL) - return -1; - } icls = PyObject_GetAttr(inst, __class__); if (icls == NULL) { --- 2086,2089 ---- From gvanrossum@users.sourceforge.net Wed Feb 12 03:30:37 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:30:37 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.181,1.182 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv26151/Lib/test Modified Files: test_descr.py Log Message: SF #532767: isinstance(x, X) should work when x is a proxy for an X instance, as long as x.__class__ is X or a subclass thereof. Did a little cleanup of PyObject_IsInstance() too. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.181 retrieving revision 1.182 diff -C2 -d -r1.181 -r1.182 *** test_descr.py 11 Feb 2003 18:44:42 -0000 1.181 --- test_descr.py 12 Feb 2003 03:30:34 -0000 1.182 *************** *** 3736,3740 **** def meth_class_get(): # Full coverage of descrobject.c::classmethod_get() ! if verbose: print "Testing __get__ method of METH_CLASS C methods..." # Baseline arg = [1, 2, 3] --- 3736,3741 ---- def meth_class_get(): # Full coverage of descrobject.c::classmethod_get() ! if verbose: ! print "Testing __get__ method of METH_CLASS C methods..." # Baseline arg = [1, 2, 3] *************** *** 3773,3776 **** --- 3774,3803 ---- raise TestFailed, "shouldn't have allowed descr.__get__(None, int)" + def isinst_isclass(): + if verbose: + print "Testing proxy isinstance() and isclass()..." + class Proxy(object): + def __init__(self, obj): + self.__obj = obj + def __getattribute__(self, name): + if name.startswith("_Proxy__"): + return object.__getattribute__(self, name) + else: + return getattr(self.__obj, name) + # Test with a classic class + class C: + pass + a = C() + pa = Proxy(a) + verify(isinstance(a, C)) # Baseline + verify(isinstance(pa, C)) # Test + # Test with a new-style class + class C(object): + pass + a = C() + pa = Proxy(a) + verify(isinstance(a, C)) # Baseline + verify(isinstance(pa, C)) # Test + def test_main(): *************** *** 3860,3863 **** --- 3887,3891 ---- dict_type_with_metaclass() meth_class_get() + isinst_isclass() if verbose: print "All OK" From gvanrossum@users.sourceforge.net Wed Feb 12 03:33:01 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:33:01 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.651,1.652 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv27194 Modified Files: NEWS Log Message: SF #532767: isinstance(x, X) should work when x is a proxy for an X instance, as long as x.__class__ is X or a subclass thereof. Did a little cleanup of PyObject_IsInstance() too. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.651 retrieving revision 1.652 diff -C2 -d -r1.651 -r1.652 *** NEWS 11 Feb 2003 20:39:59 -0000 1.651 --- NEWS 12 Feb 2003 03:32:58 -0000 1.652 *************** *** 13,16 **** --- 13,21 ---- ----------------- + - isinstance(x, X): if X is a new-style class, this is now equivalent + to issubclass(type(x), X) or issubclass(x.__class__, X). Previously + only type(x) was tested. (For classic classes this was already the + case.) + - compile(), eval() and the exec statement now fully support source code passed as unicode strings. From gvanrossum@users.sourceforge.net Wed Feb 12 03:36:08 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:36:08 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.116,2.117 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv28205 Modified Files: abstract.c Log Message: Add missing cast in previous fix. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.116 retrieving revision 2.117 diff -C2 -d -r2.116 -r2.117 *** abstract.c 12 Feb 2003 03:30:34 -0000 2.116 --- abstract.c 12 Feb 2003 03:36:05 -0000 2.117 *************** *** 2060,2064 **** } else { ! if (c != inst->ob_type && PyType_Check(c)) retval = PyType_IsSubtype( (PyTypeObject *)c, --- 2060,2065 ---- } else { ! if (c != (PyObject *)(inst->ob_type) && ! PyType_Check(c)) retval = PyType_IsSubtype( (PyTypeObject *)c, From gvanrossum@users.sourceforge.net Wed Feb 12 03:58:40 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:58:40 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.652,1.653 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv1947/Misc Modified Files: NEWS Log Message: Implement another useful feature for proxies: in super(X, x), x may now be a proxy for an X instance, as long as issubclass(x.__class__, X). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.652 retrieving revision 1.653 diff -C2 -d -r1.652 -r1.653 *** NEWS 12 Feb 2003 03:32:58 -0000 1.652 --- NEWS 12 Feb 2003 03:58:33 -0000 1.653 *************** *** 13,16 **** --- 13,19 ---- ----------------- + - super(X, x): x may now be a proxy for an X instance, i.e. + issubclass(x.__class__, X) but not issubclass(type(x), X). + - isinstance(x, X): if X is a new-style class, this is now equivalent to issubclass(type(x), X) or issubclass(x.__class__, X). Previously From gvanrossum@users.sourceforge.net Wed Feb 12 03:58:41 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:58:41 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.182,1.183 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv1947/Lib/test Modified Files: test_descr.py Log Message: Implement another useful feature for proxies: in super(X, x), x may now be a proxy for an X instance, as long as issubclass(x.__class__, X). Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.182 retrieving revision 1.183 diff -C2 -d -r1.182 -r1.183 *** test_descr.py 12 Feb 2003 03:30:34 -0000 1.182 --- test_descr.py 12 Feb 2003 03:58:38 -0000 1.183 *************** *** 3792,3795 **** --- 3792,3802 ---- verify(isinstance(a, C)) # Baseline verify(isinstance(pa, C)) # Test + # Test with a classic subclass + class D(C): + pass + a = D() + pa = Proxy(a) + verify(isinstance(a, C)) # Baseline + verify(isinstance(pa, C)) # Test # Test with a new-style class class C(object): *************** *** 3799,3802 **** --- 3806,3840 ---- verify(isinstance(a, C)) # Baseline verify(isinstance(pa, C)) # Test + # Test with a new-style subclass + class D(C): + pass + a = D() + pa = Proxy(a) + verify(isinstance(a, C)) # Baseline + verify(isinstance(pa, C)) # Test + + def proxysuper(): + if verbose: + print "Testing super() for a proxy object..." + class Proxy(object): + def __init__(self, obj): + self.__obj = obj + def __getattribute__(self, name): + if name.startswith("_Proxy__"): + return object.__getattribute__(self, name) + else: + return getattr(self.__obj, name) + + class B(object): + def f(self): + return "B.f" + + class C(B): + def f(self): + return super(C, self).f() + "->C.f" + + obj = C() + p = Proxy(obj) + vereq(C.__dict__["f"](p), "B.f->C.f") *************** *** 3888,3891 **** --- 3926,3930 ---- meth_class_get() isinst_isclass() + proxysuper() if verbose: print "All OK" From gvanrossum@users.sourceforge.net Wed Feb 12 03:58:40 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 11 Feb 2003 19:58:40 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.208,2.209 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv1947/Objects Modified Files: typeobject.c Log Message: Implement another useful feature for proxies: in super(X, x), x may now be a proxy for an X instance, as long as issubclass(x.__class__, X). Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.208 retrieving revision 2.209 diff -C2 -d -r2.208 -r2.209 *** typeobject.c 11 Feb 2003 20:38:29 -0000 2.208 --- typeobject.c 12 Feb 2003 03:58:38 -0000 2.209 *************** *** 5026,5029 **** --- 5026,5030 ---- PyTypeObject *type; PyObject *obj; + PyTypeObject *obj_type; } superobject; *************** *** 5033,5036 **** --- 5034,5039 ---- {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, "the instance invoking super(); may be None"}, + {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, + "the type of the the instance invoking super(); may be None"}, {0} }; *************** *** 5044,5047 **** --- 5047,5051 ---- Py_XDECREF(su->obj); Py_XDECREF(su->type); + Py_XDECREF(su->obj_type); self->ob_type->tp_free(self); } *************** *** 5052,5060 **** superobject *su = (superobject *)self; ! if (su->obj) return PyString_FromFormat( ", <%s object>>", su->type ? su->type->tp_name : "NULL", ! su->obj->ob_type->tp_name); else return PyString_FromFormat( --- 5056,5064 ---- superobject *su = (superobject *)self; ! if (su->obj_type) return PyString_FromFormat( ", <%s object>>", su->type ? su->type->tp_name : "NULL", ! su->obj_type->tp_name); else return PyString_FromFormat( *************** *** 5068,5072 **** superobject *su = (superobject *)self; ! if (su->obj != NULL) { PyObject *mro, *res, *tmp, *dict; PyTypeObject *starttype; --- 5072,5076 ---- superobject *su = (superobject *)self; ! if (su->obj_type != NULL) { PyObject *mro, *res, *tmp, *dict; PyTypeObject *starttype; *************** *** 5074,5078 **** int i, n; ! starttype = su->obj->ob_type; mro = starttype->tp_mro; --- 5078,5082 ---- int i, n; ! starttype = su->obj_type; mro = starttype->tp_mro; *************** *** 5087,5090 **** --- 5091,5095 ---- break; } + #if 0 if (i >= n && PyType_Check(su->obj)) { starttype = (PyTypeObject *)(su->obj); *************** *** 5102,5105 **** --- 5107,5111 ---- } } + #endif i++; res = NULL; *************** *** 5129,5145 **** } ! static int supercheck(PyTypeObject *type, PyObject *obj) { ! if (!PyType_IsSubtype(obj->ob_type, type) && ! !(PyType_Check(obj) && ! PyType_IsSubtype((PyTypeObject *)obj, type))) { ! PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); ! return -1; ! } ! else ! return 0; } --- 5135,5203 ---- } ! static PyTypeObject * supercheck(PyTypeObject *type, PyObject *obj) { ! /* Check that a super() call makes sense. Return a type object. ! ! obj can be a new-style class, or an instance of one: ! ! - If it is a class, it must be a subclass of 'type'. This case is ! used for class methods; the return value is obj. ! ! - If it is an instance, it must be an instance of 'type'. This is ! the normal case; the return value is obj.__class__. ! ! But... when obj is an instance, we want to allow for the case where ! obj->ob_type is not a subclass of type, but obj.__class__ is! ! This will allow using super() with a proxy for obj. ! */ ! ! if (PyType_Check(obj)) { ! /* It's a new-style class */ ! if (PyType_IsSubtype((PyTypeObject *)obj, type)) { ! Py_INCREF(obj); ! return (PyTypeObject *)obj; ! } ! else ! goto fail; ! } ! else if (PyType_IsSubtype(obj->ob_type, type)) { ! Py_INCREF(obj->ob_type); ! return obj->ob_type; ! } ! else { ! /* Try the slow way */ ! static PyObject *class_str = NULL; ! PyObject *class_attr; ! ! if (class_str == NULL) { ! class_str = PyString_FromString("__class__"); ! if (class_str == NULL) ! return NULL; ! } ! ! class_attr = PyObject_GetAttr(obj, class_str); ! ! if (class_attr != NULL && ! PyType_Check(class_attr) && ! (PyTypeObject *)class_attr != obj->ob_type) ! { ! int ok = PyType_IsSubtype( ! (PyTypeObject *)class_attr, type); ! if (ok) ! return (PyTypeObject *)class_attr; ! } ! ! if (class_attr == NULL) ! PyErr_Clear(); ! else ! Py_DECREF(class_attr); ! } ! ! fail: ! PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); ! return NULL; } *************** *** 5162,5166 **** else { /* Inline the common case */ ! if (supercheck(su->type, obj) < 0) return NULL; new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, --- 5220,5225 ---- else { /* Inline the common case */ ! PyTypeObject *obj_type = supercheck(su->type, obj); ! if (obj_type == NULL) return NULL; new = (superobject *)PySuper_Type.tp_new(&PySuper_Type, *************** *** 5172,5175 **** --- 5231,5235 ---- new->type = su->type; new->obj = obj; + new->obj_type = obj_type; return (PyObject *)new; } *************** *** 5182,5185 **** --- 5242,5246 ---- PyTypeObject *type; PyObject *obj = NULL; + PyTypeObject *obj_type = NULL; if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj)) *************** *** 5187,5196 **** if (obj == Py_None) obj = NULL; ! if (obj != NULL && supercheck(type, obj) < 0) ! return -1; Py_INCREF(type); - Py_XINCREF(obj); su->type = type; su->obj = obj; return 0; } --- 5248,5261 ---- if (obj == Py_None) obj = NULL; ! if (obj != NULL) { ! obj_type = supercheck(type, obj); ! if (obj_type == NULL) ! return -1; ! Py_INCREF(obj); ! } Py_INCREF(type); su->type = type; su->obj = obj; + su->obj_type = obj_type; return 0; } *************** *** 5220,5223 **** --- 5285,5289 ---- VISIT(su->obj); VISIT(su->type); + VISIT(su->obj_type); #undef VISIT From rhettinger@users.sourceforge.net Wed Feb 12 04:09:16 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 11 Feb 2003 20:09:16 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv5555 Modified Files: pep-0308.txt Log Message: Chris Tismer's proposal is also being well received. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** pep-0308.txt 12 Feb 2003 01:38:25 -0000 1.15 --- pep-0308.txt 12 Feb 2003 04:09:14 -0000 1.16 *************** *** 95,98 **** --- 95,102 ---- that were mentally difficult to parse. + Christian Tismer proposed a variant of the same idea: + + then else + --- From tim_one@users.sourceforge.net Wed Feb 12 05:29:01 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 11 Feb 2003 21:29:01 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.129,2.130 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29447/Modules Modified Files: cPickle.c Log Message: Minor cleanup of new batch-list/dict code. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.129 retrieving revision 2.130 diff -C2 -d -r2.129 -r2.130 *** cPickle.c 11 Feb 2003 22:43:24 -0000 2.129 --- cPickle.c 12 Feb 2003 05:28:58 -0000 2.130 *************** *** 1655,1659 **** if (self->write_func(self, &append, 1) < 0) return -1; - } return 0; --- 1655,1658 ---- *************** *** 1694,1698 **** Py_DECREF(slice[i]); } ! }while (n == BATCHSIZE); return 0; --- 1693,1697 ---- Py_DECREF(slice[i]); } ! } while (n == BATCHSIZE); return 0; *************** *** 1735,1745 **** /* Memoize. */ if (len == 0) { ! if (put(self, args) < 0) ! goto finally; ! } ! else { ! if (put2(self, args) < 0) ! goto finally; } /* Materialize the list elements. */ --- 1734,1743 ---- /* Memoize. */ if (len == 0) { ! if (put(self, args) >= 0) ! res = 0; ! goto finally; } + if (put2(self, args) < 0) + goto finally; /* Materialize the list elements. */ *************** *** 1803,1807 **** if (self->write_func(self, &setitem, 1) < 0) return -1; - } return 0; --- 1801,1804 ---- *************** *** 1853,1857 **** Py_DECREF(slice[i]); } ! }while (n == BATCHSIZE); return 0; --- 1850,1854 ---- Py_DECREF(slice[i]); } ! } while (n == BATCHSIZE); return 0; *************** *** 1893,1903 **** if (len == 0) { ! if (put(self, args) < 0) ! goto finally; ! } ! else { ! if (put2(self, args) < 0) ! goto finally; } /* Materialize the dict items. */ --- 1890,1899 ---- if (len == 0) { ! if (put(self, args) >= 0) ! res = 0; ! goto finally; } + if (put2(self, args) < 0) + goto finally; /* Materialize the dict items. */ From jackjansen@users.sourceforge.net Wed Feb 12 09:58:36 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 01:58:36 -0800 Subject: [Python-checkins] python/dist/src/Doc/mac libaepack.tex,1.1,1.2 libmac.tex,1.22,1.23 libmacfs.tex,1.28,1.29 libmacos.tex,1.18,1.19 libmacostools.tex,1.15,1.16 libmacui.tex,1.17,1.18 mac.tex,1.9,1.10 toolbox.tex,1.6,1.7 undoc.tex,1.8,1.9 using.tex,1.5,1.6 libctb.tex,1.18,NONE libmacspeech.tex,1.13,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Doc/mac In directory sc8-pr-cvs1:/tmp/cvs-serv5862 Modified Files: libaepack.tex libmac.tex libmacfs.tex libmacos.tex libmacostools.tex libmacui.tex mac.tex toolbox.tex undoc.tex using.tex Removed Files: libctb.tex libmacspeech.tex Log Message: Updated the Mac documentation to the current state of affairs. Index: libaepack.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libaepack.tex,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** libaepack.tex 14 Oct 2000 05:06:24 -0000 1.1 --- libaepack.tex 12 Feb 2003 09:58:33 -0000 1.2 *************** *** 13,17 **** Python variables to AppleEvent descriptors and back (unpacking). Within Python the AppleEvent descriptor is handled by Python objects ! of built-in type \pytype{AEDesc}, defined in module \refmodule{AE}. The \module{aepack} module defines the following functions: --- 13,17 ---- Python variables to AppleEvent descriptors and back (unpacking). Within Python the AppleEvent descriptor is handled by Python objects ! of built-in type \class{AEDesc}, defined in module \refmodule{AE}. The \module{aepack} module defines the following functions: *************** *** 26,33 **** --- 26,35 ---- \begin{tableii}{l|l}{textrm}{Python type}{descriptor type} \lineii{\class{FSSpec}}{typeFSS} + \lineii{\class{FSRef}}{typeFSRef} \lineii{\class{Alias}}{typeAlias} \lineii{integer}{typeLong (32 bit integer)} \lineii{float}{typeFloat (64 bit floating point)} \lineii{string}{typeText} + \lineii{unicode}{typeUnicodeText} \lineii{list}{typeAEList} \lineii{dictionary}{typeAERecord} *************** *** 35,44 **** \end{tableii} - \pytype{FSSpec} and \pytype{Alias} are built-in object types defined - in the module \refmodule{macfs}. - If \var{x} is a Python instance then this function attempts to call an \method{__aepack__()} method. This method should return an ! \pytype{AE.AEDesc} object. If the conversion \var{x} is not defined above, this function returns --- 37,43 ---- \end{tableii} If \var{x} is a Python instance then this function attempts to call an \method{__aepack__()} method. This method should return an ! \class{AE.AEDesc} object. If the conversion \var{x} is not defined above, this function returns Index: libmac.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmac.tex,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** libmac.tex 15 Feb 2002 14:35:09 -0000 1.22 --- libmac.tex 12 Feb 2003 09:58:33 -0000 1.23 *************** *** 7,13 **** ! This module implements the operating system dependent functionality provided by the standard module \module{os}\refstmodindex{os}. It is ! best accessed through the \module{os} module. The following functions are available in this module: --- 7,14 ---- ! This module implements the Mac OS 9 operating system dependent functionality provided by the standard module \module{os}\refstmodindex{os}. It is ! best accessed through the \module{os} module. This module is only available in ! MacPython-OS9, on MacPython-OSX \module{posix} is used. The following functions are available in this module: *************** *** 30,50 **** as well as the exception \exception{error}. Note that the times returned by \function{stat()} are floating-point values, like all time ! values in MacPython. ! ! One additional function is available, but only under Classic MacPython, ! not under Carbon MacPython: ! ! \begin{funcdesc}{xstat}{path} ! This function returns the same information as \function{stat()}, but ! with three additional values appended: the size of the resource fork ! of the file and its 4-character creator and type. ! Availability: Classic MacPython only. ! \deprecated{2.3}{Use the \function{\refmodule{macfs}.FSSpec()} ! function to get an FSSpec object for the file, then ! use the \method{GetCreatorType()} method to get the ! creator and type information. It will no longer be ! possible to get the size of the resource fork.} ! \end{funcdesc} ! \section{\module{macpath} --- --- 31,35 ---- as well as the exception \exception{error}. Note that the times returned by \function{stat()} are floating-point values, like all time ! values in MacPython-OS9. \section{\module{macpath} --- Index: libmacfs.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmacfs.tex,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** libmacfs.tex 6 Aug 2002 22:15:23 -0000 1.28 --- libmacfs.tex 12 Feb 2003 09:58:33 -0000 1.29 *************** *** 2,10 **** Various file system services} ! \declaremodule{builtin}{macfs} \platform{Mac} \modulesynopsis{Support for FSSpec, the Alias Manager, \program{finder} aliases, and the Standard File package.} This module provides access to Macintosh FSSpec handling, the Alias --- 2,14 ---- Various file system services} ! \declaremodule{standard}{macfs} \platform{Mac} \modulesynopsis{Support for FSSpec, the Alias Manager, \program{finder} aliases, and the Standard File package.} + \deprecated{2.3}{The macfs module should be considered obsolete. For + \class{FSSpec}, \class{FSRef} and \class{Alias} handling use the + Carbon.File or Carbon.Folder module. For file dialogs use the + \module{EasyDialogs} module.} This module provides access to Macintosh FSSpec handling, the Alias *************** *** 16,22 **** Whenever a function or method expects a \var{file} argument, this argument can be one of three things:\ (1) a full or partial Macintosh ! pathname, (2) an \pytype{FSSpec} object or (3) a 3-tuple \code{(\var{wdRefNum}, \var{parID}, \var{name})} as described in ! \citetitle{Inside Macintosh:\ Files}. An \pytype{FSSpec} can point to a non-existing file, as long as the folder containing the file exists. Under MacPython the same is true for a pathname, but not under unix-Pyton --- 20,26 ---- Whenever a function or method expects a \var{file} argument, this argument can be one of three things:\ (1) a full or partial Macintosh ! pathname, (2) an \class{FSSpec} object or (3) a 3-tuple \code{(\var{wdRefNum}, \var{parID}, \var{name})} as described in ! \citetitle{Inside Macintosh:\ Files}. An \class{FSSpec} can point to a non-existing file, as long as the folder containing the file exists. Under MacPython the same is true for a pathname, but not under unix-Pyton *************** *** 27,51 **** Standard File package can also be found there. - \note{A module, \refmodule{macfsn}, is auto-imported to replace - StandardFile calls in \module{macfs} with NavServices calls.} - \begin{funcdesc}{FSSpec}{file} ! Create an \pytype{FSSpec} object for the specified file. \end{funcdesc} \begin{funcdesc}{RawFSSpec}{data} ! Create an \pytype{FSSpec} object given the raw data for the \C{} ! structure for the \pytype{FSSpec} as a string. This is mainly useful ! if you have obtained an \pytype{FSSpec} structure over a network. \end{funcdesc} \begin{funcdesc}{RawAlias}{data} ! Create an \pytype{Alias} object given the raw data for the \C{} structure for the alias as a string. This is mainly useful if you ! have obtained an \pytype{FSSpec} structure over a network. \end{funcdesc} \begin{funcdesc}{FInfo}{} ! Create a zero-filled \pytype{FInfo} object. \end{funcdesc} --- 31,52 ---- Standard File package can also be found there. \begin{funcdesc}{FSSpec}{file} ! Create an \class{FSSpec} object for the specified file. \end{funcdesc} \begin{funcdesc}{RawFSSpec}{data} ! Create an \class{FSSpec} object given the raw data for the \C{} ! structure for the \class{FSSpec} as a string. This is mainly useful ! if you have obtained an \class{FSSpec} structure over a network. \end{funcdesc} \begin{funcdesc}{RawAlias}{data} ! Create an \class{Alias} object given the raw data for the \C{} structure for the alias as a string. This is mainly useful if you ! have obtained an \class{FSSpec} structure over a network. \end{funcdesc} \begin{funcdesc}{FInfo}{} ! Create a zero-filled \class{FInfo} object. \end{funcdesc} *************** *** 53,59 **** Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec}, \var{isfolder}, \var{aliased})} where \var{fsspec} is the resulting ! \pytype{FSSpec} object, \var{isfolder} is true if \var{fsspec} points to a folder and \var{aliased} is true if the file was an alias in the ! first place (otherwise the \pytype{FSSpec} object for the file itself is returned). \end{funcdesc} --- 54,60 ---- Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec}, \var{isfolder}, \var{aliased})} where \var{fsspec} is the resulting ! \class{FSSpec} object, \var{isfolder} is true if \var{fsspec} points to a folder and \var{aliased} is true if the file was an alias in the ! first place (otherwise the \class{FSSpec} object for the file itself is returned). \end{funcdesc} *************** *** 62,66 **** Present the user with a standard ``open input file'' dialog. Optionally, you can pass up to four 4-character file types to limit ! the files the user can choose from. The function returns an \pytype{FSSpec} object and a flag indicating that the user completed the dialog without cancelling. --- 63,67 ---- Present the user with a standard ``open input file'' dialog. Optionally, you can pass up to four 4-character file types to limit ! the files the user can choose from. The function returns an \class{FSSpec} object and a flag indicating that the user completed the dialog without cancelling. *************** *** 76,80 **** dialog. \var{prompt} is the prompt string, and the optional \var{default} argument initializes the output file name. The function ! returns an \pytype{FSSpec} object and a flag indicating that the user completed the dialog without cancelling. \end{funcdesc} --- 77,81 ---- dialog. \var{prompt} is the prompt string, and the optional \var{default} argument initializes the output file name. The function ! returns an \class{FSSpec} object and a flag indicating that the user completed the dialog without cancelling. \end{funcdesc} *************** *** 84,88 **** have to first open the directory before clicking on the ``select current directory'' button. \var{prompt} is the prompt string which will be ! displayed at the top of the dialog. Return an \pytype{FSSpec} object and a success-indicator. \end{funcdesc} --- 85,89 ---- have to first open the directory before clicking on the ``select current directory'' button. \var{prompt} is the prompt string which will be ! displayed at the top of the dialog. Return an \class{FSSpec} object and a success-indicator. \end{funcdesc} *************** *** 106,123 **** locate. Setting \var{create} causes the folder to be created if it does not exist. Returns a \code{(\var{vrefnum}, \var{dirid})} tuple. \end{funcdesc} \begin{funcdesc}{NewAliasMinimalFromFullPath}{pathname} ! Return a minimal \pytype{alias} object that points to the given file, which must be specified as a full pathname. This is the only way to create an ! \pytype{Alias} pointing to a non-existing file. - The constants for \var{where} and \var{which} can be obtained from the - standard module \var{MACFS}. \end{funcdesc} \begin{funcdesc}{FindApplication}{creator} Locate the application with 4-character creator code \var{creator}. The ! function returns an \pytype{FSSpec} object pointing to the application. \end{funcdesc} --- 107,125 ---- locate. Setting \var{create} causes the folder to be created if it does not exist. Returns a \code{(\var{vrefnum}, \var{dirid})} tuple. + + The constants for \var{where} and \var{which} can be obtained from the + standard module \var{Carbon.Folders}. \end{funcdesc} \begin{funcdesc}{NewAliasMinimalFromFullPath}{pathname} ! Return a minimal \class{alias} object that points to the given file, which must be specified as a full pathname. This is the only way to create an ! \class{Alias} pointing to a non-existing file. \end{funcdesc} \begin{funcdesc}{FindApplication}{creator} Locate the application with 4-character creator code \var{creator}. The ! function returns an \class{FSSpec} object pointing to the application. \end{funcdesc} *************** *** 131,135 **** \begin{methoddesc}[FSSpec]{as_pathname}{} ! Return the full pathname of the file described by the \pytype{FSSpec} object. \end{methoddesc} --- 133,137 ---- \begin{methoddesc}[FSSpec]{as_pathname}{} ! Return the full pathname of the file described by the \class{FSSpec} object. \end{methoddesc} *************** *** 137,141 **** \begin{methoddesc}[FSSpec]{as_tuple}{} Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of ! the file described by the \pytype{FSSpec} object. \end{methoddesc} --- 139,143 ---- \begin{methoddesc}[FSSpec]{as_tuple}{} Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of ! the file described by the \class{FSSpec} object. \end{methoddesc} *************** *** 159,168 **** \begin{methoddesc}[FSSpec]{GetFInfo}{} ! Return a \pytype{FInfo} object describing the finder info for the file. \end{methoddesc} \begin{methoddesc}[FSSpec]{SetFInfo}{finfo} Set the finder info for the file to the values given as \var{finfo} ! (an \pytype{FInfo} object). \end{methoddesc} --- 161,170 ---- \begin{methoddesc}[FSSpec]{GetFInfo}{} ! Return a \class{FInfo} object describing the finder info for the file. \end{methoddesc} \begin{methoddesc}[FSSpec]{SetFInfo}{finfo} Set the finder info for the file to the values given as \var{finfo} ! (an \class{FInfo} object). \end{methoddesc} *************** *** 189,193 **** Resolve the alias. If the alias was created as a relative alias you should pass the file relative to which it is. Return the FSSpec for ! the file pointed to and a flag indicating whether the \pytype{Alias} object itself was modified during the search process. If the file does not exist but the path leading up to it does exist a valid fsspec --- 191,195 ---- Resolve the alias. If the alias was created as a relative alias you should pass the file relative to which it is. Return the FSSpec for ! the file pointed to and a flag indicating whether the \class{Alias} object itself was modified during the search process. If the file does not exist but the path leading up to it does exist a valid fsspec *************** *** 205,212 **** Note that it is currently not possible to directly manipulate a ! resource as an \pytype{Alias} object. Hence, after calling \method{Update()} or after \method{Resolve()} indicates that the alias has changed the Python program is responsible for getting the ! \member{data} value from the \pytype{Alias} object and modifying the resource. --- 207,214 ---- Note that it is currently not possible to directly manipulate a ! resource as an \class{Alias} object. Hence, after calling \method{Update()} or after \method{Resolve()} indicates that the alias has changed the Python program is responsible for getting the ! \member{data} value from the \class{Alias} object and modifying the resource. Index: libmacos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmacos.tex,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** libmacos.tex 19 Oct 2002 21:36:56 -0000 1.18 --- libmacos.tex 12 Feb 2003 09:58:33 -0000 1.19 *************** *** 41,44 **** --- 41,46 ---- event handler. Setting an event handler while one is already set is an error. + + Availability: MacPython-OS9. \end{funcdesc} *************** *** 64,67 **** --- 66,71 ---- The most common use case is to call \code{SchedParams(0, 0)} to completely disable event handling in the interpreter mainloop. + + Availability: MacPython-OS9. \end{funcdesc} *************** *** 75,78 **** --- 79,84 ---- If you attempt to call this function from an event handler set through \function{SetEventHandler()} you will get an exception. + + Availability: MacPython-OS9. \end{funcdesc} *************** *** 88,97 **** early in initialization without first having to load numerous extension modules. \end{funcdesc} \begin{funcdesc}{DebugStr}{message \optional{, object}} ! Drop to the low-level debugger with message \var{message}. The optional \var{object} argument is not used, but can easily be ! inspected from the debugger. Note that you should use this function with extreme care: if no --- 94,106 ---- early in initialization without first having to load numerous extension modules. + + Availability: MacPython-OS9. \end{funcdesc} \begin{funcdesc}{DebugStr}{message \optional{, object}} ! On Mac OS 9, drop to the low-level debugger with message \var{message}. The optional \var{object} argument is not used, but can easily be ! inspected from the debugger. On Mac OS X the string is simply printed ! to stderr. Note that you should use this function with extreme care: if no *************** *** 99,102 **** --- 108,132 ---- system. It is intended mainly for developers of Python extension modules. + \end{funcdesc} + + \begin{funcdesc}{SysBeep}{} + Ring the bell. + \end{funcdesc} + + \begin{funcdesc}{GetTicks}{} + Get the number of clock ticks (1/60th of a second) since system boot. + \end{funcdesc} + + \begin{funcdesc}{GetCreatorAndType}{file} + Return the file creator and file type as two four-character strings. + The \var{file} parameter can be a pathname or an \code{FSSpec} or + \code{FSRef} object. + \end{funcdesc} + + \begin{funcdesc}{SetCreatorAndType}{file, creator, type} + Set the file creator and file type. + The \var{file} parameter can be a pathname or an \code{FSSpec} or + \code{FSRef} object. \var{creator} and \var{type} must be four character + strings. \end{funcdesc} Index: libmacostools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmacostools.tex,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** libmacostools.tex 6 Aug 2002 22:14:23 -0000 1.15 --- libmacostools.tex 12 Feb 2003 09:58:33 -0000 1.16 *************** *** 8,12 **** This module contains some convenience routines for file-manipulation ! on the Macintosh. The \module{macostools} module defines the following functions: --- 8,13 ---- This module contains some convenience routines for file-manipulation ! on the Macintosh. All file parameters can be specified as ! pathnames, \class{FSRef} or \class{FSSpec} objects. The \module{macostools} module defines the following functions: *************** *** 14,19 **** \begin{funcdesc}{copy}{src, dst\optional{, createpath\optional{, copytimes}}} ! Copy file \var{src} to \var{dst}. The files can be specified as ! pathnames or \pytype{FSSpec} objects. If \var{createpath} is non-zero the folders leading to \var{dst} are created if necessary. The method copies data and --- 15,19 ---- \begin{funcdesc}{copy}{src, dst\optional{, createpath\optional{, copytimes}}} ! Copy file \var{src} to \var{dst}. If \var{createpath} is non-zero the folders leading to \var{dst} are created if necessary. The method copies data and *************** *** 30,35 **** \begin{funcdesc}{mkalias}{src, dst} ! Create a finder alias \var{dst} pointing to \var{src}. Both may be ! specified as pathnames or \pytype{FSSpec} objects. \end{funcdesc} --- 30,34 ---- \begin{funcdesc}{mkalias}{src, dst} ! Create a finder alias \var{dst} pointing to \var{src}. \end{funcdesc} *************** *** 63,67 **** All file and folder parameters can be specified either as full ! pathnames or as \pytype{FSSpec} objects. The \module{findertools} module defines the following functions: --- 62,66 ---- All file and folder parameters can be specified either as full ! pathnames, or as \class{FSRef} or \class{FSSpec} objects. The \module{findertools} module defines the following functions: *************** *** 75,80 **** \begin{funcdesc}{Print}{file} ! Tell the finder to print a file (again specified by full pathname or ! \pytype{FSSpec}). The behaviour is identical to selecting the file and using the print command in the finder's file menu. \end{funcdesc} --- 74,78 ---- \begin{funcdesc}{Print}{file} ! Tell the finder to print a file. The behaviour is identical to selecting the file and using the print command in the finder's file menu. \end{funcdesc} *************** *** 82,86 **** \begin{funcdesc}{copy}{file, destdir} Tell the finder to copy a file or folder \var{file} to folder ! \var{destdir}. The function returns an \pytype{Alias} object pointing to the new file. \end{funcdesc} --- 80,84 ---- \begin{funcdesc}{copy}{file, destdir} Tell the finder to copy a file or folder \var{file} to folder ! \var{destdir}. The function returns an \class{Alias} object pointing to the new file. \end{funcdesc} *************** *** 88,92 **** \begin{funcdesc}{move}{file, destdir} Tell the finder to move a file or folder \var{file} to folder ! \var{destdir}. The function returns an \pytype{Alias} object pointing to the new file. \end{funcdesc} --- 86,90 ---- \begin{funcdesc}{move}{file, destdir} Tell the finder to move a file or folder \var{file} to folder ! \var{destdir}. The function returns an \class{Alias} object pointing to the new file. \end{funcdesc} Index: libmacui.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmacui.tex,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** libmacui.tex 15 Apr 2002 19:53:35 -0000 1.17 --- libmacui.tex 12 Feb 2003 09:58:33 -0000 1.18 *************** *** 111,115 **** --- 111,193 ---- \end{funcdesc} + \begin{funcdesc}{AskFileForOpen}{ + \optional{message} + \optional{, typeList} + \optional{, defaultLocation} + \optional{, defaultOptionFlags} + \optional{, location} + \optional{, clientName} + \optional{, windowTitle} + \optional{, actionButtonLabel} + \optional{, cancelButtonLabel} + \optional{, preferenceKey} + \optional{, popupExtension} + \optional{, eventProc} + \optional{, previewProc} + \optional{, filterProc} + \optional{, wanted} + } + Post a dialog asking the user for a file to open, and return the file + selected or \var{None} if the user cancelled. + \var{message} is a text message to display, + \var{typeList} is a list of 4-char filetypes allowable, + \var{defaultLocation} is the pathname, FSSpec or FSRef of the folder + to show initially, + \var{location} is the \code{(x, y)} position on the screen where the + dialog is shown, + \var{actionButtonLabel} is a string to show in stead of ``Open'' in the + OK button, + \var{cancelButtonLabel} is a string to show in stead of ``Cancel'' in the + cancel button, + \var{wanted} is the type of value wanted as a return: \class{string}, + \class{unicode}, \class{FSSpec}, \class{FSRef} and subtypes thereof are + acceptable. + + For a description of the other arguments please see the Apple Navigation + Services documentation and the EasyDialogs sourcecode. + \end{funcdesc} + + \begin{funcdesc}{AskFileForSave}{ + \optional{message} + \optional{, savedFileName} + \optional{, defaultLocation} + \optional{, defaultOptionFlags} + \optional{, location} + \optional{, clientName} + \optional{, windowTitle} + \optional{, actionButtonLabel} + \optional{, cancelButtonLabel} + \optional{, preferenceKey} + \optional{, popupExtension} + \optional{, fileType} + \optional{, fileCreator} + \optional{, eventProc} + \optional{, wanted} + } + Post a dialog asking the user for a file to save to, and return the file + selected or \var{None} if the user cancelled. \var{savedFileName} is the + default for the file name to save to (the return value). See AskFileForOpen + for a description of the other arguments. + \end{funcdesc} + \begin{funcdesc}{AskFolder}{ + \optional{message} + \optional{, defaultLocation} + \optional{, defaultOptionFlags} + \optional{, location} + \optional{, clientName} + \optional{, windowTitle} + \optional{, actionButtonLabel} + \optional{, cancelButtonLabel} + \optional{, preferenceKey} + \optional{, popupExtension} + \optional{, eventProc} + \optional{, filterProc} + \optional{, wanted} + } + Post a dialog asking the user to select a folder, and return the folder + selected or \var{None} if the user cancelled. See AskFileForOpen + for a description of the arguments. + \end{funcdesc} \subsection{ProgressBar Objects \label{progressbar-objects}} Index: mac.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/mac.tex,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** mac.tex 5 Oct 2001 16:45:53 -0000 1.9 --- mac.tex 12 Feb 2003 09:58:33 -0000 1.10 *************** *** 52,61 **** \input{libmac} - \input{libctb} \input{libmacfs} \input{libmacic} \input{libmacos} \input{libmacostools} - \input{libmacspeech} \input{libmacui} \input{libframework} --- 52,59 ---- Index: toolbox.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/toolbox.tex,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** toolbox.tex 8 Mar 2002 03:15:49 -0000 1.6 --- toolbox.tex 12 Feb 2003 09:58:33 -0000 1.7 *************** *** 14,19 **** Macintosh} or similar works. ! These modules all live in a package called \module{Carbon}. Despite the ! name Carbon they are also available under classic PPC MacPython. The normal use pattern is --- 14,20 ---- Macintosh} or similar works. ! These modules all live in a package called \module{Carbon}. Despite that name ! they are not all part of the Carbon framework: CF is really in the CoreFoundation ! framework and Qt is in the QuickTime framework. The normal use pattern is *************** *** 37,40 **** --- 38,46 ---- \modulesynopsis{Interface to the Apple Events toolbox.} + \section{\module{Carbon.AH} --- Apple Help} + \declaremodule{standard}{Carbon.AH} + \platform{Mac} + \modulesynopsis{Interface to the Apple Help manager.} + \section{\module{Carbon.App} --- Appearance Manager} *************** *** 49,57 **** \modulesynopsis{Interface to the Core Foundation.} ! This module is only available under Carbon MacPython. The \code{CFBase}, \code{CFArray}, \code{CFData}, \code{CFDictionary}, \code{CFString} and \code{CFURL} objects are supported, some only partially. \section{\module{Carbon.Cm} --- Component Manager} \declaremodule{standard}{Carbon.Cm} --- 55,73 ---- \modulesynopsis{Interface to the Core Foundation.} ! The \code{CFBase}, \code{CFArray}, \code{CFData}, \code{CFDictionary}, \code{CFString} and \code{CFURL} objects are supported, some only partially. + \section{\module{Carbon.CG} --- Core Graphics} + \declaremodule{standard}{Carbon.CG} + \platform{Mac} + \modulesynopsis{Interface to the Component Manager.} + + \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} + \declaremodule{standard}{Carbon.CaronEvt} + \platform{Mac} + \modulesynopsis{Interface to the Carbon Event Manager.} + \section{\module{Carbon.Cm} --- Component Manager} \declaremodule{standard}{Carbon.Cm} *************** *** 75,79 **** \declaremodule{standard}{Carbon.Evt} \platform{Mac} ! \modulesynopsis{Interface to the Event Manager.} --- 91,95 ---- \declaremodule{standard}{Carbon.Evt} \platform{Mac} ! \modulesynopsis{Interface to the classic Event Manager.} *************** *** 83,94 **** \modulesynopsis{Interface to the Font Manager.} \section{\module{Carbon.Help} --- Help Manager} \declaremodule{standard}{Carbon.Help} \platform{Mac} ! \modulesynopsis{Interface to the Balloon Help Manager.} ! ! This module is only available under MacOS9 and earlier in ! classic PPC MacPython. \section{\module{Carbon.List} --- List Manager} --- 99,112 ---- \modulesynopsis{Interface to the Font Manager.} + \section{\module{Carbon.Folder} --- Folder Manager} + \declaremodule{standard}{Carbon.Folder} + \platform{Mac} + \modulesynopsis{Interface to the Folder Manager.} + \section{\module{Carbon.Help} --- Help Manager} \declaremodule{standard}{Carbon.Help} \platform{Mac} ! \modulesynopsis{Interface to the Carbon Help Manager.} \section{\module{Carbon.List} --- List Manager} *************** *** 133,139 **** \modulesynopsis{Interface to the Resource Manager and Handles.} ! ! \input{libscrap} ! \section{\module{Carbon.Snd} --- Sound Manager} --- 151,158 ---- \modulesynopsis{Interface to the Resource Manager and Handles.} ! \section{\module{Carbon.Scrap} --- Scrap Manager} ! \declaremodule{standard}{Carbon.Scrap} ! \platform{Mac} ! \modulesynopsis{Interface to the Carbon Scrap Manager.} \section{\module{Carbon.Snd} --- Sound Manager} Index: undoc.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/undoc.tex,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** undoc.tex 17 Jan 2002 04:51:55 -0000 1.8 --- undoc.tex 12 Feb 2003 09:58:33 -0000 1.9 *************** *** 64,81 **** - \section{\module{macfsn} --- NavServices calls} - \declaremodule{standard}{macfsn} - \platform{Mac} - \modulesynopsis{NavServices versions of StandardFile calls.} - - - \module{macfsn} contains wrapper functions that have the same API as - the \refmodule{macfs} StandardFile calls, but are implemented with - Navigation Services through the - \refmodule{Nav}\refbimodindex{Nav} module. Importing it will replace - the methods in \refmodule{macfs}\refbimodindex{macfs} with these, if - Navigation Services is available on your machine. - - \section{\module{macresource} --- Locate script resources} \declaremodule{standard}{macresource} --- 64,67 ---- *************** *** 93,105 **** A low-level interface to Navigation Services. - - - \section{\module{mactty} --- Serial line connections} - \declaremodule{standard}{mactty} - \platform{Mac} - \modulesynopsis{Easy access serial to line connections.} - - This module is only available under Mac OS 9 or earlier in classic PPC - MacPython. \section{\module{mkcwproject} --- Create CodeWarrior projects} --- 79,82 ---- Index: using.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/using.tex,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** using.tex 18 Oct 2002 18:16:19 -0000 1.5 --- using.tex 12 Feb 2003 09:58:33 -0000 1.6 *************** *** 1,14 **** ! \chapter{Using Python on the Macintosh \label{using}} \sectionauthor{Bob Savage}{bobsavage@mac.com} ! Using Python on the Macintosh can seem like something completely different than using it on a \UNIX-like or Windows system. Most of the Python documentation, both the ``official'' documentation and published books, describe only how Python is used on these systems, ! causing confusion for the new user of MacPython. This chapter gives a brief introduction to the specifics of using Python on a Macintosh. ! \section{Getting and Installing MacPython \label{getting}} The most recent release version as well as possible newer experimental --- 1,20 ---- ! \chapter{Using Python on a Mac OS 9 Macintosh \label{using}} \sectionauthor{Bob Savage}{bobsavage@mac.com} ! Using Python on a Mac OS 9 Macintosh can seem like something completely different than using it on a \UNIX-like or Windows system. Most of the Python documentation, both the ``official'' documentation and published books, describe only how Python is used on these systems, ! causing confusion for the new user of MacPython-OS9. This chapter gives a brief introduction to the specifics of using Python on a Macintosh. + Note that this chapter is mainly relevant to Mac OS 9: MacPython-OSX + is a superset of a normal unix Python. While MacPython-OS9 runs fine + on Mac OS X it is a better choice to use MacPython-OSX there. + + The section on the IDE (see Section \ref{IDE}) is relevant to MacPython-OSX + too. ! \section{Getting and Installing MacPython-OS9 \label{getting}} The most recent release version as well as possible newer experimental *************** *** 61,74 **** \item - After dropping the script onto the \program{PythonInterpreter}, a - window appeared which said: ``File contains \code{\e r} characters - (incorrect line endings?)''. That script probably originated on a - \UNIX{} or Windows machine. You will need to change the line endings - to the standard Mac usage. One way to do this is to open the file in - \program{BBedit} - (\url{http://www.barebones.com/products/bbedit_lite.html}) which can - easily change the line endings between Mac, DOS, and \UNIX\ styles. - - \item When you waved the script icon over the \program{PythonInterpreter}, the \program{PythonInterpreter} icon did not hilight. Most likely the --- 67,70 ---- *************** *** 119,123 **** \label{argv}} ! There are two ways to simulate command-line arguments with MacPython. \begin{enumerate} --- 115,119 ---- \label{argv}} ! There are two ways to simulate command-line arguments with MacPython-OS9. \begin{enumerate} *************** *** 363,374 **** %\section{CGI on the Mac with Python \label{CGI}} %**NEED INFO HERE** - - \section{Mac OS X} - - At the time of this writing Mac OS X had just been released as a - Public Beta. Efforts are under way to bring MacPython to Mac OS X. The - MacPython release \version{1.5.2c1} runs quite well within the - ``Classic'' environment. A ``Carbon'' port of the MacPython code is - being prepared for release, and several people have made a command - line version available to the ``Darwin'' layer (which is accessible - via Terminal.app). --- 359,360 ---- --- libctb.tex DELETED --- --- libmacspeech.tex DELETED --- From amk@amk.ca Wed Feb 12 12:50:40 2003 From: amk@amk.ca (A.M. Kuchling) Date: Wed, 12 Feb 2003 07:50:40 -0500 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.15,1.16 In-Reply-To: ; from rhettinger@users.sourceforge.net on Tue, Feb 11, 2003 at 08:09:16PM -0800 References: Message-ID: <20030212075040.B4188@nyman.amk.ca> On Tue, Feb 11, 2003 at 08:09:16PM -0800, rhettinger@users.sourceforge.net wrote: >+ then else I'm not following these threads closely, but the above seems wrong; should it be then else ? --amk From rhettinger@users.sourceforge.net Wed Feb 12 12:36:02 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Wed, 12 Feb 2003 04:36:02 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv7597 Modified Files: pep-0308.txt Log Message: Put variables in correct order. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** pep-0308.txt 12 Feb 2003 04:09:14 -0000 1.16 --- pep-0308.txt 12 Feb 2003 12:35:59 -0000 1.17 *************** *** 86,90 **** Holger Krekel proposed a new, minimally invasive variant: ! and else The concept behind it is that a nearly complete ternary operator --- 86,90 ---- Holger Krekel proposed a new, minimally invasive variant: ! and else The concept behind it is that a nearly complete ternary operator *************** *** 97,101 **** Christian Tismer proposed a variant of the same idea: ! then else --- --- 97,101 ---- Christian Tismer proposed a variant of the same idea: ! then else --- From jackjansen@users.sourceforge.net Wed Feb 12 12:47:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 04:47:03 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE Wlists.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv12279 Modified Files: Wlists.py Log Message: In a MultiList select all cells in the row, not only the first one. Index: Wlists.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/Wlists.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** Wlists.py 11 Feb 2003 16:26:26 -0000 1.14 --- Wlists.py 12 Feb 2003 12:47:00 -0000 1.15 *************** *** 574,581 **** set_sel = self._list.LSetSelect for i in range(len(self.items)): ! if i in selection: ! set_sel(1, (0, i)) ! else: ! set_sel(0, (0, i)) #self._list.LAutoScroll() --- 574,582 ---- set_sel = self._list.LSetSelect for i in range(len(self.items)): ! for j in range(len(self.items[i])): ! if i in selection: ! set_sel(1, (j, i)) ! else: ! set_sel(0, (j, i)) #self._list.LAutoScroll() From jackjansen@users.sourceforge.net Wed Feb 12 12:47:59 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 04:47:59 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PackageManager.py,NONE,1.1 PythonIDEMain.py,1.27,1.28 InstallManager.py,1.1,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv12573 Modified Files: PythonIDEMain.py Added Files: PackageManager.py Removed Files: InstallManager.py Log Message: Renamed InstallManager to PackageManager, finished a first stab at the implementation and integrated it into the IDE. --- NEW FILE: PackageManager.py --- import W import Wapplication from Carbon import Evt import EasyDialogs import FrameWork import sys import string import os import pimp ELIPSES = '...' class PackageManagerMain(Wapplication.Application): def __init__(self): self.preffilepath = os.path.join("Python", "Package Install Manager Prefs") Wapplication.Application.__init__(self, 'Pimp') from Carbon import AE from Carbon import AppleEvents AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments, self.ignoreevent) AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication, self.quitevent) if 1: import PyConsole # With -D option (OSX command line only) keep stderr, for debugging the IDE # itself. debug_stderr = None if len(sys.argv) >= 2 and sys.argv[1] == '-D': debug_stderr = sys.stderr del sys.argv[1] PyConsole.installoutput() if debug_stderr: sys.stderr = debug_stderr self.opendoc(None) self.mainloop() def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") ## newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') ## openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') ## openbynameitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openbyname') FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') ## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') ## saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') FrameWork.Separator(m) m = Wapplication.Menu(self.menubar, "Edit") undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") FrameWork.Separator(m) cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") FrameWork.MenuItem(m, "Clear", None, "clear") FrameWork.Separator(m) selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") m = Wapplication.Menu(self.menubar, "Package") runitem = FrameWork.MenuItem(m, "Install", "I", 'install') homepageitem = FrameWork.MenuItem(m, "Visit Homepage", None, 'homepage') self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') self.makeopenwindowsmenu() self._menustocheck = [closeitem, saveasitem, undoitem, cutitem, copyitem, pasteitem, selallitem, runitem, homepageitem] def quitevent(self, theAppleEvent, theReply): from Carbon import AE AE.AEInteractWithUser(50000000) self._quit() def ignoreevent(self, theAppleEvent, theReply): pass def opendocsevent(self, theAppleEvent, theReply): W.SetCursor('watch') import aetools parameters, args = aetools.unpackevent(theAppleEvent) docs = parameters['----'] if type(docs) <> type([]): docs = [docs] for doc in docs: fsr, a = doc.FSResolveAlias(None) path = fsr.as_pathname() path = urllib.pathname2url(path) self.opendoc(path) def opendoc(self, url): PackageBrowser(url) def getabouttext(self): return "About Package Manager"+ELIPSES def do_about(self, id, item, window, event): EasyDialogs.Message("Package Install Manager for Python") def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) if filename: filename = urllib.pathname2url(filename) self.opendoc(filename) def domenu_openbyname(self, *args): url = EasyDialogs.AskString("Open URL:", ok="Open") if url: self.opendoc(url) def makeopenwindowsmenu(self): for i in range(len(self.openwindowsmenu.items)): self.openwindowsmenu.menu.DeleteMenuItem(1) self.openwindowsmenu.items = [] windows = [] self._openwindows = {} for window in self._windows.keys(): title = window.GetWTitle() if not title: title = "" windows.append((title, window)) windows.sort() for title, window in windows: shortcut = None item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) self._openwindows[item.item] = window self._openwindowscheckmark = 0 self.checkopenwindowsmenu() def domenu_openwindows(self, id, item, window, event): w = self._openwindows[item] w.ShowWindow() w.SelectWindow() def domenu_quit(self): self._quit() def domenu_save(self, *args): print "Save" def _quit(self): ## import PyConsole, PyEdit for window in self._windows.values(): try: rv = window.close() # ignore any errors while quitting except: rv = 0 # (otherwise, we can get stuck!) if rv and rv > 0: return ## try: ## PyConsole.console.writeprefs() ## PyConsole.output.writeprefs() ## PyEdit.searchengine.writeprefs() ## except: ## # Write to __stderr__ so the msg end up in Console.app and has ## # at least _some_ chance of getting read... ## # But: this is a workaround for way more serious problems with ## # the Python 2.2 Jaguar addon. ## sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") self.quitting = 1 class PimpInterface: def setuppimp(self, url): self.pimpprefs = pimp.PimpPreferences() self.pimpdb = pimp.PimpDatabase(self.pimpprefs) self.pimpinstaller = pimp.PimpInstaller(self.pimpdb) if not url: url = self.pimpprefs.pimpDatabase self.pimpdb.appendURL(url) def getbrowserdata(self): self.packages = self.pimpdb.list() rv = [] for pkg in self.packages: name = pkg.fullname() status, _ = pkg.installed() description = pkg.description() rv.append((status, name, description)) return rv def getstatus(self, number): pkg = self.packages[number] return pkg.installed() def installpackage(self, sel, output, recursive, force): pkg = self.packages[sel] list, messages = self.pimpinstaller.prepareInstall(pkg, force, recursive) if messages: return messages messages = self.pimpinstaller.install(list, output) return messages class PackageBrowser(PimpInterface): def __init__(self, url = None): self.ic = None self.setuppimp(url) self.setupwidgets() self.updatestatus() def setupwidgets(self): self.w = W.Window((580, 400), "Python Install Manager", minsize = (300, 200), tabbable = 0) ## self.w.divline = W.HorizontalLine((0, 20, 0, 0)) self.w.titlebar = W.TextBox((4, 4, 40, 12), 'Packages:') data = self.getbrowserdata() self.w.packagebrowser = W.MultiList((4, 20, 0, -70), data, self.listhit, cols=3) self.w.installed_l = W.TextBox((4, -66, 60, 12), 'Installed:') self.w.installed = W.TextBox((64, -66, 0, 12), '') self.w.message_l = W.TextBox((4, -48, 60, 12), 'Status:') self.w.message = W.TextBox((64, -48, 0, 12), '') self.w.homepage_button = W.Button((4, -28, 96, 18), 'View homepage', self.do_homepage) self.w.verbose_button = W.CheckBox((-288, -26, 60, 18), 'Verbose') self.w.recursive_button = W.CheckBox((-224, -26, 80, 18), 'Recursive', self.updatestatus) self.w.recursive_button.set(1) self.w.force_button = W.CheckBox((-140, -26, 60, 18), 'Force', self.updatestatus) self.w.install_button = W.Button((-76, -28, 56, 18), 'Install', self.do_install) self.w.open() def updatestatus(self): sel = self.w.packagebrowser.getselection() data = self.getbrowserdata() self.w.packagebrowser.setitems(data) if len(sel) != 1: self.w.installed.set('') self.w.message.set('') self.w.install_button.enable(0) self.w.homepage_button.enable(0) self.w.verbose_button.enable(0) self.w.recursive_button.enable(0) self.w.force_button.enable(0) else: sel = sel[0] self.w.packagebrowser.setselection([sel]) installed, message = self.getstatus(sel) self.w.installed.set(installed) self.w.message.set(message) self.w.install_button.enable(installed != "yes" or self.w.force_button.get()) self.w.homepage_button.enable(not not self.packages[sel].homepage()) self.w.verbose_button.enable(1) self.w.recursive_button.enable(1) self.w.force_button.enable(1) def listhit(self, *args, **kwargs): self.updatestatus() def do_install(self): sel = self.w.packagebrowser.getselection()[0] if self.w.verbose_button.get(): output = sys.stdout else: output = None recursive = self.w.recursive_button.get() force = self.w.force_button.get() messages = self.installpackage(sel, output, recursive, force) self.updatestatus() if messages: EasyDialogs.Message('\n'.join(messages)) def do_homepage(self): sel = self.w.packagebrowser.getselection()[0] if not self.ic: import ic self.ic = ic.IC() self.ic.launchurl(self.packages[sel].homepage()) if __name__ == '__main__': PackageManagerMain() Index: PythonIDEMain.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PythonIDEMain.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** PythonIDEMain.py 6 Feb 2003 22:32:35 -0000 1.27 --- PythonIDEMain.py 12 Feb 2003 12:47:56 -0000 1.28 *************** *** 83,86 **** --- 83,88 ---- FrameWork.Separator(m) saveasappletitem = FrameWork.MenuItem(m, "Save as Applet"+ELIPSES, None, 'save_as_applet') + FrameWork.Separator(m) + instmgritem = FrameWork.MenuItem(m, "Package Manager", None, 'openpackagemanager') if not runningOnOSX(): # On OSX there's a special "magic" quit menu, so we shouldn't add *************** *** 308,311 **** --- 310,318 ---- sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") self.quitting = 1 + + def domenu_openpackagemanager(self): + import PackageManager + PackageManager.PackageBrowser() + print "Done" def makehelpmenu(self): --- InstallManager.py DELETED --- From montanaro@users.sourceforge.net Wed Feb 12 15:11:56 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:11:56 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv16545 Modified Files: csv.py Log Message: forgot to add Dict{Reader,Writer} to __all__ Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** csv.py 12 Feb 2003 02:43:14 -0000 1.31 --- csv.py 12 Feb 2003 15:11:53 -0000 1.32 *************** *** 7,11 **** "Error", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", ! "unregister_dialect", "__version__" ] class Dialect: --- 7,11 ---- "Error", "Dialect", "excel", "excel_tab", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", ! "unregister_dialect", "__version__", "DictReader", "DictWriter" ] class Dialect: From jackjansen@users.sourceforge.net Wed Feb 12 15:36:29 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:36:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv29687 Modified Files: pimp.py Log Message: - Better way to find site-packages - Catch stderr as well as stdout - Fixed a bug with non-installable packages - Parse .pth files after installing, so you don't have to restart Python (or the IDE) after installing. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** pimp.py 11 Feb 2003 22:40:59 -0000 1.7 --- pimp.py 12 Feb 2003 15:36:25 -0000 1.8 *************** *** 34,38 **** DEFAULT_DOWNLOADDIR='/tmp' DEFAULT_BUILDDIR='/tmp' ! DEFAULT_INSTALLDIR=os.path.join(sys.prefix, "Lib", "site-packages") DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() --- 34,43 ---- DEFAULT_DOWNLOADDIR='/tmp' DEFAULT_BUILDDIR='/tmp' ! for _p in sys.path: ! if _p[-13:] == 'site-packages': ! DEFAULT_INSTALLDIR=_p ! break ! else: ! DEFAULT_INSTALLDIR=sys.prefix # Have to put things somewhere DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() *************** *** 340,344 **** rv = [] ! if not self._dict['Download-URL']: return [(None, "This package needs to be installed manually")] if not self._dict['Prerequisites']: --- 345,349 ---- rv = [] ! if not self._dict.get('Download-URL'): return [(None, "This package needs to be installed manually")] if not self._dict['Prerequisites']: *************** *** 370,374 **** if NO_EXECUTE: return 0 ! fp = os.popen(cmd, "r") while 1: line = fp.readline() --- 375,380 ---- if NO_EXECUTE: return 0 ! dummy, fp = os.popen4(cmd, "r") ! dummy.close() while 1: line = fp.readline() *************** *** 450,460 **** --- 456,470 ---- if msg: return "download %s: %s" % (self.fullname(), msg) + msg = self.unpackSinglePackage(output) if msg: return "unpack %s: %s" % (self.fullname(), msg) + if self._dict.has_key('Pre-install-command'): if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) + + old_contents = os.listdir(self._db.preferences.installDir) installcmd = self._dict.get('Install-command') if not installcmd: *************** *** 462,465 **** --- 472,479 ---- if self._cmd(output, self._buildDirname, installcmd): return "install %s: running \"%s\" failed" % self.fullname() + + new_contents = os.listdir(self._db.preferences.installDir) + self._interpretPthFiles(old_contents, new_contents) + if self._dict.has_key('Post-install-command'): if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): *************** *** 467,470 **** --- 481,510 ---- (self.fullname(), self._dict['Post-install-command']) return None + + def _interpretPthFiles(self, old_contents, new_contents): + """Evaluate any new .pth files that have appeared after installing""" + for fn in new_contents: + if fn in old_contents: + continue + if fn[-4:] != '.pth': + continue + fullname = os.path.join(self._db.preferences.installDir, fn) + f = open(fullname) + for line in f.readlines(): + if not line: + continue + if line[0] == '#': + continue + if line[:6] == 'import': + exec line + continue + if line[-1] == '\n': + line = line[:-1] + if not os.path.isabs(line): + line = os.path.join(self._db.preferences.installDir, line) + line = os.path.realpath(line) + if not line in sys.path: + sys.path.append(line) + class PimpInstaller: From jackjansen@users.sourceforge.net Wed Feb 12 15:37:30 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:37:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac aepack.py,1.3,1.4 aetypes.py,1.2,1.3 bgenlocations.py,1.2,1.3 buildtools.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv30629 Modified Files: aepack.py aetypes.py bgenlocations.py buildtools.py Log Message: When in MacPython-OSX use bundlebuilder to create .app bundles. Index: aepack.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/aepack.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** aepack.py 29 Jan 2003 10:41:18 -0000 1.3 --- aepack.py 12 Feb 2003 15:37:25 -0000 1.4 *************** *** 89,92 **** --- 89,94 ---- if isinstance(x, FSSType): return AE.AECreateDesc('fss ', x.data) + if isinstance(x, FSRefType): + return AE.AECreateDesc('fsrf', x.data) if isinstance(x, AliasType): return AE.AECreateDesc('alis', x.data) *************** *** 167,170 **** --- 169,174 ---- if t == typeFSS: return Carbon.File.FSSpec(rawdata=desc.data) + if t == typeFSRef: + return Carbon.File.FSRef(rawdata=desc.data) if t == typeInsertionLoc: record = desc.AECoerceDesc('reco') Index: aetypes.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/aetypes.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** aetypes.py 29 Jan 2003 10:39:19 -0000 1.2 --- aetypes.py 12 Feb 2003 15:37:25 -0000 1.3 *************** *** 12,33 **** def pack(*args, **kwargs): from aepack import pack ! return apply(pack, args, kwargs) - def IsSubclass(cls, base): - """Test whether CLASS1 is the same as or a subclass of CLASS2""" - # Loop to optimize for single inheritance - while 1: - if cls is base: return 1 - if len(cls.__bases__) <> 1: break - cls = cls.__bases__[0] - # Recurse to cope with multiple inheritance - for c in cls.__bases__: - if IsSubclass(c, base): return 1 - return 0 - - def IsInstance(x, cls): - """Test whether OBJECT is an instance of (a subclass of) CLASS""" - return type(x) is InstanceType and IsSubclass(x.__class__, cls) - def nice(s): """'nice' representation of an object""" --- 12,17 ---- def pack(*args, **kwargs): from aepack import pack ! return pack( *args, **kwargs) def nice(s): """'nice' representation of an object""" *************** *** 64,68 **** def IsEnum(x): ! return IsInstance(x, Enum) def mkenum(enum): --- 48,52 ---- def IsEnum(x): ! return isinstance(x, Enum) def mkenum(enum): *************** *** 109,113 **** def IsBoolean(x): ! return IsInstance(x, Boolean) def mkboolean(bool): --- 93,97 ---- def IsBoolean(x): ! return isinstance(x, Boolean) def mkboolean(bool): *************** *** 131,135 **** def IsType(x): ! return IsInstance(x, Type) def mktype(type): --- 115,119 ---- def IsType(x): ! return isinstance(x, Type) def mktype(type): *************** *** 154,158 **** def IsKeyword(x): ! return IsInstance(x, Keyword) class Range: --- 138,142 ---- def IsKeyword(x): ! return isinstance(x, Keyword) class Range: *************** *** 173,177 **** def IsRange(x): ! return IsInstance(x, Range) class Comparison: --- 157,161 ---- def IsRange(x): ! return isinstance(x, Range) class Comparison: *************** *** 196,200 **** def IsComparison(x): ! return IsInstance(x, Comparison) class NComparison(Comparison): --- 180,184 ---- def IsComparison(x): ! return isinstance(x, Comparison) class NComparison(Comparison): *************** *** 221,225 **** def IsOrdinal(x): ! return IsInstance(x, Ordinal) class NOrdinal(Ordinal): --- 205,209 ---- def IsOrdinal(x): ! return isinstance(x, Ordinal) class NOrdinal(Ordinal): *************** *** 251,255 **** def IsLogical(x): ! return IsInstance(x, Logical) class StyledText: --- 235,239 ---- def IsLogical(x): ! return isinstance(x, Logical) class StyledText: *************** *** 270,274 **** def IsStyledText(x): ! return IsInstance(x, StyledText) class AEText: --- 254,258 ---- def IsStyledText(x): ! return isinstance(x, StyledText) class AEText: *************** *** 291,295 **** def IsAEText(x): ! return IsInstance(x, AEText) class IntlText: --- 275,279 ---- def IsAEText(x): ! return isinstance(x, AEText) class IntlText: *************** *** 312,316 **** def IsIntlText(x): ! return IsInstance(x, IntlText) class IntlWritingCode: --- 296,300 ---- def IsIntlText(x): ! return isinstance(x, IntlText) class IntlWritingCode: *************** *** 332,336 **** def IsIntlWritingCode(x): ! return IsInstance(x, IntlWritingCode) class QDPoint: --- 316,320 ---- def IsIntlWritingCode(x): ! return isinstance(x, IntlWritingCode) class QDPoint: *************** *** 352,356 **** def IsQDPoint(x): ! return IsInstance(x, QDPoint) class QDRectangle: --- 336,340 ---- def IsQDPoint(x): ! return isinstance(x, QDPoint) class QDRectangle: *************** *** 375,379 **** def IsQDRectangle(x): ! return IsInstance(x, QDRectangle) class RGBColor: --- 359,363 ---- def IsQDRectangle(x): ! return isinstance(x, QDRectangle) class RGBColor: *************** *** 396,400 **** def IsRGBColor(x): ! return IsInstance(x, RGBColor) class ObjectSpecifier: --- 380,384 ---- def IsRGBColor(x): ! return isinstance(x, RGBColor) class ObjectSpecifier: *************** *** 445,449 **** def IsObjectSpecifier(x): ! return IsInstance(x, ObjectSpecifier) --- 429,433 ---- def IsObjectSpecifier(x): ! return isinstance(x, ObjectSpecifier) Index: bgenlocations.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bgenlocations.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** bgenlocations.py 26 Jan 2003 20:33:46 -0000 1.2 --- bgenlocations.py 12 Feb 2003 15:37:26 -0000 1.3 *************** *** 27,33 **** # if sys.platform == 'mac': ! _MWERKSDIR="Moes:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" else: ! _MWERKSDIR="/Volumes/Moes/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes") --- 27,33 ---- # if sys.platform == 'mac': ! _MWERKSDIR="Sap:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" else: ! _MWERKSDIR="/Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes") Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** buildtools.py 5 Feb 2003 13:39:04 -0000 1.4 --- buildtools.py 12 Feb 2003 15:37:26 -0000 1.5 *************** *** 45,51 **** """Locate the applet template along sys.path""" if MacOS.runtimemodel == 'macho': ! if template: ! return template ! return findtemplate_macho() if not template: template=TEMPLATE --- 45,49 ---- """Locate the applet template along sys.path""" if MacOS.runtimemodel == 'macho': ! return None if not template: template=TEMPLATE *************** *** 62,74 **** return file ! def findtemplate_macho(): ! execpath = sys.executable.split('/') ! if not 'Contents' in execpath: ! raise BuildError, "Not running from a .app bundle: %s" % sys.executable ! i = execpath.index('Contents') ! return '/'.join(execpath[:i]) ! ! ! def process(template, filename, destname, copy_codefragment, rsrcname=None, others=[], raw=0, progress="default"): --- 60,64 ---- return file ! def process(template, filename, destname, copy_codefragment=0, rsrcname=None, others=[], raw=0, progress="default"): *************** *** 119,123 **** pass process_common(template, progress, code, rsrcname, destname, 0, ! copy_codefragment, raw, others) --- 109,113 ---- pass process_common(template, progress, code, rsrcname, destname, 0, ! copy_codefragment, raw, others, filename) *************** *** 141,148 **** def process_common(template, progress, code, rsrcname, destname, is_update, ! copy_codefragment, raw=0, others=[]): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, ! is_update, raw, others) if others: raise BuildError, "Extra files only allowed for MachoPython applets" --- 131,138 ---- def process_common(template, progress, code, rsrcname, destname, is_update, ! copy_codefragment, raw=0, others=[], filename=None): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, ! is_update, raw, others, filename) if others: raise BuildError, "Extra files only allowed for MachoPython applets" *************** *** 275,284 **** progress.inc(0) ! def process_common_macho(template, progress, code, rsrcname, destname, is_update, raw=0, others=[]): # First make sure the name ends in ".app" if destname[-4:] != '.app': destname = destname + '.app' # Now deduce the short name ! shortname = os.path.split(destname)[1] if shortname[-4:] == '.app': # Strip the .app suffix --- 265,278 ---- progress.inc(0) ! def process_common_macho(template, progress, code, rsrcname, destname, is_update, ! raw=0, others=[], filename=None): ! # Check that we have a filename ! if filename is None: ! raise BuildError, "Need source filename on MacOSX" # First make sure the name ends in ".app" if destname[-4:] != '.app': destname = destname + '.app' # Now deduce the short name ! destdir, shortname = os.path.split(destname) if shortname[-4:] == '.app': # Strip the .app suffix *************** *** 296,429 **** else: plistname = None ! # Start with copying the .app framework ! if not is_update: ! exceptlist = ["Contents/Info.plist", ! "Contents/Resources/English.lproj/InfoPlist.strings", ! "Contents/Resources/English.lproj/Documentation", ! "Contents/Resources/python.rsrc", ! ] ! copyapptree(template, destname, exceptlist, progress) ! # SERIOUS HACK. If we've just copied a symlink as the ! # executable we assume we're running from the MacPython addon ! # to 10.2 python. We remove the symlink again and install ! # the appletrunner script. ! executable = os.path.join(destname, "Contents/MacOS/python") ! if os.path.islink(executable): ! os.remove(executable) ! dummyfp, appletrunner, d2 = imp.find_module('appletrunner') ! del dummyfp ! shutil.copy2(appletrunner, executable) ! os.chmod(executable, 0775) ! # Now either use the .plist file or the default if progress: ! progress.label('Create info.plist') ! progress.inc(0) if plistname: ! shutil.copy2(plistname, os.path.join(destname, 'Contents', 'Info.plist')) ! if icnsname: ! icnsdest = os.path.split(icnsname)[1] ! icnsdest = os.path.join(destname, ! os.path.join('Contents', 'Resources', icnsdest)) ! shutil.copy2(icnsname, icnsdest) ! # XXXX Wrong. This should be parsed from plist file. Also a big hack:-) ! if shortname == 'PythonIDE': ! ownertype = 'Pide' ! else: ! ownertype = 'PytA' ! # XXXX Should copy .icns file ! else: ! cocoainfo = '' ! for o in others: ! if o[-4:] == '.nib': ! nibname = os.path.split(o)[1][:-4] ! cocoainfo = """ ! NSMainNibFile ! %s ! NSPrincipalClass ! NSApplication""" % nibname ! elif o[-6:] == '.lproj': ! files = os.listdir(o) ! for f in files: ! if f[-4:] == '.nib': ! nibname = os.path.split(f)[1][:-4] ! cocoainfo = """ ! NSMainNibFile ! %s ! NSPrincipalClass ! NSApplication""" % nibname ! ! plistname = os.path.join(template, 'Contents', 'Resources', 'Applet-Info.plist') ! plistdata = open(plistname).read() ! plistdata = plistdata % {'appletname':shortname, 'cocoainfo':cocoainfo} ! ofp = open(os.path.join(destname, 'Contents', 'Info.plist'), 'w') ! ofp.write(plistdata) ! ofp.close() ! ownertype = 'PytA' ! # Create the PkgInfo file ! if progress: ! progress.label('Create PkgInfo') ! progress.inc(0) ! ofp = open(os.path.join(destname, 'Contents', 'PkgInfo'), 'wb') ! ofp.write('APPL' + ownertype) ! ofp.close() ! ! ! # Copy the resources from the target specific resource template, if any ! typesfound, ownertype = [], None ! try: ! input = macresource.open_pathname(rsrcname) ! except (MacOS.Error, ValueError): ! if progress: ! progress.inc(50) ! else: ! if progress: ! progress.label("Copy resources...") ! progress.set(20) ! resfilename = 'python.rsrc' # XXXX later: '%s.rsrc' % shortname ! try: ! output = Res.FSOpenResourceFile( ! os.path.join(destname, 'Contents', 'Resources', resfilename), ! u'', WRITE) ! except MacOS.Error: ! fsr, dummy = Res.FSCreateResourceFile( ! os.path.join(destname, 'Contents', 'Resources'), ! unicode(resfilename), '') ! output = Res.FSOpenResourceFile(fsr, u'', WRITE) ! ! typesfound, ownertype = copyres(input, output, [], 0, progress) ! Res.CloseResFile(input) ! Res.CloseResFile(output) ! ! if code: ! if raw: ! pycname = '__rawmain__.pyc' ! else: ! pycname = '__main__.pyc' ! # And we also create __rawmain__.pyc ! outputfilename = os.path.join(destname, 'Contents', 'Resources', '__rawmain__.pyc') ! if progress: ! progress.label('Creating __rawmain__.pyc') ! progress.inc(0) ! rawsourcefp, rawsourcefile, d2 = imp.find_module('appletrawmain') ! rawsource = rawsourcefp.read() ! rawcode = compile(rawsource, rawsourcefile, 'exec') ! writepycfile(rawcode, outputfilename) ! ! outputfilename = os.path.join(destname, 'Contents', 'Resources', pycname) ! if progress: ! progress.label('Creating '+pycname) ! progress.inc(0) ! writepycfile(code, outputfilename) ! # Copy other files the user asked for ! for osrc in others: ! oname = os.path.split(osrc)[1] ! odst = os.path.join(destname, 'Contents', 'Resources', oname) ! if progress: ! progress.label('Copy ' + oname) ! progress.inc(0) ! if os.path.isdir(osrc): ! copyapptree(osrc, odst) ! else: ! shutil.copy2(osrc, odst) if progress: progress.label('Done.') --- 290,313 ---- else: plistname = None ! if not os.path.exists(rsrcname): ! rsrcname = None if progress: ! progress.label('Creating bundle...') ! import bundlebuilder ! builder = bundlebuilder.AppBuilder(verbosity=0) ! builder.mainprogram = filename ! builder.builddir = destdir ! builder.name = shortname ! if rsrcname: ! builder.resources.append(rsrcname) ! for o in others: ! builder.resources.append(o) if plistname: ! import Plist ! builder.plist = Plist.fromFile(plistname) ! if icnsname: ! builder.iconfile = icnsname ! builder.setup() ! builder.build() if progress: progress.label('Done.') From jackjansen@users.sourceforge.net Wed Feb 12 15:38:47 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:38:47 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyEdit.py,1.35,1.36 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv31048 Modified Files: PyEdit.py Log Message: Create applets slightly differently: by saving the sourcecode to a temporary location. This is needed to makethings work with the new buildtools based on bundlebuilder. Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** PyEdit.py 6 Feb 2003 22:32:35 -0000 1.35 --- PyEdit.py 12 Feb 2003 15:38:37 -0000 1.36 *************** *** 455,458 **** --- 455,468 ---- except (SyntaxError, EOFError): raise buildtools.BuildError, "Syntax error in script %s" % `filename` + + import tempfile + tmpdir = tempfile.mkdtemp() + + if filename[-3:] != ".py": + filename = filename + ".py" + filename = os.path.join(tmpdir, os.path.split(filename)[1]) + fp = open(filename, "w") + fp.write(pytext) + fp.close() # Try removing the output file *************** *** 462,466 **** pass template = buildtools.findtemplate() ! buildtools.process_common(template, None, code, rsrcname, destname, 0, 1) def domenu_gotoline(self, *args): --- 472,476 ---- pass template = buildtools.findtemplate() ! buildtools.process(template, filename, destname, rsrcname=rsrcname, progress=None) def domenu_gotoline(self, *args): From jackjansen@users.sourceforge.net Wed Feb 12 15:39:18 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:39:18 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyBrowser.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv31767 Modified Files: PyBrowser.py Log Message: More int() around float arguments. Index: PyBrowser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyBrowser.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** PyBrowser.py 6 Feb 2003 22:32:35 -0000 1.22 --- PyBrowser.py 12 Feb 2003 15:39:16 -0000 1.23 *************** *** 92,96 **** l, t, r, b = cellRect cellwidth = r - l ! Qd.MoveTo(l + 2, t + ascent) condense, text = truncString(text, cellwidth - 3) if condense: --- 92,96 ---- l, t, r, b = cellRect cellwidth = r - l ! Qd.MoveTo(int(l + 2), int(t + ascent)) condense, text = truncString(text, cellwidth - 3) if condense: From jackjansen@users.sourceforge.net Wed Feb 12 15:40:00 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:40:00 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PackageManager.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv32097 Modified Files: PackageManager.py Log Message: Allow this to run both standalone and as a window in the IDE. Index: PackageManager.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PackageManager.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PackageManager.py 12 Feb 2003 12:47:56 -0000 1.1 --- PackageManager.py 12 Feb 2003 15:39:56 -0000 1.2 *************** *** 1,2 **** --- 1,36 ---- + # Prelude to allow running this as a main program + def _init(): + import macresource + import sys, os + macresource.need('DITL', 468, "PythonIDE.rsrc") + widgetrespathsegs = [sys.exec_prefix, "Mac", "Tools", "IDE", "Widgets.rsrc"] + widgetresfile = os.path.join(*widgetrespathsegs) + if not os.path.exists(widgetresfile): + widgetrespathsegs = [os.pardir, "Tools", "IDE", "Widgets.rsrc"] + widgetresfile = os.path.join(*widgetrespathsegs) + refno = macresource.need('CURS', 468, widgetresfile) + if os.environ.has_key('PYTHONIDEPATH'): + # For development set this environment variable + ide_path = os.environ['PYTHONIDEPATH'] + elif refno: + # We're not a fullblown application + idepathsegs = [sys.exec_prefix, "Mac", "Tools", "IDE"] + ide_path = os.path.join(*idepathsegs) + if not os.path.exists(ide_path): + idepathsegs = [os.pardir, "Tools", "IDE"] + for p in sys.path: + ide_path = os.path.join(*([p]+idepathsegs)) + if os.path.exists(ide_path): + break + + else: + # We are a fully frozen application + ide_path = sys.argv[0] + if ide_path not in sys.path: + sys.path.insert(0, ide_path) + + if __name__ == '__main__': + _init() + import W import Wapplication *************** *** 70,74 **** self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') self.makeopenwindowsmenu() ! self._menustocheck = [closeitem, saveasitem, undoitem, cutitem, copyitem, pasteitem, selallitem, --- 104,108 ---- self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') self.makeopenwindowsmenu() ! self._menustocheck = [closeitem, undoitem, cutitem, copyitem, pasteitem, selallitem, From jackjansen@users.sourceforge.net Wed Feb 12 15:42:53 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 07:42:53 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX Makefile,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv1174 Modified Files: Makefile Log Message: Use bundlebuilder directly to build applets. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/Makefile,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** Makefile 28 Jan 2003 21:45:44 -0000 1.33 --- Makefile 12 Feb 2003 15:42:49 -0000 1.34 *************** *** 47,52 **** CACHERSRC=$(srcdir)/Mac/scripts/cachersrc.py compileall=$(srcdir)/Lib/compileall.py ! installapps: install_PythonLauncher install_Python install_BuildApplet install_IDE install_IDLE install_PythonLauncher: --- 47,54 ---- CACHERSRC=$(srcdir)/Mac/scripts/cachersrc.py compileall=$(srcdir)/Lib/compileall.py + bundlebuilder=$(srcdir)/Lib/plat-mac/bundlebuilder.py ! installapps: install_PythonLauncher install_Python install_BuildApplet \ ! install_PackageManager install_IDE install_IDLE install_PythonLauncher: *************** *** 103,112 **** echo See Mac/OSX/README for details; \ else \ ! echo $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ ! --output $(PYTHONAPPSDIR)/PythonIDE.app --noargv \ ! $(srcdir)/Mac/Tools/IDE/PythonIDE.py ; \ ! $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ ! --output $(PYTHONAPPSDIR)/PythonIDE.app --noargv \ ! $(srcdir)/Mac/Tools/IDE/PythonIDE.py; \ fi --- 105,139 ---- echo See Mac/OSX/README for details; \ else \ ! echo $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PythonIDE.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PythonIDE.icns \ ! --creator Pide build; \ ! $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PythonIDE.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PythonIDE.icns \ ! --creator Pide build; \ ! fi ! ! install_PackageManager: $(INSTALLED_PYTHONW) ! @if ! $(INSTALLED_PYTHONW) -c "import waste"; then \ ! echo PackageManager needs the \"waste\" extension module; \ ! echo See Mac/OSX/README for details; \ ! else \ ! echo $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PackageManager.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PackageManager.icns \ ! --creator Pimp build; \ ! $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PackageManager.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PackageManager.icns \ ! --creator Pimp build; \ fi From jackjansen@users.sourceforge.net Wed Feb 12 16:16:56 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:16:56 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSXResources/iconsrc PackageManager.psd,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSXResources/iconsrc In directory sc8-pr-cvs1:/tmp/cvs-serv19225 Added Files: PackageManager.psd Log Message: Photoshop source file for package manager icon. --- NEW FILE: PackageManager.psd --- (This appears to be a binary file; contents omitted.) From jvr@users.sourceforge.net Wed Feb 12 16:19:43 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:19:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv20922/Lib/plat-mac Modified Files: bundlebuilder.py Log Message: Thank you sir, can I have another. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** bundlebuilder.py 2 Feb 2003 18:56:37 -0000 1.6 --- bundlebuilder.py 12 Feb 2003 16:19:39 -0000 1.7 *************** *** 256,263 **** execdir=$(dirname "${0}") ! executable=${execdir}/%(executable)s resdir=$(dirname "${execdir}")/Resources ! main=${resdir}/%(mainprogram)s ! PYTHONPATH=$resdir export PYTHONPATH exec "${executable}" "${main}" "${1}" --- 256,263 ---- execdir=$(dirname "${0}") ! executable="${execdir}/%(executable)s" resdir=$(dirname "${execdir}")/Resources ! main="${resdir}/%(mainprogram)s" ! PYTHONPATH="$resdir" export PYTHONPATH exec "${executable}" "${main}" "${1}" From jackjansen@users.sourceforge.net Wed Feb 12 16:20:28 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:20:28 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PackageManager.icns,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv21143 Added Files: PackageManager.icns Log Message: Icons for the package manager. --- NEW FILE: PackageManager.icns --- (This appears to be a binary file; contents omitted.) From theller@python.net Wed Feb 12 16:28:54 2003 From: theller@python.net (Thomas Heller) Date: 12 Feb 2003 17:28:54 +0100 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.7,1.8 In-Reply-To: References: Message-ID: jackjansen@users.sourceforge.net writes: > Update of /cvsroot/python/python/dist/src/Lib/plat-mac > In directory sc8-pr-cvs1:/tmp/cvs-serv29687 > > Modified Files: > pimp.py > Log Message: > - Better way to find site-packages > ! for _p in sys.path: > ! if _p[-13:] == 'site-packages': > ! DEFAULT_INSTALLDIR=_p > ! break > ! else: > ! DEFAULT_INSTALLDIR=sys.prefix # Have to put things somewhere Doesn't distutils expose this directory via sysconfig.get_python_lib() ? Thomas From jackjansen@users.sourceforge.net Wed Feb 12 16:37:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:37:03 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv28512 Modified Files: pimp.py Log Message: - Use distutils to find site-python (suggested by Thomas Heller, thanks!) - Fixed a bug for packages without MD5 checksum. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** pimp.py 12 Feb 2003 15:36:25 -0000 1.8 --- pimp.py 12 Feb 2003 16:37:00 -0000 1.9 *************** *** 19,22 **** --- 19,23 ---- import plistlib import distutils.util + import distutils.sysconfig import md5 *************** *** 34,43 **** DEFAULT_DOWNLOADDIR='/tmp' DEFAULT_BUILDDIR='/tmp' ! for _p in sys.path: ! if _p[-13:] == 'site-packages': ! DEFAULT_INSTALLDIR=_p ! break ! else: ! DEFAULT_INSTALLDIR=sys.prefix # Have to put things somewhere DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() --- 35,39 ---- DEFAULT_DOWNLOADDIR='/tmp' DEFAULT_BUILDDIR='/tmp' ! DEFAULT_INSTALLDIR=distutils.sysconfig.get_python_lib() DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() *************** *** 420,424 **** if not os.path.exists(self.archiveFilename): return 0 ! if not self._dict['MD5Sum']: sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 --- 416,420 ---- if not os.path.exists(self.archiveFilename): return 0 ! if not self._dict.get('MD5Sum'): sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname()) return 1 From gvanrossum@users.sourceforge.net Wed Feb 12 16:57:10 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:57:10 -0800 Subject: [Python-checkins] python/dist/src/Python compile.c,2.274,2.275 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv6029 Modified Files: compile.c Log Message: SF #660455 : patch by NNorwitz. "Unsigned" (i.e., positive-looking, but really negative) hex/oct constants with a leading minus sign are once again properly negated. The micro-optimization for negated numeric constants did the wrong thing for such hex/oct constants. The patch avoids the optimization for all hex/oct constants. This needs to be backported to Python 2.2! Index: compile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/compile.c,v retrieving revision 2.274 retrieving revision 2.275 diff -C2 -d -r2.274 -r2.275 *** compile.c 10 Feb 2003 08:21:10 -0000 2.274 --- compile.c 12 Feb 2003 16:56:51 -0000 2.275 *************** *** 2070,2074 **** && TYPE((patom = CHILD(ppower, 0))) == atom && TYPE((pnum = CHILD(patom, 0))) == NUMBER ! && !(childtype == MINUS && is_float_zero(STR(pnum)))) { if (childtype == TILDE) { com_invert_constant(c, pnum); --- 2070,2075 ---- && TYPE((patom = CHILD(ppower, 0))) == atom && TYPE((pnum = CHILD(patom, 0))) == NUMBER ! && !(childtype == MINUS && ! (STR(pnum)[0] == '0' || is_float_zero(STR(pnum))))) { if (childtype == TILDE) { com_invert_constant(c, pnum); From gvanrossum@users.sourceforge.net Wed Feb 12 16:57:49 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:57:49 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_compile.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6504a Modified Files: test_compile.py Log Message: SF #660455 : patch by NNorwitz. "Unsigned" (i.e., positive-looking, but really negative) hex/oct constants with a leading minus sign are once again properly negated. The micro-optimization for negated numeric constants did the wrong thing for such hex/oct constants. The patch avoids the optimization for all hex/oct constants. This needs to be backported to Python 2.2! Index: test_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_compile.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** test_compile.py 28 Jan 2003 20:39:49 -0000 1.14 --- test_compile.py 12 Feb 2003 16:57:47 -0000 1.15 *************** *** 134,141 **** expect_same("000000000000009.", 9.) ! ## # Verify treatment of unary minus on negative numbers SF bug #660455 ! ## import warnings ! ## warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) ! ## # XXX Of course the following test will have to be changed in Python 2.4 ! ## expect_same("0xffffffff", -1) ! ## expect_same("-0xffffffff", 1) --- 134,144 ---- expect_same("000000000000009.", 9.) ! # Verify treatment of unary minus on negative numbers SF bug #660455 ! import warnings ! warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) ! # XXX Of course the following test will have to be changed in Python 2.4 ! # This test is in a so the filterwarnings() can affect it ! exec """ ! expect_same("0xffffffff", -1) ! expect_same("-0xffffffff", 1) ! """ From gvanrossum@users.sourceforge.net Wed Feb 12 17:05:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 09:05:30 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.653,1.654 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv10299 Modified Files: NEWS Log Message: SF #660455 : patch by NNorwitz. "Unsigned" (i.e., positive-looking, but really negative) hex/oct constants with a leading minus sign are once again properly negated. The micro-optimization for negated numeric constants did the wrong thing for such hex/oct constants. The patch avoids the optimization for all hex/oct constants. This needs to be backported to Python 2.2! Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.653 retrieving revision 1.654 diff -C2 -d -r1.653 -r1.654 *** NEWS 12 Feb 2003 03:58:33 -0000 1.653 --- NEWS 12 Feb 2003 17:05:26 -0000 1.654 *************** *** 13,16 **** --- 13,28 ---- ----------------- + - Through a bytecode optimizer bug (and I bet you didn't even know + Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants + with a leading minus sign would come out with the wrong sign. + ("Unsigned" hex/oct constants are those with a face value in the + range sys.maxint+1 through sys.maxint*2+1, inclusive; these have + always been interpreted as negative numbers through sign folding.) + E.g. 0xffffffff is -1, and -(0xffffffff) is 1, but -0xffffffff would + come out as -4294967295. This was the case in Python 2.2 through + 2.2.2 and 2.3a1, and in Python 2.4 it will once again have that + value, but according to PEP 237 it really needs to be 1 now. This + will be backported to Python 2.2.3 a well. (SF #660455) + - super(X, x): x may now be a proxy for an X instance, i.e. issubclass(x.__class__, X) but not issubclass(type(x), X). From gvanrossum@users.sourceforge.net Wed Feb 12 17:09:20 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 09:09:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_hexoct.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12021 Added Files: test_hexoct.py Log Message: Systematic testing of hex/oct constants. --- NEW FILE: test_hexoct.py --- """Test correct treatment of hex/oct constants. This is complex because of changes due to PEP 237. Some of these tests will hvae to change in Python 2.4! """ import unittest from test import test_support import warnings warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning, "") class TextHexOct(unittest.TestCase): def test_hex_baseline(self): # Baseline tests self.assertEqual(0x0, 0) self.assertEqual(0x10, 16) self.assertEqual(0x7fffffff, 2147483647) # Ditto with a minus sign and parentheses self.assertEqual(-(0x0), 0) self.assertEqual(-(0x10), -16) self.assertEqual(-(0x7fffffff), -2147483647) # Ditto with a minus sign and NO parentheses self.assertEqual(-0x0, 0) self.assertEqual(-0x10, -16) self.assertEqual(-0x7fffffff, -2147483647) def test_hex_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: # Positive-looking constants with negavive values self.assertEqual(0x80000000, -2147483648L) self.assertEqual(0xffffffff, -1) # Ditto with a minus sign and parentheses self.assertEqual(-(0x80000000), 2147483648L) self.assertEqual(-(0xffffffff), 1) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-0x80000000, 2147483648L) self.assertEqual(-0xffffffff, 1) \n""" def test_oct_baseline(self): # Baseline tests self.assertEqual(00, 0) self.assertEqual(020, 16) self.assertEqual(017777777777, 2147483647) # Ditto with a minus sign and parentheses self.assertEqual(-(00), 0) self.assertEqual(-(020), -16) self.assertEqual(-(017777777777), -2147483647) # Ditto with a minus sign and NO parentheses self.assertEqual(-00, 0) self.assertEqual(-020, -16) self.assertEqual(-017777777777, -2147483647) def test_oct_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: # Positive-looking constants with negavive values self.assertEqual(020000000000, -2147483648L) self.assertEqual(037777777777, -1) # Ditto with a minus sign and parentheses self.assertEqual(-(020000000000), 2147483648L) self.assertEqual(-(037777777777), 1) # Ditto with a minus sign and NO parentheses # This failed in Python 2.2 through 2.2.2 and in 2.3a1 self.assertEqual(-020000000000, 2147483648L) self.assertEqual(-037777777777, 1) \n""" def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TextHexOct)) test_support.run_suite(suite) if __name__ == "__main__": test_main() From gvanrossum@users.sourceforge.net Wed Feb 12 16:57:34 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 08:57:34 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_grammar.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6400 Modified Files: test_grammar.py Log Message: SF #660455 : patch by NNorwitz. "Unsigned" (i.e., positive-looking, but really negative) hex/oct constants with a leading minus sign are once again properly negated. The micro-optimization for negated numeric constants did the wrong thing for such hex/oct constants. The patch avoids the optimization for all hex/oct constants. This needs to be backported to Python 2.2! Index: test_grammar.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_grammar.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** test_grammar.py 29 Aug 2002 14:57:26 -0000 1.44 --- test_grammar.py 12 Feb 2003 16:57:31 -0000 1.45 *************** *** 38,42 **** maxint = 2147483647 if maxint == 2147483647: ! if -2147483647-1 != -020000000000: raise TestFailed, 'max negative int' # XXX -2147483648 if 037777777777 != -1: raise TestFailed, 'oct -1' --- 38,44 ---- maxint = 2147483647 if maxint == 2147483647: ! # The following test will start to fail in Python 2.4; ! # change the 020000000000 to -020000000000 ! if -2147483647-1 != 020000000000: raise TestFailed, 'max negative int' # XXX -2147483648 if 037777777777 != -1: raise TestFailed, 'oct -1' From montanaro@users.sourceforge.net Wed Feb 12 17:37:54 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 12 Feb 2003 09:37:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv26079 Modified Files: libcsv.tex Log Message: rearranged the introduction and made lots of fiddly little changes to the main text. In particular, describe Dialect class and its attributes, then dumped the individual descriptions of the various parameters. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** libcsv.tex 10 Feb 2003 22:43:12 -0000 1.5 --- libcsv.tex 12 Feb 2003 17:37:49 -0000 1.6 *************** *** 7,41 **** \indexii{data}{tabular} - The \module{csv} module implements classes to read and write tabular data. The so-called CSV (Comma Separated Values) format is the most common import ! and export format for spreadsheets and databases. While the delimiters and ! quoting characters vary, the overall format is similar enough that it is ! possible to write a single module which can manipulate such data. ! ! There is no ``CSV standard'', so the format is operationally defined by the ! many applications which read and write it. The lack of a standard means ! there can be subtle differences in the data produced and consumed by ! different applications. These differences can it annoying to process CSV ! files from multiple sources. ! ! The \module{csv} module allows programmers to say, ``write this data in the ! format preferred by Excel (tm),'' without knowing all the fiddly little ! details of the CSV format used by Excel. Programmers can also easily define ! their own CSV formats. ! \subsection{Relationship to other Python modules} - The csv module reads and writes sequences. It can also read and write data - in dictionary form using the \class{DictReader} and \class{DictWriter} - classes. Sequence types other than lists and tuples (e.g. \code{array} - objects) can be written. To make it as easy as possible to interface with - modules which implement the DB API, the value None is written as the empty - string. While this isn't a reversible transformation, it makes it easier to - dump SQL NULL data values to CSV files without preprocessing the data - returned from a {}\code{cursor.fetch*()} call. \subsection{Module Contents} The \module{csv} module defines the following functions. --- 7,36 ---- \indexii{data}{tabular} The so-called CSV (Comma Separated Values) format is the most common import ! and export format for spreadsheets and databases. There is no ``CSV ! standard'', so the format is operationally defined by the many applications ! which read and write it. The lack of a standard means that subtle ! differences often exist in the data produced and consumed by different ! applications. These differences can make it annoying to process CSV files ! from multiple sources. Still, while the delimiters and quoting characters ! vary, the overall format is similar enough that it is possible to write a ! single module which can efficiently manipulate such data, hiding the details ! of reading and writing the data from the programmer. + The \module{csv} module implements classes to read and write tabular data in + CSV format. It allows programmers to say, ``write this data in the format + preferred by Excel,'' or ``read data from this file which was generated by + Excel,'' without knowing the precise details of the CSV format used by + Excel. Programmers can also describe the CSV formats understood by other + applications or define their own special-purpose CSV formats. ! The \module{csv} module's \class{reader} and \class{writer} objects read and ! write sequences. Programmers can also read and write data in dictionary ! form using the \class{DictReader} and {}\class{DictWriter} classes. \subsection{Module Contents} + The \module{csv} module defines the following functions. *************** *** 49,53 **** information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of ! these parameters. \end{funcdesc} --- 44,48 ---- information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of ! these parameters. All data read are returned as strings. \end{funcdesc} *************** *** 62,66 **** current dialect. For more information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. \end{funcdesc} --- 57,67 ---- current dialect. For more information about the dialect and formatting parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. To make it as easy as ! possible to interface with modules which implement the DB API, the value ! {}\constant{None} is written as the empty string. While this isn't a ! reversible transformation, it makes it easier to dump SQL NULL data values ! to CSV files without preprocessing the data returned from a ! {}\code{cursor.fetch*()} call. All other non-string data are stringified ! with \function{str} before being written. \end{funcdesc} *************** *** 70,75 **** \end{funcdesc} \begin{funcdesc}{get_dialect}{name} ! Return the dialect associated with \var{name}. A \exception{KeyError} is raised if \var{name} is not a registered dialect name. \end{funcdesc} --- 71,82 ---- \end{funcdesc} + \begin{funcdesc}{unregister_dialect}{name} + Delete the dialect associated with \var{name} from the dialect registry. An + \exception{Error} is raised if \var{name} is not a registered dialect + name. + \end{funcdesc} + \begin{funcdesc}{get_dialect}{name} ! Return the dialect associated with \var{name}. An \exception{Error} is raised if \var{name} is not a registered dialect name. \end{funcdesc} *************** *** 79,82 **** --- 86,90 ---- \end{funcdesc} + The \module{csv} module defines the following classes. *************** *** 97,100 **** --- 105,109 ---- \end{classdesc} + \begin{classdesc}{DictWriter}{fileobj, fieldnames \optional{, restval=""} *************** *** 115,123 **** \end{classdesc} - The \module{csv} module defines the following exception. ! \begin{excdesc}{Error} ! Raised by any of the functions when an error is detected. ! \end{excdesc} The \module{csv} module defines the following constants. --- 124,172 ---- \end{classdesc} ! \begin{classdesc}{Dialect}{} ! The \class{Dialect} class is a container class relied on primarily for its ! attributes, which are used to define the parameters for a specific ! \class{reader} or \class{writer} instance. ! \end{classdesc} ! ! \begin{memberdesc}[string]{delimiter} ! A one-character string used to separate fields. It defaults to \code{","}. ! \end{memberdesc} ! ! \begin{memberdesc}[boolean]{doublequote} ! Controls how instances of \var{quotechar} appearing inside a field should be ! themselves be quoted. When \constant{True}, the character is doubledd. ! When \constant{False}, the \var{escapechar} must be a one-character string ! which is used as a prefix to the \var{quotechar}. It defaults to ! \constant{True}. ! \end{memberdesc} ! ! \begin{memberdesc}{escapechar} ! A one-character string used to escape the \var{delimiter} if \var{quoting} ! is set to \constant{QUOTE_NONE}. It defaults to \constant{None}. ! \end{memberdesc} ! ! \begin{memberdesc}[string]{lineterminator} ! The string used to terminate lines in the CSV file. It defaults to ! \code{"\e r\e n"}. ! \end{memberdesc} ! ! \begin{memberdesc}[string]{quotechar} ! A one-character string used to quote elements containing the \var{delimiter} ! or which start with the \var{quotechar}. It defaults to \code{'"'}. ! \end{memberdesc} ! ! \begin{memberdesc}[integer]{quoting} ! Controls when quotes should be generated by the writer. It can take on any ! of the \code{QUOTE_*} constants defined below and defaults to ! \constant{QUOTE_MINIMAL}. ! \end{memberdesc} ! ! \begin{memberdesc}[boolean]{skipinitialspace} ! When \constant{True}, whitespace immediately following the \var{delimiter} ! is ignored. The default is \constant{False}. ! \end{memberdesc} ! The \module{csv} module defines the following constants. *************** *** 139,148 **** Instructs \class{writer} objects to never quote fields. When the current {}\var{delimiter} occurs in output data it is preceded by the current ! {}\var{escapechar} character. When QUOTE_NONE is in effect, it is an error ! not to have a single-character \var{escapechar} defined, even if no data to ! be written contains the \var{delimiter} character. \end{datadesc} \subsection{Dialects and Formatting Parameters\label{fmt-params}} --- 188,204 ---- Instructs \class{writer} objects to never quote fields. When the current {}\var{delimiter} occurs in output data it is preceded by the current ! {}\var{escapechar} character. When \constant{QUOTE_NONE} is in effect, it ! is an error not to have a single-character \var{escapechar} defined, even if ! no data to be written contains the \var{delimiter} character. \end{datadesc} + The \module{csv} module defines the following exception. + + \begin{excdesc}{Error} + Raised by any of the functions when an error is detected. + \end{excdesc} + + \subsection{Dialects and Formatting Parameters\label{fmt-params}} *************** *** 154,190 **** of the \class{Dialect} class as the dialect parameter. In addition to, or instead of, the \var{dialect} parameter, the programmer can also specify ! individual formatting parameters, described in the following section. ! ! ! \subsubsection{Formatting Parameters} ! ! Both the \class{reader} and \class{writer} classes take several specific ! formatting parameters, specified as keyword parameters. ! ! \begin{description} ! \item[quotechar]{specifies a one-character string to use as the quoting ! character. It defaults to \code{"}.} ! ! \item[delimiter]{specifies a one-character string to use as the field ! separator. It defaults to \code{,}.} ! ! \item[escapechar]{specifies a one-character string used to escape the ! delimiter when quotechar is set to \var{None}.} ! ! \item[skipinitialspace]{specifies how to interpret whitespace which ! immediately follows a delimiter. It defaults to False, which means ! that whitespace immediately following a delimiter is part of the ! following field.} ! ! \item[lineterminator]{specifies the character sequence which should ! terminate rows.} ! ! \item[quoting]{controls when quotes should be generated by the ! writer. It can take on any of the \code{QUOTE_*} constants defined above.} ! ! \item[doublequote]{controls the handling of quotes inside fields. When ! \var{True}, two consecutive quotes are interpreted as one during read, and ! when writing, each quote is written as two quotes.} ! \end{description} --- 210,215 ---- of the \class{Dialect} class as the dialect parameter. In addition to, or instead of, the \var{dialect} parameter, the programmer can also specify ! individual formatting parameters, which have the same names as the ! attributes defined above for the \class{Dialect} class. From gvanrossum@users.sourceforge.net Wed Feb 12 19:09:55 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 11:09:55 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.59,1.337.2.4.2.60 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv12781/Misc Modified Files: Tag: release22-maint NEWS Log Message: Backport SF #660455 fix. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.59 retrieving revision 1.337.2.4.2.60 diff -C2 -d -r1.337.2.4.2.59 -r1.337.2.4.2.60 *** NEWS 10 Feb 2003 01:57:50 -0000 1.337.2.4.2.59 --- NEWS 12 Feb 2003 19:09:45 -0000 1.337.2.4.2.60 *************** *** 3,6 **** --- 3,18 ---- ============================ + - Through a bytecode optimizer bug (and I bet you didn't even know + Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants + with a leading minus sign would come out with the wrong sign. + ("Unsigned" hex/oct constants are those with a face value in the + range sys.maxint+1 through sys.maxint*2+1, inclusive; these have + always been interpreted as negative numbers through sign folding.) + E.g. 0xffffffff is -1, and -(0xffffffff) is 1, but -0xffffffff would + come out as -4294967295. This was the case in Python 2.2 through + 2.2.2 and 2.3a1, and in Python 2.4 it will once again have that + value, but according to PEP 237 it really needs to be 1 in Python + 2.2.3 and 2.3. (SF #660455) + - SF bug #678518: fix some bugs in the parser module. From gvanrossum@users.sourceforge.net Wed Feb 12 19:10:16 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 11:10:16 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_compile.py,1.10,1.10.8.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12781/Lib/test Modified Files: Tag: release22-maint test_compile.py Log Message: Backport SF #660455 fix. Index: test_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_compile.py,v retrieving revision 1.10 retrieving revision 1.10.8.1 diff -C2 -d -r1.10 -r1.10.8.1 *** test_compile.py 13 Nov 2001 22:03:20 -0000 1.10 --- test_compile.py 12 Feb 2003 19:09:39 -0000 1.10.8.1 *************** *** 124,125 **** --- 124,129 ---- expect_same("000000000000008.", 8.) expect_same("000000000000009.", 9.) + + # Verify treatment of unary minus on negative numbers SF bug #660455 + expect_same("0xffffffff", -1) + expect_same("-0xffffffff", 1) From gvanrossum@users.sourceforge.net Wed Feb 12 19:10:18 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 11:10:18 -0800 Subject: [Python-checkins] python/dist/src/Python compile.c,2.234.4.5,2.234.4.6 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv12781/Python Modified Files: Tag: release22-maint compile.c Log Message: Backport SF #660455 fix. Index: compile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/compile.c,v retrieving revision 2.234.4.5 retrieving revision 2.234.4.6 diff -C2 -d -r2.234.4.5 -r2.234.4.6 *** compile.c 7 Oct 2002 11:30:07 -0000 2.234.4.5 --- compile.c 12 Feb 2003 19:09:41 -0000 2.234.4.6 *************** *** 1953,1957 **** && TYPE((patom = CHILD(ppower, 0))) == atom && TYPE((pnum = CHILD(patom, 0))) == NUMBER ! && !(childtype == MINUS && is_float_zero(STR(pnum)))) { if (childtype == TILDE) { com_invert_constant(c, pnum); --- 1953,1958 ---- && TYPE((patom = CHILD(ppower, 0))) == atom && TYPE((pnum = CHILD(patom, 0))) == NUMBER ! && !(childtype == MINUS && ! (STR(pnum)[0] == '0' || is_float_zero(STR(pnum))))) { if (childtype == TILDE) { com_invert_constant(c, pnum); From gvanrossum@users.sourceforge.net Wed Feb 12 20:40:12 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 12:40:12 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.123,1.124 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv17815 Modified Files: regrtest.py Log Message: Expect test_ossaudiodev to skip on Linux, too. (It's broken. Volunteers wanted to fix it!) Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.123 retrieving revision 1.124 diff -C2 -d -r1.123 -r1.124 *** regrtest.py 5 Feb 2003 16:46:01 -0000 1.123 --- regrtest.py 12 Feb 2003 20:40:08 -0000 1.124 *************** *** 594,597 **** --- 594,598 ---- test_nis test_ntpath + test_ossaudiodev test_socketserver test_sunaudiodev From gvanrossum@users.sourceforge.net Wed Feb 12 20:43:38 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 12:43:38 -0800 Subject: [Python-checkins] python/dist/src/Objects intobject.c,2.101,2.102 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv20340 Modified Files: intobject.c Log Message: Issue a warning when int('0...', 0) returns an int with the sign folded; this will change in Python 2.4. On a 32-bit machine, this happens for 0x80000000 through 0xffffffff, and for octal constants in the same value range. No warning is issued if an explicit base is given, *or* if the string contains a sign (since in those cases no sign folding ever happens). Index: intobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/intobject.c,v retrieving revision 2.101 retrieving revision 2.102 diff -C2 -d -r2.101 -r2.102 *** intobject.c 10 Feb 2003 02:12:42 -0000 2.101 --- intobject.c 12 Feb 2003 20:43:33 -0000 2.102 *************** *** 188,194 **** long x; char buffer[256]; /* For errors */ if ((base != 0 && base < 2) || base > 36) { ! PyErr_SetString(PyExc_ValueError, "int() base must be >= 2 and <= 36"); return NULL; } --- 188,196 ---- long x; char buffer[256]; /* For errors */ + int warn = 0; if ((base != 0 && base < 2) || base > 36) { ! PyErr_SetString(PyExc_ValueError, ! "int() base must be >= 2 and <= 36"); return NULL; } *************** *** 197,202 **** s++; errno = 0; ! if (base == 0 && s[0] == '0') x = (long) PyOS_strtoul(s, &end, base); else x = PyOS_strtol(s, &end, base); --- 199,207 ---- s++; errno = 0; ! if (base == 0 && s[0] == '0') { x = (long) PyOS_strtoul(s, &end, base); + if (x < 0) + warn = 1; + } else x = PyOS_strtol(s, &end, base); *************** *** 216,219 **** --- 221,229 ---- return NULL; return PyLong_FromString(s, pend, base); + } + if (warn) { + if (PyErr_Warn(PyExc_FutureWarning, + "int('0...', 0): sign will change in Python 2.4") < 0) + return NULL; } if (pend) From gvanrossum@users.sourceforge.net Wed Feb 12 20:48:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 12:48:30 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.654,1.655 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv24803 Modified Files: NEWS Log Message: Issue a warning when int('0...', 0) returns an int with the sign folded; this will change in Python 2.4. On a 32-bit machine, this happens for 0x80000000 through 0xffffffff, and for octal constants in the same value range. No warning is issued if an explicit base is given, *or* if the string contains a sign (since in those cases no sign folding ever happens). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.654 retrieving revision 1.655 diff -C2 -d -r1.654 -r1.655 *** NEWS 12 Feb 2003 17:05:26 -0000 1.654 --- NEWS 12 Feb 2003 20:48:22 -0000 1.655 *************** *** 11,15 **** Core and builtins ! ----------------- - Through a bytecode optimizer bug (and I bet you didn't even know --- 11,15 ---- Core and builtins ! ---------------- - Through a bytecode optimizer bug (and I bet you didn't even know *************** *** 24,27 **** --- 24,34 ---- value, but according to PEP 237 it really needs to be 1 now. This will be backported to Python 2.2.3 a well. (SF #660455) + + - int(s, base) sometimes sign-folds hex and oct constants; it only + does this when base is 0 and s.strip() starts with a '0'. When the + sign is actually folded, as in int("0xffffffff", 0) on a 32-bit + machine, which returns -1, a FutureWarning is now issued; in Python + 2.4, this will return 4294967295L, as do int("+0xffffffff", 0) and + int("0xffffffff", 16) right now. (PEP 347) - super(X, x): x may now be a proxy for an X instance, i.e. From gvanrossum@users.sourceforge.net Wed Feb 12 21:45:32 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 13:45:32 -0800 Subject: [Python-checkins] python/dist/src/Python import.c,2.216,2.217 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv1603 Modified Files: import.c Log Message: Provide access to the import lock, fixing SF bug #580952. This is mostly from SF patch #683257, but I had to change unlock_import() to return an error value to avoid fatal error. Should this be backported? The patch requested this, but it's a new feature. Index: import.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/import.c,v retrieving revision 2.216 retrieving revision 2.217 diff -C2 -d -r2.216 -r2.217 *** import.c 24 Jan 2003 16:15:45 -0000 2.216 --- import.c 12 Feb 2003 21:45:27 -0000 2.217 *************** *** 253,257 **** return; } ! if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) { PyThreadState *tstate = PyEval_SaveThread(); PyThread_acquire_lock(import_lock, 1); --- 253,258 ---- return; } ! if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) ! { PyThreadState *tstate = PyEval_SaveThread(); PyThread_acquire_lock(import_lock, 1); *************** *** 262,273 **** } ! static void unlock_import(void) { long me = PyThread_get_thread_ident(); if (me == -1) ! return; /* Too bad */ if (import_lock_thread != me) ! Py_FatalError("unlock_import: not holding the import lock"); import_lock_level--; if (import_lock_level == 0) { --- 263,274 ---- } ! static int unlock_import(void) { long me = PyThread_get_thread_ident(); if (me == -1) ! return 0; /* Too bad */ if (import_lock_thread != me) ! return -1; import_lock_level--; if (import_lock_level == 0) { *************** *** 275,278 **** --- 276,280 ---- PyThread_release_lock(import_lock); } + return 1; } *************** *** 280,284 **** #define lock_import() ! #define unlock_import() #endif --- 282,286 ---- #define lock_import() ! #define unlock_import() 0 #endif *************** *** 296,299 **** --- 298,327 ---- } + static PyObject * + imp_acquire_lock(PyObject *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":acquire_lock")) + return NULL; + #ifdef WITH_THREAD + lock_import(); + #endif + return Py_None; + } + + static PyObject * + imp_release_lock(PyObject *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":release_lock")) + return NULL; + #ifdef WITH_THREAD + if (unlock_import() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + #endif + return Py_None; + } + /* Helper for sys */ *************** *** 1971,1975 **** lock_import(); result = import_module_ex(name, globals, locals, fromlist); ! unlock_import(); return result; } --- 1999,2008 ---- lock_import(); result = import_module_ex(name, globals, locals, fromlist); ! if (unlock_import() < 0) { ! Py_XDECREF(result); ! PyErr_SetString(PyExc_RuntimeError, ! "not holding the import lock"); ! return NULL; ! } return result; } *************** *** 2744,2747 **** --- 2777,2791 ---- On platforms without threads, return 0."); + PyDoc_STRVAR(doc_acquire_lock, + "acquire_lock() -> None\n\ + Acquires the interpreter's import lock for the current thread. This lock + should be used by import hooks to ensure thread-safety when importing modules. + On platforms without threads, this function does nothing."); + + PyDoc_STRVAR(doc_release_lock, + "release_lock() -> None\n\ + Release the interpreter's import lock.\n\ + On platforms without threads, this function does nothing."); + static PyMethodDef imp_methods[] = { {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, *************** *** 2751,2754 **** --- 2795,2800 ---- {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, {"lock_held", imp_lock_held, METH_VARARGS, doc_lock_held}, + {"acquire_lock", imp_acquire_lock, METH_VARARGS, doc_acquire_lock}, + {"release_lock", imp_release_lock, METH_VARARGS, doc_release_lock}, /* The rest are obsolete */ {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, From gvanrossum@users.sourceforge.net Wed Feb 12 21:46:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 13:46:15 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.655,1.656 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv1904 Modified Files: NEWS Log Message: Provide access to the import lock, fixing SF bug #580952. This is mostly from SF patch #683257, but I had to change unlock_import() to return an error value to avoid fatal error. Should this be backported? The patch requested this, but it's a new feature. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.655 retrieving revision 1.656 diff -C2 -d -r1.655 -r1.656 *** NEWS 12 Feb 2003 20:48:22 -0000 1.655 --- NEWS 12 Feb 2003 21:46:11 -0000 1.656 *************** *** 11,15 **** Core and builtins ! ---------------- - Through a bytecode optimizer bug (and I bet you didn't even know --- 11,15 ---- Core and builtins ! ----------------- - Through a bytecode optimizer bug (and I bet you didn't even know *************** *** 75,78 **** --- 75,84 ---- Extension modules ----------------- + + - The imp module now has ways to acquire and release the "import + lock": imp.acquire_lock() and imp.release_lock(). Note: this is a + reentrant lock, so releasing the lock only truly releases it when + this is the last release_lock() call. You can check with + imp.lock_held(). (SF bug #580952 and patch #683257.) - Fix some bugs in the parser module. SF bug #678518. From nnorwitz@users.sourceforge.net Wed Feb 12 23:02:24 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:02:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_imp.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2792/Lib/test Added Files: test_imp.py Log Message: Cleanup from patch #683257: Add missing INCREFs and re-indent returns to be consistent. Add \n\ for lines in docstring Add a pathetic test Add docs --- NEW FILE: test_imp.py --- import imp import unittest from test_support import TestFailed class ImpLock(unittest.TestCase): # XXX this test is woefully inadequate, please fix me def testLock(self): LOOPS = 50 for i in range(LOOPS): imp.acquire_lock() for i in range(LOOPS): imp.release_lock() for i in range(LOOPS): try: imp.release_lock() except RuntimeError: pass else: raise TestFailed, \ "release_lock() without lock should raise RuntimeError" if __name__ == "__main__": test_support.run_unittest(ImpLock) From nnorwitz@users.sourceforge.net Wed Feb 12 23:02:24 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:02:24 -0800 Subject: [Python-checkins] python/dist/src/Python import.c,2.217,2.218 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv2792/Python Modified Files: import.c Log Message: Cleanup from patch #683257: Add missing INCREFs and re-indent returns to be consistent. Add \n\ for lines in docstring Add a pathetic test Add docs Index: import.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/import.c,v retrieving revision 2.217 retrieving revision 2.218 diff -C2 -d -r2.217 -r2.218 *** import.c 12 Feb 2003 21:45:27 -0000 2.217 --- import.c 12 Feb 2003 23:02:19 -0000 2.218 *************** *** 306,310 **** lock_import(); #endif ! return Py_None; } --- 306,311 ---- lock_import(); #endif ! Py_INCREF(Py_None); ! return Py_None; } *************** *** 321,325 **** } #endif ! return Py_None; } --- 322,327 ---- } #endif ! Py_INCREF(Py_None); ! return Py_None; } *************** *** 2779,2784 **** PyDoc_STRVAR(doc_acquire_lock, "acquire_lock() -> None\n\ ! Acquires the interpreter's import lock for the current thread. This lock ! should be used by import hooks to ensure thread-safety when importing modules. On platforms without threads, this function does nothing."); --- 2781,2787 ---- PyDoc_STRVAR(doc_acquire_lock, "acquire_lock() -> None\n\ ! Acquires the interpreter's import lock for the current thread.\n\ ! This lock should be used by import hooks to ensure thread-safety\n\ ! when importing modules.\n\ On platforms without threads, this function does nothing."); From nnorwitz@users.sourceforge.net Wed Feb 12 23:02:56 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:02:56 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libimp.tex,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv2792/Doc/lib Modified Files: libimp.tex Log Message: Cleanup from patch #683257: Add missing INCREFs and re-indent returns to be consistent. Add \n\ for lines in docstring Add a pathetic test Add docs Index: libimp.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libimp.tex,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** libimp.tex 25 Dec 2002 23:13:34 -0000 1.34 --- libimp.tex 12 Feb 2003 23:02:18 -0000 1.35 *************** *** 107,110 **** --- 107,123 ---- \end{funcdesc} + \begin{funcdesc}{acquire_lock}{} + Acquires the interpreter's import lock for the current thread. This lock + should be used by import hooks to ensure thread-safety when importing modules. + On platforms without threads, this function does nothing. + \versionadded{2.3} + \end{funcdesc} + + \begin{funcdesc}{release_lock}{} + Release the interpreter's import lock. + On platforms without threads, this function does nothing. + \versionadded{2.3} + \end{funcdesc} + The following constants with integer values, defined in this module, are used to indicate the search result of \function{find_module()}. From gvanrossum@users.sourceforge.net Wed Feb 12 23:08:25 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:08:25 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.252,1.253 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv5865 Modified Files: socketmodule.c Log Message: Addressing SF bug #643005, implement socket.inet_aton() using inet_aton() rather than inet_addr() -- the latter is obsolete because it has a problem: "255.255.255.255" is a valid address but indistinguishable from an error. (I'm not sure if inet_aton() exists everywhere -- in case it doesn't, I've left the old code in with an #ifdef.) Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.252 retrieving revision 1.253 diff -C2 -d -r1.252 -r1.253 *** socketmodule.c 31 Jan 2003 18:15:58 -0000 1.252 --- socketmodule.c 12 Feb 2003 23:08:22 -0000 1.253 *************** *** 2714,2722 **** /* Have to use inet_addr() instead */ char *ip_addr; ! unsigned long packed_addr; if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) { return NULL; } packed_addr = inet_addr(ip_addr); --- 2714,2737 ---- /* Have to use inet_addr() instead */ char *ip_addr; ! #if 1 ! struct in_addr buf; if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) { return NULL; } + + if (inet_aton(ip_addr, &buf)) + return PyString_FromStringAndSize((char *)(&buf), + sizeof(buf)); + + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; + + #else /* In case you don't have inet_aton() */ + /* XXX Problem here: inet_aton('255.255.255.255') raises + an exception while it should be a valid address. */ + unsigned long packed_addr; + packed_addr = inet_addr(ip_addr); *************** *** 2729,2732 **** --- 2744,2748 ---- return PyString_FromStringAndSize((char *) &packed_addr, sizeof(packed_addr)); + #endif } From nnorwitz@users.sourceforge.net Wed Feb 12 23:09:56 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:09:56 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_bz2.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6508/Lib/test Modified Files: test_bz2.py Log Message: Add test to ensure files (fds) don't leak Index: test_bz2.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_bz2.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_bz2.py 31 Dec 2002 11:28:22 -0000 1.11 --- test_bz2.py 12 Feb 2003 23:09:53 -0000 1.12 *************** *** 219,222 **** --- 219,228 ---- bz2f.close() + def testOpenDel(self): + self.createTempFile() + for i in xrange(10000): + o = BZ2File(self.filename) + del o + class BZ2CompressorTest(BaseTest): def testCompress(self): From doerwalter@users.sourceforge.net Wed Feb 12 23:49:59 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Wed, 12 Feb 2003 15:49:59 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_hexoct.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23838/Lib/test Modified Files: test_hexoct.py Log Message: Fix typo. Index: test_hexoct.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_hexoct.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_hexoct.py 12 Feb 2003 17:09:17 -0000 1.1 --- test_hexoct.py 12 Feb 2003 23:49:57 -0000 1.2 *************** *** 3,7 **** This is complex because of changes due to PEP 237. ! Some of these tests will hvae to change in Python 2.4! """ --- 3,7 ---- This is complex because of changes due to PEP 237. ! Some of these tests will have to change in Python 2.4! """ From nnorwitz@users.sourceforge.net Thu Feb 13 02:11:12 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 18:11:12 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.253,1.254 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv18177/Modules Modified Files: socketmodule.c Log Message: Use configure to check for inet_aton. Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.253 retrieving revision 1.254 diff -C2 -d -r1.253 -r1.254 *** socketmodule.c 12 Feb 2003 23:08:22 -0000 1.253 --- socketmodule.c 13 Feb 2003 02:11:10 -0000 1.254 *************** *** 2714,2718 **** /* Have to use inet_addr() instead */ char *ip_addr; ! #if 1 struct in_addr buf; --- 2714,2718 ---- /* Have to use inet_addr() instead */ char *ip_addr; ! #if HAVE_INET_ATON struct in_addr buf; From nnorwitz@users.sourceforge.net Thu Feb 13 02:11:13 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 18:11:13 -0800 Subject: [Python-checkins] python/dist/src configure.in,1.387,1.388 configure,1.376,1.377 pyconfig.h.in,1.70,1.71 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv18177 Modified Files: configure.in configure pyconfig.h.in Log Message: Use configure to check for inet_aton. Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.387 retrieving revision 1.388 diff -C2 -d -r1.387 -r1.388 *** configure.in 21 Jan 2003 10:14:40 -0000 1.387 --- configure.in 13 Feb 2003 02:11:06 -0000 1.388 *************** *** 1842,1846 **** gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getwd \ ! hstrerror inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink \ --- 1842,1846 ---- gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getwd \ ! hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink \ Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.376 retrieving revision 1.377 diff -C2 -d -r1.376 -r1.377 *** configure 21 Jan 2003 10:14:39 -0000 1.376 --- configure 13 Feb 2003 02:11:07 -0000 1.377 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.386 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.387 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 12095,12103 **** for ac_func in alarm chown clock confstr ctermid execv \ fchdir flock fork fsync fdatasync fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getwd \ ! hstrerror inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink \ --- 12095,12104 ---- + for ac_func in alarm chown clock confstr ctermid execv \ fchdir flock fork fsync fdatasync fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ getpriority getpwent getwd \ ! hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ putenv readlink \ Index: pyconfig.h.in =================================================================== RCS file: /cvsroot/python/python/dist/src/pyconfig.h.in,v retrieving revision 1.70 retrieving revision 1.71 diff -C2 -d -r1.70 -r1.71 *** pyconfig.h.in 21 Jan 2003 10:14:40 -0000 1.70 --- pyconfig.h.in 13 Feb 2003 02:11:09 -0000 1.71 *************** *** 208,211 **** --- 208,214 ---- #undef HAVE_HYPOT + /* Define to 1 if you have the `inet_aton' function. */ + #undef HAVE_INET_ATON + /* Define to 1 if you have the `inet_pton' function. */ #undef HAVE_INET_PTON From nnorwitz@users.sourceforge.net Thu Feb 13 02:15:45 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 18:15:45 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.254,1.255 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv22404/Modules Modified Files: socketmodule.c Log Message: Ummm, try to get it right this time Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.254 retrieving revision 1.255 diff -C2 -d -r1.254 -r1.255 *** socketmodule.c 13 Feb 2003 02:11:10 -0000 1.254 --- socketmodule.c 13 Feb 2003 02:15:42 -0000 1.255 *************** *** 2714,2718 **** /* Have to use inet_addr() instead */ char *ip_addr; ! #if HAVE_INET_ATON struct in_addr buf; --- 2714,2718 ---- /* Have to use inet_addr() instead */ char *ip_addr; ! #ifdef HAVE_INET_ATON struct in_addr buf; From nnorwitz@users.sourceforge.net Thu Feb 13 03:01:22 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Wed, 12 Feb 2003 19:01:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/test re_tests.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv5597/Lib/test Modified Files: re_tests.py Log Message: SF patch #682432, add lookbehind tests Index: re_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/re_tests.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** re_tests.py 6 Nov 2002 14:06:52 -0000 1.31 --- re_tests.py 13 Feb 2003 03:01:18 -0000 1.32 *************** *** 549,552 **** --- 549,559 ---- ('^(.+)?B', 'AB', SUCCEED, 'g1', 'A'), + # lookbehind: split by : but not if it is escaped by -. + ('(? Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv9238/Doc/lib Modified Files: libpickle.tex Log Message: Try to doc the new pickle details being implemented as part of PEP 307. Needs review. Index: libpickle.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpickle.tex,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** libpickle.tex 27 Nov 2002 05:26:46 -0000 1.38 --- libpickle.tex 13 Feb 2003 03:12:48 -0000 1.39 *************** *** 127,134 **** the pickled file with a standard text editor. A binary format, which is slightly more efficient, can be chosen by specifying a true value for the \var{bin} argument to the \class{Pickler} constructor or the \function{dump()} and \function{dumps()} ! functions. \subsection{Usage} --- 127,159 ---- the pickled file with a standard text editor. + There are currently 3 different protocols which can be used for pickling. + + \begin{itemize} + + \item Protocol version 0 is the original ASCII protocol and is backwards + compatible with earlier versions of Python. + + \item Protocol version 1 is the old binary format which is also compatible + with earlier versions of Python. + + \item Protocol version 2 was introduced in Python 2.3. It provides + much more efficient pickling of new-style classes. + + \end{itemize} + + Refer to PEP 307 for more information. + + If a \var{protocol} is not specified, protocol 0 is used. + If \var{protocol} is specified as a negative value, + the highest protocol version will be used. + + \versionchanged[The \var{bin} parameter is deprecated and only provided + for backwards compatibility. You should use the \var{protocol} + parameter instead]{2.3} + A binary format, which is slightly more efficient, can be chosen by specifying a true value for the \var{bin} argument to the \class{Pickler} constructor or the \function{dump()} and \function{dumps()} ! functions. A \var{protocol} version >= 1 implies use of a binary format. \subsection{Usage} *************** *** 140,147 **** following functions to make this process more convenient: ! \begin{funcdesc}{dump}{object, file\optional{, bin}} Write a pickled representation of \var{object} to the open file object \var{file}. This is equivalent to ! \code{Pickler(\var{file}, \var{bin}).dump(\var{object})}. If the optional \var{bin} argument is true, the binary pickle format is used; otherwise the (less efficient) text pickle format is used --- 165,182 ---- following functions to make this process more convenient: ! \begin{funcdesc}{dump}{object, file\optional{, protocol\optional{, bin}}} Write a pickled representation of \var{object} to the open file object \var{file}. This is equivalent to ! \code{Pickler(\var{file}, \var{protocol}, \var{bin}).dump(\var{object})}. ! ! If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value, ! the highest protocol version will be used. ! ! \versionchanged[The \var{protocol} parameter was added. ! The \var{bin} parameter is deprecated and only provided ! for backwards compatibility. You should use the \var{protocol} ! parameter instead]{2.3} ! If the optional \var{bin} argument is true, the binary pickle format is used; otherwise the (less efficient) text pickle format is used *************** *** 170,176 **** \end{funcdesc} ! \begin{funcdesc}{dumps}{object\optional{, bin}} Return the pickled representation of the object as a string, instead ! of writing it to a file. If the optional \var{bin} argument is true, the binary pickle format is used; otherwise the (less efficient) text pickle format is used (this is the default). --- 205,222 ---- \end{funcdesc} ! \begin{funcdesc}{dumps}{object\optional{, protocol\optional{, bin}}} Return the pickled representation of the object as a string, instead ! of writing it to a file. ! ! If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value, ! the highest protocol version will be used. ! ! \versionchanged[The \var{protocol} parameter was added. ! The \var{bin} parameter is deprecated and only provided ! for backwards compatibility. You should use the \var{protocol} ! parameter instead]{2.3} ! ! If the optional \var{bin} argument is true, the binary pickle format is used; otherwise the (less efficient) text pickle format is used (this is the default). *************** *** 211,217 **** \class{Unpickler}: ! \begin{classdesc}{Pickler}{file\optional{, bin}} This takes a file-like object to which it will write a pickle data ! stream. Optional \var{bin} if true, tells the pickler to use the more efficient binary pickle format, otherwise the \ASCII{} format is used (this is the default). --- 257,273 ---- \class{Unpickler}: ! \begin{classdesc}{Pickler}{file\optional{, protocol\optional{, bin}}} This takes a file-like object to which it will write a pickle data ! stream. ! ! If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value, ! the highest protocol version will be used. ! ! \versionchanged[The \var{bin} parameter is deprecated and only provided ! for backwards compatibility. You should use the \var{protocol} ! parameter instead]{2.3} ! ! Optional \var{bin} if true, tells the pickler to use the more efficient binary pickle format, otherwise the \ASCII{} format is used (this is the default). From tim_one@users.sourceforge.net Thu Feb 13 03:13:42 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 12 Feb 2003 19:13:42 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.255,1.256 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9223/python/Modules Modified Files: socketmodule.c Log Message: socket_inet_aton(): ip_addr was left undefined before use in the !HAVE_INET_ATON case. Repaired that, and tried to repair what looked like out-of-date comments. Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.255 retrieving revision 1.256 diff -C2 -d -r1.255 -r1.256 *** socketmodule.c 13 Feb 2003 02:15:42 -0000 1.255 --- socketmodule.c 13 Feb 2003 03:13:40 -0000 1.256 *************** *** 2711,2724 **** #define INADDR_NONE (-1) #endif - - /* Have to use inet_addr() instead */ - char *ip_addr; #ifdef HAVE_INET_ATON struct in_addr buf; ! if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) { return NULL; - } if (inet_aton(ip_addr, &buf)) return PyString_FromStringAndSize((char *)(&buf), --- 2711,2727 ---- #define INADDR_NONE (-1) #endif #ifdef HAVE_INET_ATON struct in_addr buf; + #else + /* Have to use inet_addr() instead */ + unsigned long packed_addr; + #endif + char *ip_addr; ! if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) return NULL; + + #ifdef HAVE_INET_ATON if (inet_aton(ip_addr, &buf)) return PyString_FromStringAndSize((char *)(&buf), *************** *** 2729,2737 **** return NULL; ! #else /* In case you don't have inet_aton() */ /* XXX Problem here: inet_aton('255.255.255.255') raises an exception while it should be a valid address. */ - unsigned long packed_addr; - packed_addr = inet_addr(ip_addr); --- 2732,2738 ---- return NULL; ! #else /* ! HAVE_INET_ATON */ /* XXX Problem here: inet_aton('255.255.255.255') raises an exception while it should be a valid address. */ packed_addr = inet_addr(ip_addr); *************** *** 2741,2745 **** return NULL; } - return PyString_FromStringAndSize((char *) &packed_addr, sizeof(packed_addr)); --- 2742,2745 ---- From rhettinger@users.sourceforge.net Thu Feb 13 07:00:00 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Wed, 12 Feb 2003 23:00:00 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.17,1.18 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv12342 Modified Files: pep-0308.txt Log Message: Amended the PEP to reflect some convergence on the newgroup: * Listed the downsides of the current proposal. * Listed why ' then else ' is starting to be preferred over ' and or '. * After BDFL comments, I withdrew my proposed c??a||b syntax and deleted the rejected c?a!b syntax. The remaining punctuation based contender is c?a:b. * After BDFL rejection of non-short-circuiting options, advocacy dropped sharply. Removed it from the list of contenders. The leading options on the table are: * (if : else: ) * then else * ? : * no change Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** pep-0308.txt 12 Feb 2003 12:35:59 -0000 1.17 --- pep-0308.txt 13 Feb 2003 06:59:58 -0000 1.18 *************** *** 56,59 **** --- 56,65 ---- This will be implemented if the proposal is accepted. + The downsides to the proposal are: + + * the required parentheses + * confusability with statement syntax + * additional semantic loading of colons + Note that at most one of and is evaluated. This is called a "short-circuit expression"; it is *************** *** 73,87 **** Alternatives - The original version of this PEP proposed the following syntax: - - if else - - The out-of-order arrangement was found to be too uncomfortable - for many of participants in the discussion; especially when - is long, it's easy to miss the conditional while - skimming. - - --- - Holger Krekel proposed a new, minimally invasive variant: --- 79,82 ---- *************** *** 93,102 **** newsgroup found this to be the most pleasing alternative. However, a couple of respondants were able to post examples ! that were mentally difficult to parse. ! Christian Tismer proposed a variant of the same idea: then else --- --- 88,108 ---- newsgroup found this to be the most pleasing alternative. However, a couple of respondants were able to post examples ! that were mentally difficult to parse. Later it was pointed ! out that this construct works by having the "else" change the ! existing meaning of "and". ! As a result, there is increasing support for Christian Tismer's ! proposed variant of the same idea: then else + The advantages are simple visual parsing, no required parenthesis, + no change in the semantics of existing keywords, not as likely + as the proposal to be confused with statement syntax, and does + not further overload the colon. The disadvantage is the + implementation costs of introducing a new keyword. However, + unlike other new keywords, the word "then" seems unlikely to + have been used as a name in existing programs. + --- *************** *** 113,142 **** --- ! David Ascher proposed a variant that doesn't have this problem: ! ! ? ! ! ! While cute, this suffers from the Perlish problem of using ! arbitrary punctuation with an arbitrary meaning; and it's no ! easier to understand than the ?: form. ! ! --- ! ! Raymond Hettinger proposed a variant that removes the ! arbitrariness: ! ?? || ! The ?? and || are not arbitrary as they strongly suggest testing ! and alternation. Another merit is that that existing operators ! are not overloaded. Having two characters at each step also helps ! visually separate the subordinate expressions. Alas, the BDFL ! prefers the proposed syntax and considers this alternative "too ! Perlish". --- ! Many people suggest adding a new builtin instead of extending the ! syntax of the language, e.g.: cond(, , ) --- 119,135 ---- --- ! The original version of this PEP proposed the following syntax: ! if else ! The out-of-order arrangement was found to be too uncomfortable ! for many of participants in the discussion; especially when ! is long, it's easy to miss the conditional while ! skimming. --- ! Some have suggested adding a new builtin instead of extending the ! syntax of the language. For example: cond(, , ) *************** *** 154,174 **** Summary of the Current State of the Discussion ! Groups are falling into one of five camps: ! 1. Adopt a ternary operator built using punctuation characters. ! It would look something like: ! ?? || ! 2. Adopt a ternary operator built using existing keywords. ! The proposal listed above is the leading example. ! 3. Adopt a ternary operator built using a new keyword. ! The leading contender looks like this: ! cond(, , ) ! 4. Adopt a function without short-circuit behavior: ! cond(, , ) ! 5. Do nothing. The first two positions are relatively similar. --- 147,163 ---- Summary of the Current State of the Discussion ! Groups are falling into one of three camps: ! 1. Adopt a ternary operator built using punctuation characters: ! ? : ! 2. Adopt a ternary operator built using new or existing keywords. ! The leading examples are: ! then else ! (if : else: ) ! 3. Do nothing. The first two positions are relatively similar. *************** *** 185,211 **** confusion between the two meanings and two usages of the keywords. ! The third form introduces a new keyword and arranges the arguments ! separated by commas. Adding a new keyword is to be generally ! avoided. But the form is clear, short, and direct. There is a ! possible confusion with function syntax which implies that all the ! arguments are evaluated rather than short-circuited. This idea ! was presented by the BDFL and should be considered a contender for ! the final vote. The exact keyword is still an open question. One ! proposal was iif(), but it looks like a typo and can be confused ! with if-and-only-if which has a different, well-defined ! mathematical meaning. ! ! The fourth position is much more conservative. Adding a new ! function, cond(), is trivially easy to implement and fits easily ! within the existing python model. Users of older versions of ! Python will find it trivial to simulate. The downside is that it ! does not provide the sought-after short-circuit evaluation (see ! the discussion below on the need for this). The bigger downside ! is that the BDFL opposes *any* solution that does not provide ! short circuit behavior. The last position is doing nothing. Arguments in favor include keeping the language simple and concise; maintaining backwards ! compatibility; and that any every use cases can already be already expressed in terms of "if" and "else". Lambda expressions are an exception as they require the conditional to be factored out into --- 174,183 ---- confusion between the two meanings and two usages of the keywords. ! Those difficulties are overcome by options which introduce new ! keywords which take more effort to implement. The last position is doing nothing. Arguments in favor include keeping the language simple and concise; maintaining backwards ! compatibility; and that any every use case can already be already expressed in terms of "if" and "else". Lambda expressions are an exception as they require the conditional to be factored out into *************** *** 215,224 **** allow greater economy of expression and that current practices show a propensity for erroneous uses of "and", "or", or one their ! more complex, visually unappealing workarounds. ! ! It should also be mentioned that most supporters of any of the ! first four positions do not want an imperfect solution and would ! sooner have no change than create a wart to attain their desired ! functionality. --- 187,191 ---- allow greater economy of expression and that current practices show a propensity for erroneous uses of "and", "or", or one their ! more complex, less visually unappealing workarounds. *************** *** 237,242 **** # Example where all three reasons apply ! data = isinstance(source, file) ?? source.readlines() ! || source.split() 1. readlines() moves the file pointer --- 204,209 ---- # Example where all three reasons apply ! data = isinstance(source, file) ? source.readlines() ! : source.split() 1. readlines() moves the file pointer *************** *** 245,249 **** valid for file objects. ! Supporters of the cond() function point-out that the need for short-circuit evaluation is rare. Scanning through existing code directories, they found that if/else did not occur often; and of --- 212,216 ---- valid for file objects. ! Supporters of a cond() function point-out that the need for short-circuit evaluation is rare. Scanning through existing code directories, they found that if/else did not occur often; and of From mhammond@users.sourceforge.net Thu Feb 13 12:05:17 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Thu, 13 Feb 2003 04:05:17 -0800 Subject: [Python-checkins] python/dist/src/PCbuild _ssl.dsp,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv16534 Modified Files: _ssl.dsp Log Message: Use python_d.exe to build _ssl_d.pyd - we can not express that we depend on a release 'python.exe' for a debug build of _ssl. It may happen that Python.exe is currently broken, and we are trying to rebuild from scratch. Index: _ssl.dsp =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/_ssl.dsp,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _ssl.dsp 3 Dec 2002 05:47:26 -0000 1.1 --- _ssl.dsp 13 Feb 2003 12:05:15 -0000 1.2 *************** *** 63,67 **** # PROP Output_Dir "." # PROP Intermediate_Dir "x86-temp-debug\_ssl" ! # PROP Cmd_Line "python -u build_ssl.py -d" # PROP Rebuild_Opt "-a" # PROP Target_File "_ssl_d.pyd" --- 63,67 ---- # PROP Output_Dir "." # PROP Intermediate_Dir "x86-temp-debug\_ssl" ! # PROP Cmd_Line "python_d -u build_ssl.py -d" # PROP Rebuild_Opt "-a" # PROP Target_File "_ssl_d.pyd" From akuchling@users.sourceforge.net Thu Feb 13 13:27:09 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 13 Feb 2003 05:27:09 -0800 Subject: [Python-checkins] python/dist/src/Modules ossaudiodev.c,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv17886 Modified Files: ossaudiodev.c Log Message: Conditionalize another constant Index: ossaudiodev.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/ossaudiodev.c,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** ossaudiodev.c 2 Feb 2003 17:59:06 -0000 1.22 --- ossaudiodev.c 13 Feb 2003 13:27:07 -0000 1.23 *************** *** 965,969 **** --- 965,971 ---- _EXPORT_INT(m, AFMT_U16_BE); _EXPORT_INT(m, AFMT_MPEG); + #ifdef AFMT_AC3 _EXPORT_INT(m, AFMT_AC3); + #endif #ifdef AFMT_S16_NE _EXPORT_INT(m, AFMT_S16_NE); From gvanrossum@users.sourceforge.net Thu Feb 13 15:02:00 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 07:02:00 -0800 Subject: [Python-checkins] python/nondist/peps pep-0308.txt,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv23947 Modified Files: pep-0308.txt Log Message: Avoid 'I' now there's more than one author. Other minor nits. Index: pep-0308.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0308.txt,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** pep-0308.txt 13 Feb 2003 06:59:58 -0000 1.18 --- pep-0308.txt 13 Feb 2003 15:01:53 -0000 1.19 *************** *** 3,7 **** Version: $Revision$ Last-Modified: $Date$ ! Author: Guido van Rossum and Raymond D. Hettinger Status: Draft Type: Standards Track --- 3,7 ---- Version: $Revision$ Last-Modified: $Date$ ! Author: Guido van Rossum, Raymond D. Hettinger Status: Draft Type: Standards Track *************** *** 19,25 **** in Python 2.4. If not, the PEP will be augmented with a summary of the reasons for rejection and the subject better not come up ! again. While I am the author of this PEP, I am neither in favor ! nor against this proposal; it is up to the community to decide. ! If the community can't decide, I'll reject the PEP. After unprecedented community response (very good arguments were --- 19,26 ---- in Python 2.4. If not, the PEP will be augmented with a summary of the reasons for rejection and the subject better not come up ! again. While the BDFL is co-author of this PEP, he is neither in ! favor nor against this proposal; it is up to the community to ! decide. If the community can't decide, the BDFL will reject the ! PEP. After unprecedented community response (very good arguments were *************** *** 212,216 **** valid for file objects. ! Supporters of a cond() function point-out that the need for short-circuit evaluation is rare. Scanning through existing code directories, they found that if/else did not occur often; and of --- 213,217 ---- valid for file objects. ! Supporters of a cond() function point out that the need for short-circuit evaluation is rare. Scanning through existing code directories, they found that if/else did not occur often; and of From tim_one@users.sourceforge.net Thu Feb 13 15:44:48 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 07:44:48 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.130,2.131 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv24734/Modules Modified Files: cPickle.c Log Message: Added a HIGHEST_PROTOCOL module attribute to pickle and cPickle. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.130 retrieving revision 2.131 diff -C2 -d -r2.130 -r2.131 *** cPickle.c 12 Feb 2003 05:28:58 -0000 2.130 --- cPickle.c 13 Feb 2003 15:44:41 -0000 2.131 *************** *** 16,20 **** /* Bump this when new opcodes are added to the pickle protocol. */ ! #define CURRENT_PROTOCOL_NUMBER 2 /* --- 16,20 ---- /* Bump this when new opcodes are added to the pickle protocol. */ ! #define HIGHEST_PROTOCOL 2 /* *************** *** 2744,2752 **** if (proto < 0) ! proto = CURRENT_PROTOCOL_NUMBER; ! if (proto > CURRENT_PROTOCOL_NUMBER) { PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; " "the highest available protocol is %d", ! proto, CURRENT_PROTOCOL_NUMBER); return NULL; } --- 2744,2752 ---- if (proto < 0) ! proto = HIGHEST_PROTOCOL; ! if (proto > HIGHEST_PROTOCOL) { PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; " "the highest available protocol is %d", ! proto, HIGHEST_PROTOCOL); return NULL; } *************** *** 4309,4313 **** */ assert(i >= 0); ! if (i <= CURRENT_PROTOCOL_NUMBER) return 0; --- 4309,4313 ---- */ assert(i >= 0); ! if (i <= HIGHEST_PROTOCOL) return 0; *************** *** 5562,5565 **** --- 5562,5569 ---- } Py_DECREF(di); + + i = PyModule_AddIntConstant(m, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL); + if (i < 0) + return; /* These are purely informational; no code uses them. */ From tim_one@users.sourceforge.net Thu Feb 13 15:45:15 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 07:45:15 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.151,1.152 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv24734/Lib Modified Files: pickle.py Log Message: Added a HIGHEST_PROTOCOL module attribute to pickle and cPickle. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.151 retrieving revision 1.152 diff -C2 -d -r1.151 -r1.152 *** pickle.py 11 Feb 2003 22:43:23 -0000 1.151 --- pickle.py 13 Feb 2003 15:44:39 -0000 1.152 *************** *** 48,51 **** --- 48,55 ---- ] # Old format versions we can read + # Keep in synch with cPickle. This is the highest protocol number we + # know how to read. + HIGHEST_PROTOCOL = 2 + # Why use struct.pack() for pickling but marshal.loads() for # unpickling? struct.pack() is 40% faster than marshal.dumps(), but *************** *** 201,207 **** protocol = 0 if protocol < 0: ! protocol = 2 ! elif protocol not in (0, 1, 2): ! raise ValueError, "pickle protocol must be 0, 1 or 2" self.write = file.write self.memo = {} --- 205,211 ---- protocol = 0 if protocol < 0: ! protocol = HIGHEST_PROTOCOL ! elif not 0 <= protocol <= HIGHEST_PROTOCOL: ! raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) self.write = file.write self.memo = {} From tim_one@users.sourceforge.net Thu Feb 13 15:45:15 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 07:45:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.47,1.48 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv24734/Lib/test Modified Files: pickletester.py Log Message: Added a HIGHEST_PROTOCOL module attribute to pickle and cPickle. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** pickletester.py 11 Feb 2003 22:43:24 -0000 1.47 --- pickletester.py 13 Feb 2003 15:44:40 -0000 1.48 *************** *** 1,4 **** --- 1,5 ---- import unittest import pickle + import cPickle import pickletools import copy_reg *************** *** 8,13 **** # Tests that try a number of pickle protocols should have a # for proto in protocols: ! # kind of outer loop. Bump the 3 to 4 if/when protocol 3 is invented. ! protocols = range(3) --- 9,15 ---- # Tests that try a number of pickle protocols should have a # for proto in protocols: ! # kind of outer loop. ! assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2 ! protocols = range(pickle.HIGHEST_PROTOCOL + 1) From tim_one@users.sourceforge.net Thu Feb 13 16:08:12 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:08:12 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv11284/nondist/peps Modified Files: pep-0307.txt Log Message: Added info about the new HIGHEST_PROTOCOL module constant. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** pep-0307.txt 11 Feb 2003 21:23:59 -0000 1.28 --- pep-0307.txt 13 Feb 2003 16:08:06 -0000 1.29 *************** *** 88,92 **** special case is added here: passing a negative number selects the highest protocol version supported by a particular implementation. ! This works in previous Python versions, too. The pickle.py module has supported passing the 'bin' value as a --- 88,97 ---- special case is added here: passing a negative number selects the highest protocol version supported by a particular implementation. ! This works in previous Python versions, too, and so can be used to ! select the highest protocol available in a way that's both backward ! and forward compatible. In addition, a new module constant ! HIGHEST_PROTOCOL is supplied by both pickle and cPickle, equal to ! the highest protocol number the module can read. This is cleaner ! than passing -1, but cannot be used before Python 2.3. The pickle.py module has supported passing the 'bin' value as a From gvanrossum@users.sourceforge.net Thu Feb 13 16:11:32 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:11:32 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.144,1.145 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv12983 Modified Files: setup.py Log Message: Re-enable compiling ossaudiodev now that it seems to work again. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.144 retrieving revision 1.145 diff -C2 -d -r1.144 -r1.145 *** setup.py 11 Feb 2003 20:05:50 -0000 1.144 --- setup.py 13 Feb 2003 16:11:27 -0000 1.145 *************** *** 746,750 **** # ossaudiodev currently doesn't work, so don't build. pass ! ## exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) ) if platform == 'sunos5': --- 746,750 ---- # ossaudiodev currently doesn't work, so don't build. pass ! exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) ) if platform == 'sunos5': From montanaro@users.sourceforge.net Thu Feb 13 16:02:53 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:02:53 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv9044 Modified Files: _csv.c Log Message: * pass NULL to type objects' PyObject_HEAD_INIT() macro * twiddle type objects' docstrings a tad (probably unnecessarily) Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** _csv.c 11 Feb 2003 04:19:33 -0000 1.29 --- _csv.c 13 Feb 2003 16:02:50 -0000 1.30 *************** *** 374,378 **** static PyTypeObject Dialect_Type = { ! PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ "_csv.Dialect", /* tp_name */ --- 374,378 ---- static PyTypeObject Dialect_Type = { ! PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "_csv.Dialect", /* tp_name */ *************** *** 696,700 **** } ! PyDoc_STRVAR(Reader_Type_doc, "CSV reader"); static struct PyMethodDef Reader_methods[] = { --- 696,705 ---- } ! PyDoc_STRVAR(Reader_Type_doc, ! "CSV reader\n" ! "\n" ! "Reader objects are responsible for reading and parsing tabular data\n" ! "in CSV format.\n" ! ); static struct PyMethodDef Reader_methods[] = { *************** *** 703,707 **** static PyTypeObject Reader_Type = { ! PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "_csv.reader", /*tp_name*/ --- 708,712 ---- static PyTypeObject Reader_Type = { ! PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "_csv.reader", /*tp_name*/ *************** *** 1094,1101 **** } ! PyDoc_STRVAR(Writer_Type_doc, "CSV writer"); static PyTypeObject Writer_Type = { ! PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "_csv.writer", /*tp_name*/ --- 1099,1111 ---- } ! PyDoc_STRVAR(Writer_Type_doc, ! "CSV writer\n" ! "\n" ! "Writer objects are responsible for generating tabular data\n" ! "in CSV format from sequence input.\n" ! ); static PyTypeObject Writer_Type = { ! PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "_csv.writer", /*tp_name*/ From gvanrossum@users.sourceforge.net Thu Feb 13 16:12:25 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:12:25 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.124,1.125 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv13400 Modified Files: regrtest.py Log Message: Re-enable compiling ossaudiodev now that it seems to work again. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.124 retrieving revision 1.125 diff -C2 -d -r1.124 -r1.125 *** regrtest.py 12 Feb 2003 20:40:08 -0000 1.124 --- regrtest.py 13 Feb 2003 16:12:21 -0000 1.125 *************** *** 594,598 **** test_nis test_ntpath - test_ossaudiodev test_socketserver test_sunaudiodev --- 594,597 ---- From gvanrossum@users.sourceforge.net Thu Feb 13 16:24:37 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:24:37 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.209,2.210 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv19269 Modified Files: typeobject.c Log Message: SF patch #685738 by Michael Stone. This changes the default __new__ to refuse arguments iff tp_init is the default __init__ implementation -- thus making it a TypeError when you try to pass arguments to a constructor if the class doesn't override at least __init__ or __new__. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.209 retrieving revision 2.210 diff -C2 -d -r2.209 -r2.210 *** typeobject.c 12 Feb 2003 03:58:38 -0000 2.209 --- typeobject.c 13 Feb 2003 16:24:34 -0000 2.210 *************** *** 2252,2255 **** --- 2252,2273 ---- } + /* If we don't have a tp_new for a new-style class, new will use this one. + Therefore this should take no arguments/keywords. However, this new may + also be inherited by objects that define a tp_init but no tp_new. These + objects WILL pass argumets to tp_new, because it gets the same args as + tp_init. So only allow arguments if we aren't using the default init, in + which case we expect init to handle argument parsing. */ + static PyObject * + object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) || + (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) { + PyErr_SetString(PyExc_TypeError, + "default __new__ takes no parameters"); + return NULL; + } + return type->tp_alloc(type, 0); + } + static void object_dealloc(PyObject *self) *************** *** 2488,2492 **** object_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! PyType_GenericNew, /* tp_new */ PyObject_Del, /* tp_free */ }; --- 2506,2510 ---- object_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! object_new, /* tp_new */ PyObject_Del, /* tp_free */ }; From gvanrossum@users.sourceforge.net Thu Feb 13 16:25:09 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:25:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.183,1.184 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19637 Modified Files: test_descr.py Log Message: SF patch #685738 by Michael Stone. This changes the default __new__ to refuse arguments iff tp_init is the default __init__ implementation -- thus making it a TypeError when you try to pass arguments to a constructor if the class doesn't override at least __init__ or __new__. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.183 retrieving revision 1.184 diff -C2 -d -r1.183 -r1.184 *** test_descr.py 12 Feb 2003 03:58:38 -0000 1.183 --- test_descr.py 13 Feb 2003 16:25:05 -0000 1.184 *************** *** 3695,3700 **** return "C.__rdiv__" ! vereq(C(1) / 1, "C.__div__") ! vereq(1 / C(1), "C.__rdiv__") # Case 3: subclass of new-style class; here it gets interesting --- 3695,3700 ---- return "C.__rdiv__" ! vereq(C() / 1, "C.__div__") ! vereq(1 / C(), "C.__rdiv__") # Case 3: subclass of new-style class; here it gets interesting *************** *** 3706,3711 **** return "D.__rdiv__" ! vereq(D(1) / C(1), "D.__div__") ! vereq(C(1) / D(1), "D.__rdiv__") # Case 4: this didn't work right in 2.2.2 and 2.3a1 --- 3706,3711 ---- return "D.__rdiv__" ! vereq(D() / C(), "D.__div__") ! vereq(C() / D(), "D.__rdiv__") # Case 4: this didn't work right in 2.2.2 and 2.3a1 *************** *** 3716,3723 **** vereq(E.__rdiv__, C.__rdiv__) ! vereq(E(1) / 1, "C.__div__") ! vereq(1 / E(1), "C.__rdiv__") ! vereq(E(1) / C(1), "C.__div__") ! vereq(C(1) / E(1), "C.__div__") # This one would fail def dict_type_with_metaclass(): --- 3716,3723 ---- vereq(E.__rdiv__, C.__rdiv__) ! vereq(E() / 1, "C.__div__") ! vereq(1 / E(), "C.__rdiv__") ! vereq(E() / C(), "C.__div__") ! vereq(C() / E(), "C.__div__") # This one would fail def dict_type_with_metaclass(): From gvanrossum@users.sourceforge.net Thu Feb 13 16:25:40 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:25:40 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv19922 Modified Files: copy_reg.py Log Message: SF patch #685738 by Michael Stone. This changes the default __new__ to refuse arguments iff tp_init is the default __init__ implementation -- thus making it a TypeError when you try to pass arguments to a constructor if the class doesn't override at least __init__ or __new__. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** copy_reg.py 10 Feb 2003 21:31:25 -0000 1.19 --- copy_reg.py 13 Feb 2003 16:25:37 -0000 1.20 *************** *** 34,42 **** pickle(type(1j), pickle_complex, complex) ! # Support for picking new-style objects def _reconstructor(cls, base, state): ! obj = base.__new__(cls, state) ! base.__init__(obj, state) return obj --- 34,45 ---- pickle(type(1j), pickle_complex, complex) ! # Support for pickling new-style objects def _reconstructor(cls, base, state): ! if base is object: ! obj = object.__new__(cls) ! else: ! obj = base.__new__(cls, state) ! base.__init__(obj, state) return obj From gvanrossum@users.sourceforge.net Thu Feb 13 16:30:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 08:30:23 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.656,1.657 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv22067 Modified Files: NEWS Log Message: SF patch #685738 by Michael Stone. This changes the default __new__ to refuse arguments iff tp_init is the default __init__ implementation -- thus making it a TypeError when you try to pass arguments to a constructor if the class doesn't override at least __init__ or __new__. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.656 retrieving revision 1.657 diff -C2 -d -r1.656 -r1.657 *** NEWS 12 Feb 2003 21:46:11 -0000 1.656 --- NEWS 13 Feb 2003 16:30:16 -0000 1.657 *************** *** 13,16 **** --- 13,22 ---- ----------------- + - If a new-style class defines neither __new__ nor __init__, its + constructor would ignore all arguments. This is changed now: the + constructor refuses arguments in this case. This might break code + that worked under Python 2.2. The simplest fix is to add a no-op + __init__: "def __init__(self, *args, **kw): pass". + - Through a bytecode optimizer bug (and I bet you didn't even know Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants From akuchlin@mems-exchange.org Thu Feb 13 16:42:51 2003 From: akuchlin@mems-exchange.org (Andrew Kuchling) Date: Thu, 13 Feb 2003 11:42:51 -0500 Subject: [Python-checkins] python/dist/src setup.py,1.144,1.145 In-Reply-To: References: Message-ID: <20030213164251.GB21196@ute.mems-exchange.org> On Thu, Feb 13, 2003 at 08:11:32AM -0800, gvanrossum@users.sourceforge.net wrote: >Re-enable compiling ossaudiodev now that it seems to work again. Does it? The December python-dev archive has a report from Jeremy that the test just hung for him; I have no idea if that problem is still valid or not. (Greg's out this week. I may look at any ossaudiodev problems that get reported, but don't count on it.) --amk From gvanrossum@users.sourceforge.net Thu Feb 13 17:01:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 09:01:35 -0800 Subject: [Python-checkins] python/dist/src/Python import.c,2.192.6.2,2.192.6.3 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv3041 Modified Files: Tag: release22-maint import.c Log Message: Backport 2.217 and 2.218: Provide access to the import lock, fixing SF bug #580952. This is mostly from SF patch #683257, but I had to change unlock_import() to return an error value to avoid fatal error. Index: import.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/import.c,v retrieving revision 2.192.6.2 retrieving revision 2.192.6.3 diff -C2 -d -r2.192.6.2 -r2.192.6.3 *** import.c 1 Jun 2002 18:26:22 -0000 2.192.6.2 --- import.c 13 Feb 2003 17:01:28 -0000 2.192.6.3 *************** *** 162,166 **** return; } ! if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) { PyThreadState *tstate = PyEval_SaveThread(); PyThread_acquire_lock(import_lock, 1); --- 162,167 ---- return; } ! if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) ! { PyThreadState *tstate = PyEval_SaveThread(); PyThread_acquire_lock(import_lock, 1); *************** *** 171,182 **** } ! static void unlock_import(void) { long me = PyThread_get_thread_ident(); if (me == -1) ! return; /* Too bad */ if (import_lock_thread != me) ! Py_FatalError("unlock_import: not holding the import lock"); import_lock_level--; if (import_lock_level == 0) { --- 172,183 ---- } ! static int unlock_import(void) { long me = PyThread_get_thread_ident(); if (me == -1) ! return 0; /* Too bad */ if (import_lock_thread != me) ! return -1; import_lock_level--; if (import_lock_level == 0) { *************** *** 184,187 **** --- 185,189 ---- PyThread_release_lock(import_lock); } + return 1; } *************** *** 189,193 **** #define lock_import() ! #define unlock_import() #endif --- 191,195 ---- #define lock_import() ! #define unlock_import() 0 #endif *************** *** 205,208 **** --- 207,238 ---- } + static PyObject * + imp_acquire_lock(PyObject *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":acquire_lock")) + return NULL; + #ifdef WITH_THREAD + lock_import(); + #endif + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + imp_release_lock(PyObject *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":release_lock")) + return NULL; + #ifdef WITH_THREAD + if (unlock_import() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + #endif + Py_INCREF(Py_None); + return Py_None; + } + /* Helper for sys */ *************** *** 1657,1661 **** lock_import(); result = import_module_ex(name, globals, locals, fromlist); ! unlock_import(); return result; } --- 1687,1696 ---- lock_import(); result = import_module_ex(name, globals, locals, fromlist); ! if (unlock_import() < 0) { ! Py_XDECREF(result); ! PyErr_SetString(PyExc_RuntimeError, ! "not holding the import lock"); ! return NULL; ! } return result; } *************** *** 2427,2430 **** --- 2462,2477 ---- "; + static char doc_acquire_lock[] = "\ + acquire_lock() -> None\n\ + Acquires the interpreter's import lock for the current thread.\n\ + This lock should be used by import hooks to ensure thread-safety\n\ + when importing modules.\n\ + On platforms without threads, this function does nothing."; + + static char doc_release_lock[] = "\ + release_lock() -> None\n\ + Release the interpreter's import lock.\n\ + On platforms without threads, this function does nothing."; + static PyMethodDef imp_methods[] = { {"find_module", imp_find_module, 1, doc_find_module}, *************** *** 2434,2437 **** --- 2481,2486 ---- {"new_module", imp_new_module, 1, doc_new_module}, {"lock_held", imp_lock_held, 1, doc_lock_held}, + {"acquire_lock", imp_acquire_lock, 1, doc_acquire_lock}, + {"release_lock", imp_release_lock, 1, doc_release_lock}, /* The rest are obsolete */ {"get_frozen_object", imp_get_frozen_object, 1}, From gvanrossum@users.sourceforge.net Thu Feb 13 17:06:07 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 09:06:07 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.60,1.337.2.4.2.61 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv4891 Modified Files: Tag: release22-maint NEWS Log Message: Backport 2.217 and 2.218: Provide access to the import lock, fixing SF bug #580952. This is mostly from SF patch #683257, but I had to change unlock_import() to return an error value to avoid fatal error. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.60 retrieving revision 1.337.2.4.2.61 diff -C2 -d -r1.337.2.4.2.60 -r1.337.2.4.2.61 *** NEWS 12 Feb 2003 19:09:45 -0000 1.337.2.4.2.60 --- NEWS 13 Feb 2003 17:06:02 -0000 1.337.2.4.2.61 *************** *** 3,6 **** --- 3,12 ---- ============================ + - The imp module now has ways to acquire and release the "import + lock": imp.acquire_lock() and imp.release_lock(). Note: this is a + reentrant lock, so releasing the lock only truly releases it when + this is the last release_lock() call. You can check with + imp.lock_held(). (SF bug #580952 and patch #683257.) + - Through a bytecode optimizer bug (and I bet you didn't even know Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants From montanaro@users.sourceforge.net Thu Feb 13 17:21:18 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 09:21:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv10987 Modified Files: test_csv.py Log Message: Since I'm no longer interested in seeing how the pattern of refcount deltas settles down, I don't need to maintain a list, a simple int will do. Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** test_csv.py 12 Feb 2003 02:44:42 -0000 1.32 --- test_csv.py 13 Feb 2003 17:21:15 -0000 1.33 *************** *** 462,466 **** class TestLeaks(unittest.TestCase): def test_create_read(self): ! deltas = [] lastrc = sys.gettotalrefcount() for i in xrange(20): --- 462,466 ---- class TestLeaks(unittest.TestCase): def test_create_read(self): ! delta = 0 lastrc = sys.gettotalrefcount() for i in xrange(20): *************** *** 471,481 **** csv.reader(["a,b,c\r\n"]) csv.reader(["a,b,c\r\n"]) ! deltas.append(rc-lastrc) lastrc = rc ! # if csv.reader() leaks, delta should be 3 or more ! self.assertEqual(deltas[-1] < 3, True) def test_create_write(self): ! deltas = [] lastrc = sys.gettotalrefcount() s = StringIO() --- 471,481 ---- csv.reader(["a,b,c\r\n"]) csv.reader(["a,b,c\r\n"]) ! delta = rc-lastrc lastrc = rc ! # if csv.reader() leaks, last delta should be 3 or more ! self.assertEqual(delta < 3, True) def test_create_write(self): ! delta = 0 lastrc = sys.gettotalrefcount() s = StringIO() *************** *** 487,499 **** csv.writer(s) csv.writer(s) ! deltas.append(rc-lastrc) lastrc = rc ! # if csv.writer() leaks, delta should be 3 or more ! self.assertEqual(deltas[-1] < 3, True) def test_read(self): ! deltas = [] ! lastrc = sys.gettotalrefcount() rows = ["a,b,c\r\n"]*5 for i in xrange(20): gc.collect() --- 487,499 ---- csv.writer(s) csv.writer(s) ! delta = rc-lastrc lastrc = rc ! # if csv.writer() leaks, last delta should be 3 or more ! self.assertEqual(delta < 3, True) def test_read(self): ! delta = 0 rows = ["a,b,c\r\n"]*5 + lastrc = sys.gettotalrefcount() for i in xrange(20): gc.collect() *************** *** 503,514 **** for row in rdr: pass ! deltas.append(rc-lastrc) lastrc = rc # if reader leaks during read, delta should be 5 or more ! self.assertEqual(deltas[-1] < 5, True) def test_write(self): ! deltas = [] ! lastrc = sys.gettotalrefcount() rows = [[1,2,3]]*5 class NUL: --- 503,513 ---- for row in rdr: pass ! delta = rc-lastrc lastrc = rc # if reader leaks during read, delta should be 5 or more ! self.assertEqual(delta < 5, True) def test_write(self): ! delta = 0 rows = [[1,2,3]]*5 class NUL: *************** *** 516,519 **** --- 515,519 ---- pass s = NUL() + lastrc = sys.gettotalrefcount() for i in xrange(20): gc.collect() *************** *** 523,530 **** for row in rows: writer.writerow(row) ! deltas.append(rc-lastrc) lastrc = rc ! # if reader leaks during read, delta should be 5 or more ! self.assertEqual(deltas[-1] < 5, True) def _testclasses(): --- 523,530 ---- for row in rows: writer.writerow(row) ! delta = rc-lastrc lastrc = rc ! # if writer leaks during write, last delta should be 5 or more ! self.assertEqual(delta < 5, True) def _testclasses(): From montanaro@users.sourceforge.net Thu Feb 13 17:30:35 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 09:30:35 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv15319 Modified Files: libcsv.tex Log Message: Comment out the \see* macros for the moment - they are blowing LaTeX's stack for some reason. They'll probably work with the full libref manual in place. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** libcsv.tex 12 Feb 2003 17:37:49 -0000 1.6 --- libcsv.tex 13 Feb 2003 17:30:30 -0000 1.7 *************** *** 260,264 **** \begin{seealso} ! \seemodule{array}{Arrays of uniformly types numeric values.} ! \seepep{305}{CSV File API} \end{seealso} --- 260,264 ---- \begin{seealso} ! % \seemodule{array}{Arrays of uniformly types numeric values.} ! % \seepep{305}{CSV File API} \end{seealso} From montanaro@users.sourceforge.net Thu Feb 13 17:31:09 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 09:31:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv .cvsignore,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv15650 Modified Files: .cvsignore Log Message: don't worry about dvi and pdf files Index: .cvsignore =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/.cvsignore,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** .cvsignore 29 Jan 2003 18:31:45 -0000 1.1 --- .cvsignore 13 Feb 2003 17:31:05 -0000 1.2 *************** *** 1 **** --- 1,3 ---- build + lib.dvi + lib.pdf From doerwalter@users.sourceforge.net Thu Feb 13 18:07:46 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Thu, 13 Feb 2003 10:07:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_userlist.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2057/Lib/test Modified Files: test_userlist.py Log Message: Port test_userlist to PyUnit and add a few tests to increase code coverage. From SF patch #662807 Index: test_userlist.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_userlist.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_userlist.py 23 Jul 2002 19:04:09 -0000 1.6 --- test_userlist.py 13 Feb 2003 18:07:43 -0000 1.7 *************** *** 2,201 **** from UserList import UserList ! from test.test_support import TestFailed ! ! # Use check instead of assert so -O doesn't render the ! # test useless. ! # XXX: could use the verify function in test_support instead ! def check(predicate, msg): ! if not predicate: ! raise TestFailed(msg + " failed") ! ! l0 = [] ! l1 = [0] ! l2 = [0, 1] ! # Test constructors ! u = UserList() ! u0 = UserList(l0) ! u1 = UserList(l1) ! u2 = UserList(l2) ! uu = UserList(u) ! uu0 = UserList(u0) ! uu1 = UserList(u1) ! uu2 = UserList(u2) ! v = UserList(tuple(u)) ! class OtherList: ! def __init__(self, initlist): ! self.__data = initlist ! def __len__(self): ! return len(self.__data) ! def __getitem__(self, i): ! return self.__data[i] ! v0 = UserList(OtherList(u0)) ! vv = UserList("this is also a sequence") ! # Test __repr__ ! check(str(u0) == str(l0), "str(u0) == str(l0)") ! check(repr(u1) == repr(l1), "repr(u1) == repr(l1)") ! check(`u2` == `l2`, "`u2` == `l2`") ! # Test __cmp__ and __len__ ! def mycmp(a, b): ! r = cmp(a, b) ! if r < 0: return -1 ! if r > 0: return 1 ! return r ! all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] ! for a in all: ! for b in all: ! check(mycmp(a, b) == mycmp(len(a), len(b)), ! "mycmp(a, b) == mycmp(len(a), len(b))") ! # Test __getitem__ ! for i in range(len(u2)): ! check(u2[i] == i, "u2[i] == i") ! # Test __setitem__ ! uu2[0] = 0 ! uu2[1] = 100 ! try: ! uu2[2] = 200 ! except IndexError: ! pass ! else: ! raise TestFailed("uu2[2] shouldn't be assignable") ! # Test __delitem__ ! del uu2[1] ! del uu2[0] ! try: ! del uu2[0] ! except IndexError: ! pass ! else: ! raise TestFailed("uu2[0] shouldn't be deletable") ! # Test __getslice__ ! for i in range(-3, 4): ! check(u2[:i] == l2[:i], "u2[:i] == l2[:i]") ! check(u2[i:] == l2[i:], "u2[i:] == l2[i:]") ! for j in range(-3, 4): ! check(u2[i:j] == l2[i:j], "u2[i:j] == l2[i:j]") ! # Test __setslice__ ! for i in range(-3, 4): ! u2[:i] = l2[:i] ! check(u2 == l2, "u2 == l2") ! u2[i:] = l2[i:] ! check(u2 == l2, "u2 == l2") ! for j in range(-3, 4): ! u2[i:j] = l2[i:j] ! check(u2 == l2, "u2 == l2") ! uu2 = u2[:] ! uu2[:0] = [-2, -1] ! check(uu2 == [-2, -1, 0, 1], "uu2 == [-2, -1, 0, 1]") ! uu2[0:] = [] ! check(uu2 == [], "uu2 == []") ! # Test __contains__ ! for i in u2: ! check(i in u2, "i in u2") ! for i in min(u2)-1, max(u2)+1: ! check(i not in u2, "i not in u2") ! # Test __delslice__ ! uu2 = u2[:] ! del uu2[1:2] ! del uu2[0:1] ! check(uu2 == [], "uu2 == []") ! uu2 = u2[:] ! del uu2[1:] ! del uu2[:1] ! check(uu2 == [], "uu2 == []") ! # Test __add__, __radd__, __mul__ and __rmul__ ! check(u1 + [] == [] + u1 == u1, "u1 + [] == [] + u1 == u1") ! check(u1 + [1] == u2, "u1 + [1] == u2") ! check([-1] + u1 == [-1, 0], "[-1] + u1 == [-1, 0]") ! check(u2 == u2*1 == 1*u2, "u2 == u2*1 == 1*u2") ! check(u2+u2 == u2*2 == 2*u2, "u2+u2 == u2*2 == 2*u2") ! check(u2+u2+u2 == u2*3 == 3*u2, "u2+u2+u2 == u2*3 == 3*u2") ! # Test append ! u = u1[:] ! u.append(1) ! check(u == u2, "u == u2") ! # Test insert ! u = u2[:] ! u.insert(0, -1) ! check(u == [-1, 0, 1], "u == [-1, 0, 1]") ! # Test pop ! u = [-1] + u2 ! u.pop() ! check(u == [-1, 0], "u == [-1, 0]") ! u.pop(0) ! check(u == [0], "u == [0]") ! # Test remove ! u = u2[:] ! u.remove(1) ! check(u == u1, "u == u1") ! # Test count ! u = u2*3 ! check(u.count(0) == 3, "u.count(0) == 3") ! check(u.count(1) == 3, "u.count(1) == 3") ! check(u.count(2) == 0, "u.count(2) == 0") ! # Test index ! check(u2.index(0) == 0, "u2.index(0) == 0") ! check(u2.index(1) == 1, "u2.index(1) == 1") ! try: ! u2.index(2) ! except ValueError: ! pass ! else: ! raise TestFailed("expected ValueError") ! # Test reverse ! u = u2[:] ! u.reverse() ! check(u == [1, 0], "u == [1, 0]") ! u.reverse() ! check(u == u2, "u == u2") ! # Test sort ! u = UserList([1, 0]) ! u.sort() ! check(u == u2, "u == u2") ! # Test extend - u = u1[:] - u.extend(u2) - check(u == u1 + u2, "u == u1 + u2") --- 2,261 ---- from UserList import UserList ! import unittest, test.test_support ! class UserListTest(unittest.TestCase): ! def test_constructors(self): ! l0 = [] ! l1 = [0] ! l2 = [0, 1] ! u = UserList() ! u0 = UserList(l0) ! u1 = UserList(l1) ! u2 = UserList(l2) ! uu = UserList(u) ! uu0 = UserList(u0) ! uu1 = UserList(u1) ! uu2 = UserList(u2) ! v = UserList(tuple(u)) ! class OtherList: ! def __init__(self, initlist): ! self.__data = initlist ! def __len__(self): ! return len(self.__data) ! def __getitem__(self, i): ! return self.__data[i] ! v0 = UserList(OtherList(u0)) ! vv = UserList("this is also a sequence") ! def test_repr(self): ! l0 = [] ! l2 = [0, 1, 2] ! u0 = UserList(l0) ! u2 = UserList(l2) ! self.assertEqual(str(u0), str(l0)) ! self.assertEqual(repr(u0), repr(l0)) ! self.assertEqual(`u2`, `l2`) ! def test_cmplen(self): ! l0 = [] ! l1 = [0] ! l2 = [0, 1] ! # Test constructors ! u = UserList() ! u0 = UserList(l0) ! u1 = UserList(l1) ! u2 = UserList(l2) ! uu = UserList(u) ! uu0 = UserList(u0) ! uu1 = UserList(u1) ! uu2 = UserList(u2) ! def mycmp(x, y): ! r = cmp(x, y) ! if r < 0: return -1 ! if r > 0: return 1 ! return r ! all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] ! for a in all: ! for b in all: ! self.assertEqual(mycmp(a, b), mycmp(len(a), len(b))) ! self.assert_(u0 <= u2) ! self.assert_(u2 >= u0) ! def test_getitem(self): ! u = UserList([0, 1, 2]) ! for i in xrange(len(u)): ! self.assertEqual(u[i], i) ! def test_setitem(self): ! u = UserList([0, 1]) ! u[0] = 0 ! u[1] = 100 ! self.assertEqual(u, [0, 100]) ! self.assertRaises(IndexError, u.__setitem__, 2, 200) ! def test_delitem(self): ! u = UserList([0, 1]) ! del u[1] ! del u[0] ! self.assertRaises(IndexError, u.__delitem__, 0) ! def test_getslice(self): ! l = [0, 1] ! u = UserList(l) ! for i in xrange(-3, 4): ! self.assertEqual(u[:i], l[:i]) ! self.assertEqual(u[i:], l[i:]) ! for j in xrange(-3, 4): ! self.assertEqual(u[i:j], l[i:j]) ! def test_setslice(self): ! l = [0, 1] ! u = UserList(l) ! # Test __setslice__ ! for i in range(-3, 4): ! u[:i] = l[:i] ! self.assertEqual(u, l) ! u2 = u[:] ! u2[:i] = u[:i] ! self.assertEqual(u2, u) ! u[i:] = l[i:] ! self.assertEqual(u, l) ! u2 = u[:] ! u2[i:] = u[i:] ! self.assertEqual(u2, u) ! for j in range(-3, 4): ! u[i:j] = l[i:j] ! self.assertEqual(u, l) ! u2 = u[:] ! u2[i:j] = u[i:j] ! self.assertEqual(u2, u) ! uu2 = u2[:] ! uu2[:0] = [-2, -1] ! self.assertEqual(uu2, [-2, -1, 0, 1]) ! uu2[0:] = [] ! self.assertEqual(uu2, []) ! def test_contains(self): ! u = UserList([0, 1, 2]) ! for i in u: ! self.assert_(i in u) ! for i in min(u)-1, max(u)+1: ! self.assert_(i not in u) ! def test_delslice(self): ! u = UserList([0, 1]) ! del u[1:2] ! del u[0:1] ! self.assertEqual(u, []) ! u = UserList([0, 1]) ! del u[1:] ! del u[:1] ! self.assertEqual(u, []) ! def test_addmul(self): ! u1 = UserList([0]) ! u2 = UserList([0, 1]) ! self.assertEqual(u1, u1 + []) ! self.assertEqual(u1, [] + u1) ! self.assertEqual(u1 + [1], u2) ! self.assertEqual([-1] + u1, [-1, 0]) ! self.assertEqual(u2, u2*1) ! self.assertEqual(u2, 1*u2) ! self.assertEqual(u2+u2, u2*2) ! self.assertEqual(u2+u2, 2*u2) ! self.assertEqual(u2+u2+u2, u2*3) ! self.assertEqual(u2+u2+u2, 3*u2) ! def test_add_specials(self): ! u = UserList("spam") ! u2 = u + "eggs" ! self.assertEqual(u2, list("spameggs")) ! def test_radd_specials(self): ! u = UserList("eggs") ! u2 = "spam" + u ! self.assertEqual(u2, list("spameggs")) ! u2 = u.__radd__(UserList("spam")) ! self.assertEqual(u2, list("spameggs")) ! def test_append(self): ! u = UserList((0, )) ! u.append(1) ! self.assertEqual(u, [0, 1]) ! def test_insert(self): ! u = UserList((0, 1)) ! u.insert(0, -1) ! self.assertEqual(u, [-1, 0, 1]) ! def test_pop(self): ! u = UserList((-1, 0, 1)) ! u.pop() ! self.assertEqual(u, [-1, 0]) ! u.pop(0) ! self.assertEqual(u, [0]) ! def test_remove(self): ! u = UserList((0, 1)) ! u.remove(1) ! self.assertEqual(u, [0]) ! def test_count(self): ! u = UserList((0, 1))*3 ! self.assertEqual(u.count(0), 3) ! self.assertEqual(u.count(1), 3) ! self.assertEqual(u.count(2), 0) ! def test_index(self): ! u = UserList((0, 1)) ! self.assertEqual(u.index(0), 0) ! self.assertEqual(u.index(1), 1) ! self.assertRaises(ValueError, u.index, 2) ! def test_reverse(self): ! u = UserList((0, 1)) ! u2 = u[:] ! u.reverse() ! self.assertEqual(u, [1, 0]) ! u.reverse() ! self.assertEqual(u, u2) ! def test_sort(self): ! u = UserList([1, 0]) ! u.sort() ! self.assertEqual(u, [0, 1]) + def test_slice(self): + u = UserList("spam") + u[:2] = "h" + self.assertEqual(u, list("ham")) ! def test_iadd(self): ! u = UserList((0, 1)) ! u += [0, 1] ! self.assertEqual(u, [0, 1, 0, 1]) ! u += UserList([0, 1]) ! self.assertEqual(u, [0, 1, 0, 1, 0, 1]) ! u = UserList("spam") ! u += "eggs" ! self.assertEqual(u, list("spameggs")) ! def test_extend(self): ! u1 = UserList((0, )) ! u2 = UserList((0, 1)) ! u = u1[:] ! u.extend(u2) ! self.assertEqual(u, u1 + u2) ! u = UserList("spam") ! u.extend("eggs") ! self.assertEqual(u, list("spameggs")) ! def test_imul(self): ! u = UserList((0, 1)) ! u *= 3 ! self.assertEqual(u, [0, 1, 0, 1, 0, 1]) ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(UserListTest)) ! test.test_support.run_suite(suite) ! if __name__ == "__main__": ! test_main() From tim_one@users.sourceforge.net Thu Feb 13 18:24:19 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 10:24:19 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.131,2.132 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9175/Modules Modified Files: cPickle.c Log Message: Taught cPickle how to read pickles containing NEWOBJ. This won't get exercised by the test suite before cPickle knows how to create NEWOBJ too. For now, it was just tried once by hand (via loading a NEWOBJ pickle created by pickle.py). Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.131 retrieving revision 2.132 diff -C2 -d -r2.131 -r2.132 *** cPickle.c 13 Feb 2003 15:44:41 -0000 2.131 --- cPickle.c 13 Feb 2003 18:24:14 -0000 2.132 *************** *** 3699,3702 **** --- 3699,3749 ---- } + static int + load_newobj(Unpicklerobject *self) + { + PyObject *args = NULL; + PyObject *clsraw = NULL; + PyTypeObject *cls; /* clsraw cast to its true type */ + PyObject *obj; + + /* Stack is ... cls argtuple, and we want to call + * cls.__new__(cls, *argtuple). + */ + PDATA_POP(self->stack, args); + if (args == NULL) goto Fail; + if (! PyTuple_Check(args)) { + PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg " + "tuple."); + goto Fail; + } + + PDATA_POP(self->stack, clsraw); + cls = (PyTypeObject *)clsraw; + if (cls == NULL) goto Fail; + if (! PyType_Check(cls)) { + PyErr_SetString(UnpicklingError, "NEWOBJ class argument " + "isn't a type object"); + goto Fail; + } + if (cls->tp_new == NULL) { + PyErr_SetString(UnpicklingError, "NEWOBJ class argument " + "has NULL tp_new"); + goto Fail; + } + + /* Call __new__. */ + obj = cls->tp_new(cls, args, NULL); + if (obj == NULL) goto Fail; + + Py_DECREF(args); + Py_DECREF(clsraw); + PDATA_PUSH(self->stack, obj, -1); + return 0; + + Fail: + Py_XDECREF(args); + Py_XDECREF(clsraw); + return -1; + } static int *************** *** 4462,4465 **** --- 4509,4517 ---- continue; + case NEWOBJ: + if (load_newobj(self) < 0) + break; + continue; + case GLOBAL: if (load_global(self) < 0) *************** *** 4639,4647 **** if (self->readline_func(self, &s) < 0) return -1; if (self->readline_func(self, &s) < 0) return -1; ! PDATA_APPEND(self->stack, Py_None,-1); return 0; } static int noload_global(Unpicklerobject *self) { --- 4691,4716 ---- if (self->readline_func(self, &s) < 0) return -1; if (self->readline_func(self, &s) < 0) return -1; ! PDATA_APPEND(self->stack, Py_None, -1); return 0; } static int + noload_newobj(Unpicklerobject *self) + { + PyObject *obj; + + PDATA_POP(self->stack, obj); /* pop argtuple */ + if (obj == NULL) return -1; + Py_DECREF(obj); + + PDATA_POP(self->stack, obj); /* pop cls */ + if (obj == NULL) return -1; + Py_DECREF(obj); + + PDATA_APPEND(self->stack, Py_None, -1); + return 0; + } + + static int noload_global(Unpicklerobject *self) { *************** *** 4827,4830 **** --- 4896,4904 ---- case INST: if (noload_inst(self) < 0) + break; + continue; + + case NEWOBJ: + if (noload_newobj(self) < 0) break; continue; From montanaro@users.sourceforge.net Thu Feb 13 18:30:12 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 10:30:12 -0800 Subject: [Python-checkins] python/dist/src/Doc/tools makesec.sh,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/tools In directory sc8-pr-cvs1:/tmp/cvs-serv12936 Added Files: makesec.sh Log Message: first cut at a shell script to view a single section from the library reference manual --- NEW FILE: makesec.sh --- #!/bin/bash # Simple little checker for individual libref manual sections # # usage: makesec.sh section # # This script builds the minimal file necessary to run a single section # through latex, does so, then converts the resulting dvi file to ps or pdf # and feeds the result into a viewer. It's by no means foolproof, but seems # to work okay for me (knock wood). It sure beats manually commenting out # most of the man lib.tex file and running everything manually. # It attempts to locate an appropriate dvi converter and viewer for the # selected output format. It understands the following environment # variables: # # PYSRC - refers to the root of your build tree (dir containing Doc) # DVICVT - refers to a dvi converter like dvips or dvipdf # VIEWER - refers to an appropriate viewer for the ps/pdf file # # Of the three, only PYSRC is currently required. The other two can be set # to specify unusual tools which perform those tasks. # Known issues: # - It would be nice if the script could determine PYSRC on its own. # - Something about \seealso{}s blows the latex stack, so they need # to be commented out for now. if [ x$PYSRC = x ] ; then echo "PYSRC must refer to the Python source tree" 1>&2 exit 1 fi if [ ! -d $PYSRC/Doc ] ; then echo "Can't find a Doc subdirectory in $PYSRC" 1>&2 exit 1 fi if [ "$#" -ne 1 ] ; then echo "Must specify a single libref manual section on cmd line" 1>&2 exit 1 fi # settle on a dvi converter if [ x$DVICVT != x ] ; then converter=$DVICVT ext=`echo $DVICVT | sed -e 's/^dvi//'` result=lib.$ext elif [ x`which dvipdf` != x ] ; then converter=`which dvipdf` ext=.pdf elif [ x`which dvips` != x ] ; then converter=`which dvips` ext=.ps else echo "Can't find a reasonable dvi converter" 1>&2 echo "Set DVICVT to refer to one" 1>&2 exit 1 fi # how about a viewer? if [ x$VIEWER != x ] ; then viewer=$VIEWER elif [ $ext = ".ps" -a x`which gv` != x ] ; then viewer=gv elif [ $ext = ".ps" -a x`which gs` != x ] ; then viewer=gs elif [ $ext = ".pdf" -a x`which acroread` != x ] ; then viewer=acroread elif [ $ext = ".pdf" -a "`uname`" = "Darwin" -a x`which open` != x ] ; then viewer=open elif [ $ext = ".pdf" -a x`which acroread` != x ] ; then viewer=acroread else echo "Can't find a reasonable viewer" 1>&2 echo "Set VIEWER to refer to one" 1>&2 exit 1 fi # make sure necessary links are in place for f in howto.cls pypaper.sty ; do rm -f $f ln -s $PYSRC/Doc/$f done export TEXINPUTS=.:$PYSRC/Doc/texinputs: # strip extension in case they gave full filename inp=`basename $1 .tex` # create the minimal framework necessary to run section through latex tmpf=lib.tex cat > $tmpf < Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15877 Modified Files: test_sundry.py Log Message: Remove filecmp Index: test_sundry.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sundry.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_sundry.py 3 Dec 2002 09:34:54 -0000 1.12 --- test_sundry.py 13 Feb 2003 18:36:22 -0000 1.13 *************** *** 37,41 **** import dumbdbm import encodings - import filecmp import fnmatch import formatter --- 37,40 ---- From tim_one@users.sourceforge.net Thu Feb 13 18:42:03 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 10:42:03 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.48,1.49 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv18574/Lib/test Modified Files: pickletester.py Log Message: Added a simple NEWOBJ test. This is in the pickle-only part of the test for now (cPickle can't yet produce NEWOBJ). Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** pickletester.py 13 Feb 2003 15:44:40 -0000 1.48 --- pickletester.py 13 Feb 2003 18:42:00 -0000 1.49 *************** *** 725,728 **** --- 725,738 ---- class TempAbstractPickleTests(unittest.TestCase): + def test_simple_newobj(self): + x = object.__new__(SimpleNewObj) # avoid __init__ + x.abc = 666 + for proto in protocols: + s = self.dumps(x, proto) + self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) + y = self.loads(s) # will raise TypeError if __init__ called + self.assertEqual(y.abc, 666) + self.assertEqual(x.__dict__, y.__dict__) + def test_newobj_list_slots(self): x = SlotList([1, 2, 3]) *************** *** 771,774 **** --- 781,789 ---- class SlotList(MyList): __slots__ = ["foo"] + + class SimpleNewObj(object): + def __init__(self, a, b, c): + # raise an error, to make sure this isn't called + raise TypeError("SimpleNewObj.__init__() didn't expect to get called") class AbstractPickleModuleTests(unittest.TestCase): From gvanrossum@users.sourceforge.net Thu Feb 13 18:45:00 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 10:45:00 -0800 Subject: [Python-checkins] python/dist/src/Modules xxmodule.c,2.34,2.35 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv20447 Modified Files: xxmodule.c Log Message: Another dummy type. Curious: Str didn't need me to put something in tp_new, but Null did. Why the difference? Index: xxmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/xxmodule.c,v retrieving revision 2.34 retrieving revision 2.35 diff -C2 -d -r2.34 -r2.35 *** xxmodule.c 11 Feb 2003 21:19:11 -0000 2.34 --- xxmodule.c 13 Feb 2003 18:44:57 -0000 2.35 *************** *** 261,264 **** --- 261,320 ---- }; + /* ---------- */ + + static PyObject * + null_richcompare(PyObject *self, PyObject *other, int op) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + static PyTypeObject Null_Type = { + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "xxmodule.Null", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + null_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + &PyBaseObject_Type, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + }; + /* ---------- */ *************** *** 311,313 **** --- 367,374 ---- return; PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); + + /* Add Null */ + if (PyType_Ready(&Null_Type) < 0) + return; + PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); } From montanaro@users.sourceforge.net Thu Feb 13 19:01:21 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 11:01:21 -0800 Subject: [Python-checkins] python/nondist/peps pep-0305.txt,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv27170 Modified Files: pep-0305.txt Log Message: posted again Index: pep-0305.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0305.txt,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** pep-0305.txt 10 Feb 2003 04:03:49 -0000 1.14 --- pep-0305.txt 13 Feb 2003 19:01:17 -0000 1.15 *************** *** 9,13 **** Content-Type: text/x-rst Created: 26-Jan-2003 ! Post-History: 31-Jan-2003 --- 9,13 ---- Content-Type: text/x-rst Created: 26-Jan-2003 ! Post-History: 31-Jan-2003, 13-Feb-2003 From tim_one@users.sourceforge.net Thu Feb 13 19:30:59 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 11:30:59 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_xpickle.py,NONE,1.1 pickletester.py,1.49,1.50 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv5218 Modified Files: pickletester.py Added Files: test_xpickle.py Log Message: We didn't have any tests making pickles with one of {pickle, cPickle}, and loading them via the other, except for the special cases of this Guido added to test_datetime.py for datetime module objects. The new test_xpickle.py tries all of pickletester's AbstractPickleTests in both x-module ways. --- NEW FILE: test_xpickle.py --- # test_pickle dumps and loads pickles via pickle.py. # test_cpickle does the same, but via the cPickle module. # This test covers the other two cases, making pickles with one module and # loading them via the other. import pickle import cPickle import unittest from cStringIO import StringIO from test import test_support from test.pickletester import AbstractPickleTests class DumpCPickle_LoadPickle(AbstractPickleTests): error = KeyError def dumps(self, arg, proto=0, fast=0): # Ignore fast return cPickle.dumps(arg, proto) def loads(self, buf): # Ignore fast return pickle.loads(buf) class DumpPickle_LoadCPickle(AbstractPickleTests): error = cPickle.BadPickleGet def dumps(self, arg, proto=0, fast=0): # Ignore fast return pickle.dumps(arg, proto) def loads(self, buf): # Ignore fast return cPickle.loads(buf) def test_main(): suite = unittest.TestSuite() for test in (DumpCPickle_LoadPickle, DumpPickle_LoadCPickle, ): suite.addTest(unittest.makeSuite(test)) test_support.run_suite(suite) if __name__ == "__main__": test_main() Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** pickletester.py 13 Feb 2003 18:42:00 -0000 1.49 --- pickletester.py 13 Feb 2003 19:30:57 -0000 1.50 *************** *** 807,810 **** --- 807,815 ---- os.remove(TESTFN) + def test_highest_protocol(self): + # Of course this needs to be changed when HIGHEST_PROTOCOL changes. + self.assertEqual(self.module.HIGHEST_PROTOCOL, 2) + + class AbstractPersistentPicklerTests(unittest.TestCase): From tim_one@users.sourceforge.net Thu Feb 13 19:37:21 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 11:37:21 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_xpickle.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv9016/Lib/test Modified Files: test_xpickle.py Log Message: Removed unused cut'n'paste import. Index: test_xpickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_xpickle.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_xpickle.py 13 Feb 2003 19:30:57 -0000 1.1 --- test_xpickle.py 13 Feb 2003 19:37:19 -0000 1.2 *************** *** 7,11 **** import cPickle import unittest - from cStringIO import StringIO from test import test_support --- 7,10 ---- From tim_one@users.sourceforge.net Thu Feb 13 21:04:02 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 13:04:02 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.132,2.133 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv28537/Modules Modified Files: cPickle.c Log Message: save(): Reformat tail end just for clarity. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.132 retrieving revision 2.133 diff -C2 -d -r2.132 -r2.133 *** cPickle.c 13 Feb 2003 18:24:14 -0000 2.132 --- cPickle.c 13 Feb 2003 21:03:57 -0000 2.133 *************** *** 2456,2462 **** } ! if ((__reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type))) { Py_INCREF(__reduce__); - Py_INCREF(args); ARG_TUP(self, args); --- 2456,2463 ---- } ! assert(t == NULL); /* just a reminder */ ! __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type); ! if (__reduce__ != NULL) { Py_INCREF(__reduce__); Py_INCREF(args); ARG_TUP(self, args); *************** *** 2468,2481 **** } else { ! PyErr_Clear(); ! ! if ((__reduce__ = PyObject_GetAttr(args, __reduce___str))) { t = PyObject_Call(__reduce__, empty_tuple, NULL); if (!t) goto finally; } - else { - PyErr_Clear(); - } } --- 2469,2480 ---- } else { ! __reduce__ = PyObject_GetAttr(args, __reduce___str); ! if (__reduce__ == NULL) ! PyErr_Clear(); ! else { t = PyObject_Call(__reduce__, empty_tuple, NULL); if (!t) goto finally; } } *************** *** 2487,2492 **** if (!PyTuple_Check(t)) { ! cPickle_ErrFormat(PicklingError, "Value returned by %s must " ! "be a tuple", "O", __reduce__); goto finally; } --- 2486,2492 ---- if (!PyTuple_Check(t)) { ! cPickle_ErrFormat(PicklingError, "Value returned by " ! "%s must be a tuple", ! "O", __reduce__); goto finally; } *************** *** 2494,2505 **** size = PyTuple_Size(t); ! if ((size != 3) && (size != 2)) { ! cPickle_ErrFormat(PicklingError, "tuple returned by %s must " ! "contain only two or three elements", "O", __reduce__); goto finally; } callable = PyTuple_GET_ITEM(t, 0); - arg_tup = PyTuple_GET_ITEM(t, 1); --- 2494,2505 ---- size = PyTuple_Size(t); ! if (size != 3 && size != 2) { ! cPickle_ErrFormat(PicklingError, "tuple returned by " ! "%s must contain only two or three elements", ! "O", __reduce__); goto finally; } callable = PyTuple_GET_ITEM(t, 0); arg_tup = PyTuple_GET_ITEM(t, 1); *************** *** 2511,2516 **** if (!( PyTuple_Check(arg_tup) || arg_tup==Py_None )) { ! cPickle_ErrFormat(PicklingError, "Second element of tuple " ! "returned by %s must be a tuple", "O", __reduce__); goto finally; } --- 2511,2517 ---- if (!( PyTuple_Check(arg_tup) || arg_tup==Py_None )) { ! cPickle_ErrFormat(PicklingError, "Second element of " ! "tuple returned by %s must be a tuple", ! "O", __reduce__); goto finally; } From gvanrossum@users.sourceforge.net Thu Feb 13 21:13:20 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 13:13:20 -0800 Subject: [Python-checkins] python/dist/src/Lib pdb.py,1.51,1.51.4.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv32588 Modified Files: Tag: release21-maint pdb.py Log Message: Backport 1.60 -- because this is an annoyance that Zope folks run into and Zope 2.6 (which requires Python 2.1.x) isn't dead yet. Duh. The do_EOF() implementation was bogus. Make it more like do_quit() -- but print a blank line first. Index: pdb.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pdb.py,v retrieving revision 1.51 retrieving revision 1.51.4.1 diff -C2 -d -r1.51 -r1.51.4.1 *** pdb.py 9 Feb 2001 23:28:07 -0000 1.51 --- pdb.py 13 Feb 2003 21:13:17 -0000 1.51.4.1 *************** *** 182,186 **** def do_EOF(self, arg): ! return 0 # Don't die on EOF def do_break(self, arg, temporary = 0): --- 182,188 ---- def do_EOF(self, arg): ! print ! self.set_quit() ! return 1 def do_break(self, arg, temporary = 0): From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:01 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:01 -0800 Subject: [Python-checkins] python/dist/src/Parser parsetok.c,2.34,2.35 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Parser Modified Files: parsetok.c Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: parsetok.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/parsetok.c,v retrieving revision 2.34 retrieving revision 2.35 diff -C2 -d -r2.34 -r2.35 *** parsetok.c 11 Dec 2002 14:04:58 -0000 2.34 --- parsetok.c 13 Feb 2003 22:07:58 -0000 2.35 *************** *** 131,134 **** --- 131,143 ---- type = NEWLINE; /* Add an extra newline */ started = 0; + /* Add the right number of dedent tokens, + except if a certain flag is given -- + codeop.py uses this. */ + if (tok->indent && + !(flags & PyPARSE_DONT_IMPLY_DEDENT)) + { + tok->pendin = -tok->indent; + tok->indent = 0; + } } else From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:25 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:25 -0800 Subject: [Python-checkins] python/dist/src/Include parsetok.h,2.20,2.21 pythonrun.h,2.61,2.62 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Include Modified Files: parsetok.h pythonrun.h Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: parsetok.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/parsetok.h,v retrieving revision 2.20 retrieving revision 2.21 diff -C2 -d -r2.20 -r2.21 *** parsetok.h 11 Dec 2002 14:04:57 -0000 2.20 --- parsetok.h 13 Feb 2003 22:07:52 -0000 2.21 *************** *** 22,25 **** --- 22,27 ---- #endif + #define PyPARSE_DONT_IMPLY_DEDENT 0x0002 + PyAPI_FUNC(node *) PyParser_ParseString(const char *, grammar *, int, perrdetail *); Index: pythonrun.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pythonrun.h,v retrieving revision 2.61 retrieving revision 2.62 diff -C2 -d -r2.61 -r2.62 *** pythonrun.h 10 Feb 2003 08:21:06 -0000 2.61 --- pythonrun.h 13 Feb 2003 22:07:52 -0000 2.62 *************** *** 11,14 **** --- 11,15 ---- #define PyCF_MASK_OBSOLETE (CO_GENERATOR_ALLOWED | CO_NESTED) #define PyCF_SOURCE_IS_UTF8 0x0100 + #define PyCF_DONT_IMPLY_DEDENT 0x0200 typedef struct { From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:27 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:27 -0800 Subject: [Python-checkins] python/dist/src/Lib code.py,1.21,1.22 codeop.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Lib Modified Files: code.py codeop.py Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: code.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/code.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** code.py 4 Apr 2002 22:55:58 -0000 1.21 --- code.py 13 Feb 2003 22:07:53 -0000 1.22 *************** *** 304,306 **** if __name__ == '__main__': ! interact() --- 304,307 ---- if __name__ == '__main__': ! import pdb ! pdb.run("interact()\n") Index: codeop.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/codeop.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** codeop.py 17 Aug 2001 22:11:27 -0000 1.5 --- codeop.py 13 Feb 2003 22:07:54 -0000 1.6 *************** *** 64,67 **** --- 64,69 ---- __all__ = ["compile_command", "Compile", "CommandCompiler"] + PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h + def _maybe_compile(compiler, source, filename, symbol): # Check for source consisting of only blank lines and comments *************** *** 104,107 **** --- 106,112 ---- raise SyntaxError, err1 + def _compile(source, filename, symbol): + return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) + def compile_command(source, filename="", symbol="single"): r"""Compile a command and determine whether it is incomplete. *************** *** 122,126 **** malformed literals). """ ! return _maybe_compile(compile, source, filename, symbol) class Compile: --- 127,131 ---- malformed literals). """ ! return _maybe_compile(_compile, source, filename, symbol) class Compile: *************** *** 130,134 **** with the statement in force.""" def __init__(self): ! self.flags = 0 def __call__(self, source, filename, symbol): --- 135,139 ---- with the statement in force.""" def __init__(self): ! self.flags = PyCF_DONT_IMPLY_DEDENT def __call__(self, source, filename, symbol): From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:00 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:00 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.657,1.658 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Misc Modified Files: NEWS Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.657 retrieving revision 1.658 diff -C2 -d -r1.657 -r1.658 *** NEWS 13 Feb 2003 16:30:16 -0000 1.657 --- NEWS 13 Feb 2003 22:07:56 -0000 1.658 *************** *** 13,16 **** --- 13,24 ---- ----------------- + - Finally fixed the bug in compile() and exec where a string ending + with an indented code block but no newline would raise SyntaxError. + This would have been a four-line change in parsetok.c... Except + codeop.py depends on this behavior, so a compilation flag had to be + invented that causes the tokenizer to revert to the old behavior; + this required extra changes to 2 .h files, 2 .c files, and 2 .py + files. + - If a new-style class defines neither __new__ nor __init__, its constructor would ignore all arguments. This is changed now: the From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:29 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_codeop.py,1.4,1.5 test_compile.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Lib/test Modified Files: test_codeop.py test_compile.py Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: test_codeop.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_codeop.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_codeop.py 23 Jul 2002 19:03:46 -0000 1.4 --- test_codeop.py 13 Feb 2003 22:07:54 -0000 1.5 *************** *** 6,10 **** from test.test_support import run_unittest ! from codeop import compile_command class CodeopTests(unittest.TestCase): --- 6,10 ---- from test.test_support import run_unittest ! from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT class CodeopTests(unittest.TestCase): *************** *** 12,16 **** def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' ! expected = compile(str, "", symbol) self.assertEquals( compile_command(str, "", symbol), expected) --- 12,16 ---- def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' ! expected = compile(str, "", symbol, PyCF_DONT_IMPLY_DEDENT) self.assertEquals( compile_command(str, "", symbol), expected) *************** *** 43,47 **** # special case self.assertEquals(compile_command(""), ! compile("pass", "", 'single')) av("3**3","eval") --- 43,48 ---- # special case self.assertEquals(compile_command(""), ! compile("pass", "", 'single', ! PyCF_DONT_IMPLY_DEDENT)) av("3**3","eval") Index: test_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_compile.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_compile.py 12 Feb 2003 16:57:47 -0000 1.15 --- test_compile.py 13 Feb 2003 22:07:55 -0000 1.16 *************** *** 90,93 **** --- 90,102 ---- expect_error("3-4e/21") + if verbose: + print "testing compile() of indented block w/o trailing newline" + + s = """ + if 1: + if 2: + pass""" + compile(s, "", "exec") + if verbose: From gvanrossum@users.sourceforge.net Thu Feb 13 22:08:02 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:08:02 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.280,2.281 pythonrun.c,2.176,2.177 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv26189/Python Modified Files: bltinmodule.c pythonrun.c Log Message: - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.280 retrieving revision 2.281 diff -C2 -d -r2.280 -r2.281 *** bltinmodule.c 10 Feb 2003 17:36:40 -0000 2.280 --- bltinmodule.c 13 Feb 2003 22:07:58 -0000 2.281 *************** *** 381,385 **** } ! if (supplied_flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE)) { PyErr_SetString(PyExc_ValueError, "compile(): unrecognised flags"); --- 381,387 ---- } ! if (supplied_flags & ! ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT)) ! { PyErr_SetString(PyExc_ValueError, "compile(): unrecognised flags"); Index: pythonrun.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/pythonrun.c,v retrieving revision 2.176 retrieving revision 2.177 diff -C2 -d -r2.176 -r2.177 *** pythonrun.c 24 Jan 2003 16:17:18 -0000 2.176 --- pythonrun.c 13 Feb 2003 22:07:59 -0000 2.177 *************** *** 549,559 **** /* compute parser flags based on compiler flags */ - #if 0 /* future keyword */ #define PARSER_FLAGS(flags) \ ! (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \ ! PyPARSE_YIELD_IS_KEYWORD : 0) ! #else ! #define PARSER_FLAGS(flags) 0 ! #endif int --- 549,555 ---- /* compute parser flags based on compiler flags */ #define PARSER_FLAGS(flags) \ ! (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ ! PyPARSE_DONT_IMPLY_DEDENT : 0) int From tim_one@users.sourceforge.net Thu Feb 13 22:17:08 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:17:08 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.133,2.134 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29988/Modules Modified Files: cPickle.c Log Message: The version of PyImport_Import() in cPickle is no longer needed (an edited version was moved into import.c long ago), so squashed the duplication. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.133 retrieving revision 2.134 diff -C2 -d -r2.133 -r2.134 *** cPickle.c 13 Feb 2003 21:03:57 -0000 2.133 --- cPickle.c 13 Feb 2003 22:17:05 -0000 2.134 *************** *** 825,892 **** } - #define PyImport_Import cPickle_Import - - static PyObject * - PyImport_Import(PyObject *module_name) - { - static PyObject *silly_list=0, *__builtins___str=0, *__import___str; - static PyObject *standard_builtins=0; - PyObject *globals=0, *__import__=0, *__builtins__=0, *r=0; - - if (!( silly_list )) { - if (!( __import___str=PyString_FromString("__import__"))) - return NULL; - if (!( __builtins___str=PyString_FromString("__builtins__"))) - return NULL; - if (!( silly_list=Py_BuildValue("[s]","__doc__"))) - return NULL; - } - - if ((globals=PyEval_GetGlobals())) { - Py_INCREF(globals); - __builtins__=PyObject_GetItem(globals,__builtins___str); - if (!__builtins__) - goto err; - } - else { - PyErr_Clear(); - - if (!(standard_builtins || - (standard_builtins=PyImport_ImportModule("__builtin__")))) - return NULL; - - __builtins__=standard_builtins; - Py_INCREF(__builtins__); - globals = Py_BuildValue("{sO}", "__builtins__", __builtins__); - if (!globals) - goto err; - } - - if (PyDict_Check(__builtins__)) { - __import__=PyObject_GetItem(__builtins__,__import___str); - if (!__import__) goto err; - } - else { - __import__=PyObject_GetAttr(__builtins__,__import___str); - if (!__import__) goto err; - } - - r=PyObject_CallFunction(__import__,"OOOO", - module_name, globals, globals, silly_list); - if (!r) - goto err; - - Py_DECREF(globals); - Py_DECREF(__builtins__); - Py_DECREF(__import__); - - return r; - err: - Py_XDECREF(globals); - Py_XDECREF(__builtins__); - Py_XDECREF(__import__); - return NULL; - } - static PyObject * whichmodule(PyObject *global, PyObject *global_name) --- 825,828 ---- From gvanrossum@users.sourceforge.net Thu Feb 13 22:19:44 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:19:44 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.658,1.659 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv31370 Modified Files: NEWS Log Message: Add SF reference to news item. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.658 retrieving revision 1.659 diff -C2 -d -r1.658 -r1.659 *** NEWS 13 Feb 2003 22:07:56 -0000 1.658 --- NEWS 13 Feb 2003 22:19:20 -0000 1.659 *************** *** 19,23 **** invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py ! files. - If a new-style class defines neither __new__ nor __init__, its --- 19,23 ---- invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py ! files. (Fixes SF bug #501622.) - If a new-style class defines neither __new__ nor __init__, its From rhettinger@users.sourceforge.net Thu Feb 13 22:58:05 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 13 Feb 2003 14:58:05 -0800 Subject: [Python-checkins] python/dist/src/Lib calendar.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv17485 Modified Files: calendar.py Log Message: SF 685011: calendar module overflow handling Restored a Py2.2 behavior to not range check the day of the month. A user application was this exploiting undocumented, accidental "feature". Index: calendar.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/calendar.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** calendar.py 25 Dec 2002 16:37:19 -0000 1.31 --- calendar.py 13 Feb 2003 22:58:02 -0000 1.32 *************** *** 214,218 **** """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] ! days = datetime.date(year, month, day).toordinal() - _EPOCH_ORD hours = days*24 + hour minutes = hours*60 + minute --- 214,218 ---- """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] ! days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute From tim_one@users.sourceforge.net Thu Feb 13 23:00:34 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 13 Feb 2003 15:00:34 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.134,2.135 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv20672/python/Modules Modified Files: cPickle.c Log Message: Minor assorted cleanups; no semantic changes. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.134 retrieving revision 2.135 diff -C2 -d -r2.134 -r2.135 *** cPickle.c 13 Feb 2003 22:17:05 -0000 2.134 --- cPickle.c 13 Feb 2003 23:00:26 -0000 2.135 *************** *** 893,897 **** Py_DECREF(key); PyErr_Format(PyExc_ValueError, ! "fast mode: can't pickle cyclic objects including object type %s at %p", obj->ob_type->tp_name, obj); self->fast_container = -1; --- 893,898 ---- Py_DECREF(key); PyErr_Format(PyExc_ValueError, ! "fast mode: can't pickle cyclic objects " ! "including object type %s at %p", obj->ob_type->tp_name, obj); self->fast_container = -1; *************** *** 2787,2794 **** int proto = 0; ! /* XXX What is this doing? The documented signature is ! * XXX Pickler(file, proto=0), but this accepts Pickler() and ! * XXX Pickler(integer) too. The meaning then is clear as mud. ! * XXX Bug? Feature? */ if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) { --- 2788,2797 ---- int proto = 0; ! /* XXX ! * The documented signature is Pickler(file, proto=0), but this ! * accepts Pickler() and Pickler(integer) too. The meaning then ! * is clear as mud, undocumented, and not supported by pickle.py. ! * I'm told Zope uses this, but I haven't traced into this code ! * far enough to figure out what it means. */ if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) { *************** *** 2950,2955 **** if (fc) { if (fc==Py_None) { ! PyErr_SetString(UnpicklingError, ! "Global and instance pickles are not supported."); return NULL; } --- 2953,2958 ---- if (fc) { if (fc==Py_None) { ! PyErr_SetString(UnpicklingError, "Global and instance " ! "pickles are not supported."); return NULL; } *************** *** 3865,3869 **** PyErr_SetObject(BadPickleGet, py_str); rc = -1; ! } else { PDATA_APPEND(self->stack, value, -1); rc = 0; --- 3868,3873 ---- PyErr_SetObject(BadPickleGet, py_str); rc = -1; ! } ! else { PDATA_APPEND(self->stack, value, -1); rc = 0; *************** *** 3892,3896 **** PyErr_SetObject(BadPickleGet, py_key); rc = -1; ! } else { PDATA_APPEND(self->stack, value, -1); rc = 0; --- 3896,3901 ---- PyErr_SetObject(BadPickleGet, py_key); rc = -1; ! } ! else { PDATA_APPEND(self->stack, value, -1); rc = 0; *************** *** 3928,3932 **** PyErr_SetObject(BadPickleGet, py_key); rc = -1; ! } else { PDATA_APPEND(self->stack, value, -1); rc = 0; --- 3933,3938 ---- PyErr_SetObject(BadPickleGet, py_key); rc = -1; ! } ! else { PDATA_APPEND(self->stack, value, -1); rc = 0; From tim.one@comcast.net Thu Feb 13 23:06:41 2003 From: tim.one@comcast.net (Tim Peters) Date: Thu, 13 Feb 2003 18:06:41 -0500 Subject: [Python-checkins] python/dist/src/Lib calendar.py,1.31,1.32 In-Reply-To: Message-ID: [rhettinger@users.sourceforge.net] > Update of /cvsroot/python/python/dist/src/Lib > In directory sc8-pr-cvs1:/tmp/cvs-serv17485 > > Modified Files: > calendar.py > Log Message: > SF 685011: calendar module overflow handling > > Restored a Py2.2 behavior to not range check the day of the month. > A user application was this exploiting undocumented, accidental "feature". Heh. If you've learned that no line of code can ever be changed without *someone* whining about it, I won't make you learn that lesson again . From akuchling@users.sourceforge.net Fri Feb 14 01:13:04 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 13 Feb 2003 17:13:04 -0800 Subject: [Python-checkins] python/dist/src/Lib asyncore.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv4486 Modified Files: asyncore.py Log Message: Fix comment typo Index: asyncore.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/asyncore.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** asyncore.py 26 Dec 2002 18:22:54 -0000 1.39 --- asyncore.py 14 Feb 2003 01:13:01 -0000 1.40 *************** *** 362,366 **** return getattr(self.socket, attr) ! # log and log_info maybe overriden to provide more sophisitcated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging. --- 362,366 ---- return getattr(self.socket, attr) ! # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging. From akuchling@users.sourceforge.net Fri Feb 14 01:14:19 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Thu, 13 Feb 2003 17:14:19 -0800 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv4808 Modified Files: textwrap.py Log Message: Fix docstring typo Index: textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** textwrap.py 3 Feb 2003 14:46:57 -0000 1.23 --- textwrap.py 14 Feb 2003 01:14:15 -0000 1.24 *************** *** 54,58 **** fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed ! by two spaces. Off by default becaus the algorithm is (unavoidably) imperfect. break_long_words (default: true) --- 54,58 ---- fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed ! by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) From nnorwitz@users.sourceforge.net Fri Feb 14 01:45:57 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 13 Feb 2003 17:45:57 -0800 Subject: [Python-checkins] python/dist/src/Doc Makefile.deps,1.97,1.98 Message-ID: Update of /cvsroot/python/python/dist/src/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv13866 Modified Files: Makefile.deps Log Message: Remove deps on mac doc files which have been removed Index: Makefile.deps =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/Makefile.deps,v retrieving revision 1.97 retrieving revision 1.98 diff -C2 -d -r1.97 -r1.98 *** Makefile.deps 28 Jan 2003 21:53:05 -0000 1.97 --- Makefile.deps 14 Feb 2003 01:45:53 -0000 1.98 *************** *** 348,356 **** mac/libaepack.tex \ mac/libaetypes.tex \ - mac/libctb.tex \ mac/libmacfs.tex \ mac/libmacos.tex \ mac/libmacostools.tex \ - mac/libmacspeech.tex \ mac/libmacui.tex \ mac/libmacic.tex \ --- 348,354 ---- From rhettinger@users.sourceforge.net Fri Feb 14 01:49:12 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 13 Feb 2003 17:49:12 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libsets.tex,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv14510 Modified Files: libsets.tex Log Message: SF bug #663701. The caret wasn't printing well in the PDF documentation. Index: libsets.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libsets.tex,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** libsets.tex 15 Jan 2003 15:46:05 -0000 1.9 --- libsets.tex 14 Feb 2003 01:49:09 -0000 1.10 *************** *** 94,98 **** \lineii{\var{s}.difference(\var{t})} {new set with elements in \var{s} but not in \var{t}} ! \lineii{\var{s} \textasciicircum\ \var{t}} {new set with elements in either \var{s} or \var{t} but not both} \lineii{\var{s}.symmetric_difference(\var{t})} --- 94,98 ---- \lineii{\var{s}.difference(\var{t})} {new set with elements in \var{s} but not in \var{t}} ! \lineii{\var{s} \^\ \var{t}} {new set with elements in either \var{s} or \var{t} but not both} \lineii{\var{s}.symmetric_difference(\var{t})} From rhettinger@users.sourceforge.net Fri Feb 14 03:42:13 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 13 Feb 2003 19:42:13 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libsets.tex,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv16656/Doc/lib Modified Files: libsets.tex Log Message: SF bug #663701: sets module review Renamed hook methods to use the double underscore convention. Index: libsets.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libsets.tex,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** libsets.tex 14 Feb 2003 01:49:09 -0000 1.10 --- libsets.tex 14 Feb 2003 03:42:11 -0000 1.11 *************** *** 204,210 **** The mechanism is to always add a hashable element, or if it is not hashable, the element is checked to see if it has an ! \method{_as_immutable()} method which returns an immutable equivalent. ! Since \class{Set} objects have a \method{_as_immutable()} method returning an instance of \class{ImmutableSet}, it is possible to construct sets of sets. --- 204,210 ---- The mechanism is to always add a hashable element, or if it is not hashable, the element is checked to see if it has an ! \method{__as_immutable__()} method which returns an immutable equivalent. ! Since \class{Set} objects have a \method{__as_immutable__()} method returning an instance of \class{ImmutableSet}, it is possible to construct sets of sets. *************** *** 213,217 **** \method{remove()} methods which need to hash an element to check for membership in a set. Those methods check an element for hashability ! and, if not, check for a \method{_as_temporarily_immutable()} method which returns the element wrapped by a class that provides temporary methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}. --- 213,217 ---- \method{remove()} methods which need to hash an element to check for membership in a set. Those methods check an element for hashability ! and, if not, check for a \method{__as_temporarily_immutable__()} method which returns the element wrapped by a class that provides temporary methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}. *************** *** 220,224 **** the original mutable object. ! \class{Set} objects implement the \method{_as_temporarily_immutable()} method which returns the \class{Set} object wrapped by a new class \class{_TemporarilyImmutableSet}. --- 220,224 ---- the original mutable object. ! \class{Set} objects implement the \method{__as_temporarily_immutable__()} method which returns the \class{Set} object wrapped by a new class \class{_TemporarilyImmutableSet}. From rhettinger@users.sourceforge.net Fri Feb 14 03:42:13 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 13 Feb 2003 19:42:13 -0800 Subject: [Python-checkins] python/dist/src/Lib sets.py,1.41,1.42 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv16656/Lib Modified Files: sets.py Log Message: SF bug #663701: sets module review Renamed hook methods to use the double underscore convention. Index: sets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sets.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** sets.py 9 Feb 2003 06:40:57 -0000 1.41 --- sets.py 14 Feb 2003 03:42:11 -0000 1.42 *************** *** 249,253 **** return element in self._data except TypeError: ! transform = getattr(element, "_as_temporarily_immutable", None) if transform is None: raise # re-raise the TypeError exception we caught --- 249,253 ---- return element in self._data except TypeError: ! transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught *************** *** 326,330 **** return except TypeError: ! transform = getattr(element, "_as_immutable", None) if transform is None: raise # re-raise the TypeError exception we caught --- 326,330 ---- return except TypeError: ! transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught *************** *** 336,340 **** data[element] = value except TypeError: ! transform = getattr(element, "_as_immutable", None) if transform is None: raise # re-raise the TypeError exception we caught --- 336,340 ---- data[element] = value except TypeError: ! transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught *************** *** 465,469 **** self._data[element] = True except TypeError: ! transform = getattr(element, "_as_immutable", None) if transform is None: raise # re-raise the TypeError exception we caught --- 465,469 ---- self._data[element] = True except TypeError: ! transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught *************** *** 478,482 **** del self._data[element] except TypeError: ! transform = getattr(element, "_as_temporarily_immutable", None) if transform is None: raise # re-raise the TypeError exception we caught --- 478,482 ---- del self._data[element] except TypeError: ! transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught *************** *** 497,505 **** return self._data.popitem()[0] ! def _as_immutable(self): # Return a copy of self as an immutable set return ImmutableSet(self) ! def _as_temporarily_immutable(self): # Return self wrapped in a temporarily immutable set return _TemporarilyImmutableSet(self) --- 497,505 ---- return self._data.popitem()[0] ! def __as_immutable__(self): # Return a copy of self as an immutable set return ImmutableSet(self) ! def __as_temporarily_immutable__(self): # Return self wrapped in a temporarily immutable set return _TemporarilyImmutableSet(self) From mhammond@users.sourceforge.net Fri Feb 14 04:03:56 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Thu, 13 Feb 2003 20:03:56 -0800 Subject: [Python-checkins] python/nondist/peps pep-0311.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv23483 Added Files: pep-0311.txt Log Message: New PEP 311: Simplified Global Interpreter Lock acquisition for extensions --- NEW FILE: pep-0311.txt --- PEP: 311 Title: Simplified Global Interpreter Lock acquisition for extensions Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/02/14 04:03:52 $ Author: Mark Hammond Status: Draft Type: Content-Type: text/plain Created: 05-Feb-2003 Post-History: 05-Feb-2003 14-Feb-2003 Open Issues This is where I note comments from people that are yet to be resolved. - JustvR prefers a PyGIL prefix over PyAutoThreadState. - JackJ notes that the "Auto" prefix will look a little silly in a few years, assuming this becomes the standard way of managing the lock. He doesn't really like Just's "GIL", and suggested "PyIntLock" - JackJ prefers "Acquire" over "Ensure", even though the semantics are different than for other "Acquire" functions in the API. Mark still prefers Ensure for exactly this reason. - Mark notes Dutch people must love names, and still remembers "pulling dead cows from the ditch" (but has forgotten the Dutch!) He also hopes Jack remembers the reference . - Should we provide Py_AUTO_THREAD_STATE macros? - Is my "Limitation" regarding PyEval_InitThreads() OK? Abstract This PEP proposes a simplified API for access to the Global Interpreter Lock (GIL) for Python extension modules. Specifically, it provides a solution for authors of complex multi-threaded extensions, where the current state of Python (i.e., the state of the GIL is unknown. This PEP proposes a new API, for platforms built with threading support, to manage the Python thread state. An implementation strategy is proposed, along with an initial, platform independent implementation. Rationale The current Python interpreter state API is suitable for simple, single-threaded extensions, but quickly becomes incredibly complex for non-trivial, multi-threaded extensions. Currently Python provides two mechanisms for dealing with the GIL: - Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros. These macros are provided primarily to allow a simple Python extension that already owns the GIL to temporarily release it while making an "external" (ie, non-Python), generally expensive, call. Any existing Python threads that are blocked waiting for the GIL are then free to run. While this is fine for extensions making calls from Python into the outside world, it is no help for extensions that need to make calls into Python when the thread state is unknown. - PyThreadState and PyInterpreterState APIs. These API functions allow an extension/embedded application to acquire the GIL, but suffer from a serious boot-strapping problem - they require you to know the state of the Python interpreter and of the GIL before they can be used. One particular problem is for extension authors that need to deal with threads never before seen by Python, but need to call Python from this thread. It is very difficult, delicate and error prone to author an extension where these "new" threads always know the exact state of the GIL, and therefore can reliably interact with this API. For these reasons, the question of how such extensions should interact with Python is quickly becoming a FAQ. The main impetus for this PEP, a thread on python-dev [1], immediately identified the following projects with this exact issue: - The win32all extensions - Boost - ctypes - Python-GTK bindings - Uno - PyObjC - Mac toolbox - PyXPCOM Currently, there is no reasonable, portable solution to this problem, forcing each extension author to implement their own hand-rolled version. Further, the problem is complex, meaning many implementations are likely to be incorrect, leading to a variety of problems that will often manifest simply as "Python has hung". While the biggest problem in the existing thread-state API is the lack of the ability to query the current state of the lock, it is felt that a more complete, simplified solution should be offered to extension authors. Such a solution should encourage authors to provide error-free, complex extension modules that take full advantage of Python's threading mechanisms. Limitations and Exclusions This proposal identifies a solution for extension authors with complex multi-threaded requirements, but that only require a single "PyInterpreterState". There is no attempt to cater for extensions that require multiple interpreter states. At the time of writing, no extension has been identified that requires multiple PyInterpreterStates, and indeed it is not clear if that facility works correctly in Python itself. This API will not perform automatic initialization of Python, or initialize Python for multi-threaded operation. Extension authors must continue to call Py_Initialize(), and for multi-threaded applications, PyEval_InitThreads(). The reason for this is that the first thread to call PyEval_InitThreads() is nominated as the "main thread" by Python, and so forcing the extension author to specifiy the main thread (by forcing her to make this first call) removes ambiguity. As Py_Initialize() must be called before PyEval_InitThreads(), and as both of these functions currently support being called multiple times, the burden this places on extension authors is considered reasonable. It is intended that this API be all that is necessary to acquire the Python GIL. Apart from the existing, standard Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros, it is assumed that no additional thread state API functions will be used by the extension. Extensions with such complicated requirements are free to continue to use the existing thread state API. Proposal This proposal recommends a new API be added to Python to simplify the management of the GIL. This API will be available on all platforms built with WITH_THREAD defined. The intent is that an extension author be able to use a small, well-defined "prologue dance", at any time and on any thread, and assuming Python has correctly been initialized, this dance will ensure Python is ready to be used on that thread. After the extension has finished with Python, it must also perform an "epilogue dance" to release any resources previously acquired. Ideally, these dances can be expressed in a single line. Specifically, the following new APIs are proposed: /* Ensure that the current thread is ready to call the Python C API, regardless of the current state of Python, or of its thread lock. This may be called as many times as desired by a thread, so long as each call is matched with a call to PyAutoThreadState_Release() The return value is an opaque "handle" to the thread state when PyAutoThreadState_Ensure() was called, and must be passed to PyAutoThreadState_Release() to ensure Python is left in the same state. When the function returns, the current thread will hold the GIL. Thus, the GIL is held by the thread until PyAutoThreadState_Release() is called. (Note that as happens now in Python, calling a Python API function may indeed cause a thread-switch and therefore a GIL ownership change. However, Python guarantees that when the API function returns, the GIL will again be owned by the thread making the call) Failure is a fatal error. */ PyAutoThreadState_State PyAutoThreadState_Ensure(void); /* Release any resources previously acquired. After this call, Python's state will be the same as it was prior to the corresponding PyAutoThreadState_Ensure call (but generally this state will be unknown to the caller, hence the use of the AutoThreadState API.) Every call to PyAutoThreadState_Ensure must be matched by a call to PyAutoThreadState_Release on the same thread. */ void PyAutoThreadState_Release(PyAutoThreadState_State state); Common usage will be: void SomeCFunction(void) { /* ensure we hold the lock */ PyAutoThreadState_State state = PyAutoThreadState_Ensure(); /* Use the Python API */ ... /* Restore the state of Python */ PyAutoThreadState_Release(state); } Design and Implementation The general operation of PyAutoThreadState_Ensure() will be: - assert Python is initialized. - Get a PyThreadState for the current thread, creating and saving if necessary. - remember the current state of the lock (owned/not owned) - If the current state does not own the GIL, acquire it. - Increment a counter for how many calls to PyAutoThreadState_Ensure have been made on the current thread. - return The general operation of PyAutoThreadState_Release() will be: - assert our thread currently holds the lock. - If old state indicates lock as previously unlocked, release GIL. - Decrement the PyAutoThreadState_Ensure counter for the thread. - If counter == 0: - release the PyThreadState. - forget the ThreadState as being owned by the thread. - return It is assumed that it is an error if two discrete PyThreadStates are used for a single thread. Comments in pystate.h ("State unique per thread") support this view, although it is never directly stated. Thus, this will require some implementation of Thread Local Storage. Fortunately, a platform independent implementation of Thread Local Storage already exists in the Python source tree, in the SGI threading port. This code will be integrated into the platform independent Python core, but in such a way that platforms can provide a more optimal implementation if desired. Implementation An implementation of this proposal can be found at http://www.python.org/sf/684256 References [1] http://mail.python.org/pipermail/python-dev/2002-December/031424.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From montanaro@users.sourceforge.net Fri Feb 14 05:45:34 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 21:45:34 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.111,1.112 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv19011 Modified Files: libos.tex Log Message: add missing description of os.extsep Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.111 retrieving revision 1.112 diff -C2 -d -r1.111 -r1.112 *** libos.tex 7 Feb 2003 02:27:36 -0000 1.111 --- libos.tex 14 Feb 2003 05:45:31 -0000 1.112 *************** *** 1644,1647 **** --- 1644,1652 ---- \end{datadesc} + \begin{datadesc}{extsep} + The character which separates the base filename from the extension, + e.g. \character{.} in \code{os.py}. + \end{datadesc} + \begin{datadesc}{pathsep} The character conventionally used by the operating system to separate From montanaro@users.sourceforge.net Fri Feb 14 05:46:55 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 21:46:55 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.74.2.1.2.10,1.74.2.1.2.11 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv19273 Modified Files: Tag: release22-maint libos.tex Log Message: add missing description of os.extsep Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.74.2.1.2.10 retrieving revision 1.74.2.1.2.11 diff -C2 -d -r1.74.2.1.2.10 -r1.74.2.1.2.11 *** libos.tex 7 Feb 2003 02:29:01 -0000 1.74.2.1.2.10 --- libos.tex 14 Feb 2003 05:46:52 -0000 1.74.2.1.2.11 *************** *** 1335,1338 **** --- 1335,1343 ---- \end{datadesc} + \begin{datadesc}{extsep} + The character which separates the base filename from the extension, + e.g. \character{.} in \code{os.py}. + \end{datadesc} + \begin{datadesc}{pathsep} The character conventionally used by the operating system to separate From goodger@users.sourceforge.net Fri Feb 14 05:50:00 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Thu, 13 Feb 2003 21:50:00 -0800 Subject: [Python-checkins] python/nondist/peps pep-0312.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv19967/python/nondist/peps Added Files: pep-0312.txt Log Message: "Simple Implicit Lambda", by Suzi & Martelli --- NEW FILE: pep-0312.txt --- PEP: 312 Title: Simple Implicit Lambda Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/02/14 05:49:58 $ Author: Roman Suzi , Alex Martelli Status: Draft Type: Standards Track Content-Type: text/plain Created: 11-Feb-2003 Python-Version: 2.4 Post-History: Abstract This PEP proposes to make argumentless lambda keyword optional in some cases where it is not grammatically ambiguous. Motivation Lambdas are useful for defining anonymous functions, e.g. for use as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas are not used when they would be appropriate, just because the keyword "lambda" makes code look complex. Omitting lambda in some special cases is possible, with small and backwards compatible changes to the grammar, and provides a cheap cure against such "lambdaphobia". Rationale Sometimes people do not use lambdas because they fear to introduce a term with a theory behind it. This proposal makes introducing argumentless lambdas easier, by omitting the "lambda" keyword. itself. Implementation can be done simply changing grammar so it lets the "lambda" keyword be implied in a few well-known cases. In particular, adding surrounding brackets lets you specify nullary lambda anywhere. Syntax An argumentless "lambda" keyword can be omitted in the following cases: * immediately after "=" in named parameter assignment or default value assignment; * immediately after "(" in any expression; * immediately after a "," in a function argument list; * immediately after a ":" in a dictionary literal; (not implemented) * in an assignment statement; (not implemented) Examples of Use 1) Inline "if": def ifelse(cond, true_part, false_part): if cond: return true_part() else: return false_part() # old syntax: print ifelse(a < b, lambda:A, lambda:B) # new syntax: print ifelse(a < b, :A, :B) # parts A and B may require extensive processing, as in: print ifelse(a < b, :ext_proc1(A), :ext_proc2(B)) 2) Locking: def with(alock, acallable): alock.acquire() try: acallable() finally: alock.release() with(mylock, :x(y(), 23, z(), 'foo')) Implementation Implementation requires some tweaking of the Grammar/Grammar file in the Python sources, and some adjustment of Modules/parsermodule.c to make syntactic and pragmatic changes. (Some grammar/parser guru is needed to make a full implementation.) Here are the changes needed to Grammar to allow implicit lambda: varargslist: (fpdef ['=' imptest] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) | fpdef ['=' imptest] (',' fpdef ['=' imptest])* [','] imptest: test | implambdef atom: '(' [imptestlist] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+ implambdef: ':' test imptestlist: imptest (',' imptest)* [','] argument: [test '='] imptest Three new non-terminals are needed: imptest for the place where implicit lambda may occur, implambdef for the implicit lambda definition itself, imptestlist for a place where imptest's may occur. This implementation is not complete. First, because some files in Parser module need to be updated. Second, some additional places aren't implemented, see Syntax section above. Discussion This feature is not a high-visibility one (the only novel part is the absence of lambda). The feature is intended to make null-ary lambdas more appealing syntactically, to provide lazy evaluation of expressions in some simple cases. This proposal is not targeted at more advanced cases (demanding arguments for the lambda). There is an alternative proposition for implicit lambda: implicit lambda with unused arguments. In this case the function defined by such lambda can accept any parameters, i.e. be equivalent to: lambda *args: expr. This form would be more powerful. Grep in the standard library revealed that such lambdas are indeed in use. One more extension can provide a way to have a list of parameters passed to a function defined by implicit lambda. However, such parameters need some special name to be accessed and are unlikely to be included in the language. Possible local names for such parameters are: _, __args__, __. For example: reduce(:_[0] + _[1], [1,2,3], 0) reduce(:__[0] + __[1], [1,2,3], 0) reduce(:__args__[0] + __args__[1], [1,2,3], 0) These forms do not look very nice, and in the PEP author's opinion do not justify the removal of the lambda keyword in such cases. Credits The idea of dropping lambda was first coined by Paul Rubin at 08 Feb 2003 16:39:30 -0800 in comp.lang.python while discussing the thread "For review: PEP 308 - If-then-else expression". Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From montanaro@users.sourceforge.net Fri Feb 14 06:25:48 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 22:25:48 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv28768 Modified Files: libcsv.tex Log Message: document lack of Unicode support and problematic handling of ASCII NULs. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** libcsv.tex 13 Feb 2003 17:30:30 -0000 1.7 --- libcsv.tex 14 Feb 2003 06:25:44 -0000 1.8 *************** *** 29,32 **** --- 29,37 ---- form using the \class{DictReader} and {}\class{DictWriter} classes. + \note{The first version of the \module{csv} module doesn't support Unicode + input. Also, there are currently some issues regarding ASCII NUL + characters. Accordingly, all input should generally be plain ASCII to be + safe. These restrictions will be removed in the future.} + \subsection{Module Contents} From andrewmcnamara@users.sourceforge.net Fri Feb 14 06:32:42 2003 From: andrewmcnamara@users.sourceforge.net (andrewmcnamara@users.sourceforge.net) Date: Thu, 13 Feb 2003 22:32:42 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30254 Modified Files: _csv.c Log Message: Catch the case where a multi-line field is not completed before hitting end of input and raise an exception. Fixed missing check on string conversion in reader. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** _csv.c 13 Feb 2003 16:02:50 -0000 1.30 --- _csv.c 14 Feb 2003 06:32:40 -0000 1.31 *************** *** 625,630 **** do { lineobj = PyIter_Next(self->input_iter); ! if (!lineobj) return NULL; if (self->had_parse_error) { --- 625,635 ---- do { lineobj = PyIter_Next(self->input_iter); ! if (lineobj == NULL) { ! /* End of input OR exception */ ! if (!PyErr_Occurred() && self->field_len != 0) ! return PyErr_Format(error_obj, ! "newline inside string"); return NULL; + } if (self->had_parse_error) { *************** *** 638,641 **** --- 643,650 ---- } line = PyString_AsString(lineobj); + if (line == NULL) { + Py_DECREF(lineobj); + return NULL; + } /* Process line of text - send '\0' to processing code to *************** *** 1046,1051 **** return 0; ! return PyEval_CallFunction(self->writeline, ! "(s#)", self->rec, self->rec_len); } --- 1055,1060 ---- return 0; ! return PyObject_CallFunction(self->writeline, ! "(s#)", self->rec, self->rec_len); } From fdrake@users.sourceforge.net Fri Feb 14 06:39:39 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Thu, 13 Feb 2003 22:39:39 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.112,1.113 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv32642 Modified Files: libos.tex Log Message: extsep description: - avoid "e.g." in text - record version information (should be backported) Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** libos.tex 14 Feb 2003 05:45:31 -0000 1.112 --- libos.tex 14 Feb 2003 06:39:37 -0000 1.113 *************** *** 1645,1650 **** \begin{datadesc}{extsep} ! The character which separates the base filename from the extension, ! e.g. \character{.} in \code{os.py}. \end{datadesc} --- 1645,1651 ---- \begin{datadesc}{extsep} ! The character which separates the base filename from the extension; ! for example, the \character{.} in \file{os.py}. ! \versionadded{2.2} \end{datadesc} From montanaro@users.sourceforge.net Fri Feb 14 06:46:27 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 13 Feb 2003 22:46:27 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.74.2.1.2.11,1.74.2.1.2.12 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv2465 Modified Files: Tag: release22-maint libos.tex Log Message: backporting Fred's doc fix. Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.74.2.1.2.11 retrieving revision 1.74.2.1.2.12 diff -C2 -d -r1.74.2.1.2.11 -r1.74.2.1.2.12 *** libos.tex 14 Feb 2003 05:46:52 -0000 1.74.2.1.2.11 --- libos.tex 14 Feb 2003 06:46:24 -0000 1.74.2.1.2.12 *************** *** 1336,1341 **** \begin{datadesc}{extsep} ! The character which separates the base filename from the extension, ! e.g. \character{.} in \code{os.py}. \end{datadesc} --- 1336,1342 ---- \begin{datadesc}{extsep} ! The character which separates the base filename from the extension; ! for example, the \character{.} in \code{os.py}. ! \versionadded{2.2} \end{datadesc} From doerwalter@users.sourceforge.net Fri Feb 14 11:21:55 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 14 Feb 2003 03:21:55 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_charmapcodec,1.3,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv6642/Lib/test/output Removed Files: test_charmapcodec Log Message: Port test_charmapcodec to PyUnit. From SF patch #662807 --- test_charmapcodec DELETED --- From doerwalter@users.sourceforge.net Fri Feb 14 11:21:56 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 14 Feb 2003 03:21:56 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_charmapcodec.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6642/Lib/test Modified Files: test_charmapcodec.py Log Message: Port test_charmapcodec to PyUnit. From SF patch #662807 Index: test_charmapcodec.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_charmapcodec.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_charmapcodec.py 23 Aug 2001 18:57:01 -0000 1.5 --- test_charmapcodec.py 14 Feb 2003 11:21:53 -0000 1.6 *************** *** 10,43 **** """#" ! def check(a, b): ! if a != b: ! print '*** check failed: %s != %s' % (repr(a), repr(b)) ! else: ! print '%s == %s: OK' % (a, b) # test codec's full path name (see test/testcodec.py) codecname = 'test.testcodec' ! check(unicode('abc', codecname), u'abc') ! check(unicode('xdef', codecname), u'abcdef') ! check(unicode('defx', codecname), u'defabc') ! check(unicode('dxf', codecname), u'dabcf') ! check(unicode('dxfx', codecname), u'dabcfabc') ! check(u'abc'.encode(codecname), 'abc') ! check(u'xdef'.encode(codecname), 'abcdef') ! check(u'defx'.encode(codecname), 'defabc') ! check(u'dxf'.encode(codecname), 'dabcf') ! check(u'dxfx'.encode(codecname), 'dabcfabc') ! check(unicode('ydef', codecname), u'def') ! check(unicode('defy', codecname), u'def') ! check(unicode('dyf', codecname), u'df') ! check(unicode('dyfy', codecname), u'df') ! try: ! unicode('abc\001', codecname) ! except UnicodeError: ! print '\\001 maps to undefined: OK' ! else: ! print '*** check failed: \\001 does not map to undefined' --- 10,47 ---- """#" ! import test.test_support, unittest # test codec's full path name (see test/testcodec.py) codecname = 'test.testcodec' ! class CharmapCodecTest(unittest.TestCase): ! def test_constructorx(self): ! self.assertEquals(unicode('abc', codecname), u'abc') ! self.assertEquals(unicode('xdef', codecname), u'abcdef') ! self.assertEquals(unicode('defx', codecname), u'defabc') ! self.assertEquals(unicode('dxf', codecname), u'dabcf') ! self.assertEquals(unicode('dxfx', codecname), u'dabcfabc') ! def test_encodex(self): ! self.assertEquals(u'abc'.encode(codecname), 'abc') ! self.assertEquals(u'xdef'.encode(codecname), 'abcdef') ! self.assertEquals(u'defx'.encode(codecname), 'defabc') ! self.assertEquals(u'dxf'.encode(codecname), 'dabcf') ! self.assertEquals(u'dxfx'.encode(codecname), 'dabcfabc') ! def test_constructory(self): ! self.assertEquals(unicode('ydef', codecname), u'def') ! self.assertEquals(unicode('defy', codecname), u'def') ! self.assertEquals(unicode('dyf', codecname), u'df') ! self.assertEquals(unicode('dyfy', codecname), u'df') ! def test_maptoundefined(self): ! self.assertRaises(UnicodeError, unicode, 'abc\001', codecname) ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(CharmapCodecTest)) ! test.test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() From mwh@python.net Fri Feb 14 12:15:27 2003 From: mwh@python.net (Michael Hudson) Date: Fri, 14 Feb 2003 12:15:27 +0000 Subject: [Python-checkins] python/dist/src/Modules xxmodule.c,2.34,2.35 In-Reply-To: (gvanrossum@users.sourceforge.net's message of "Thu, 13 Feb 2003 10:45:00 -0800") References: Message-ID: <2mfzqrhxcw.fsf@starship.python.net> gvanrossum@users.sourceforge.net writes: > Update of /cvsroot/python/python/dist/src/Modules > In directory sc8-pr-cvs1:/tmp/cvs-serv20447 > > Modified Files: > xxmodule.c > Log Message: > Another dummy type. > > Curious: Str didn't need me to put something in tp_new, but Null did. > Why the difference? I imagine this code from Objects/typeobject.c:inherit_special has something to do with it: if (base != &PyBaseObject_Type || (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { if (type->tp_new == NULL) type->tp_new = base->tp_new; } There's a comment block explaining the code just above it, but I didn't read it :-) Cheers, M. -- You can lead an idiot to knowledge but you cannot make him think. You can, however, rectally insert the information, printed on stone tablets, using a sharpened poker. -- Nicolai -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From jackjansen@users.sourceforge.net Fri Feb 14 12:47:19 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 04:47:19 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX setupDocs.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv9982 Modified Files: setupDocs.py Log Message: Got building documentation from source to work. Index: setupDocs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/setupDocs.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** setupDocs.py 28 Aug 2002 22:22:10 -0000 1.1 --- setupDocs.py 14 Feb 2003 12:47:14 -0000 1.2 *************** *** 58,65 **** os.chdir(workdir); ! def buildDocsFromSouce(self): ! #Totally untested ! spawn(('make','--directory', '../Docs'), 1, self.verbose, self.dry_run) ! copy_tree('../Docs/html', self.doc_dir) def ensureHtml(self): --- 58,64 ---- os.chdir(workdir); ! def buildDocsFromSource(self): ! spawn(('make','--directory', '../../Doc', 'html'), 1, self.verbose, self.dry_run) ! copy_tree('../../Doc/html', self.doc_dir) def ensureHtml(self): From jackjansen@users.sourceforge.net Fri Feb 14 14:12:04 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 06:12:04 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv8973 Modified Files: pimp.py Log Message: Factored out classes for handling source and binary distributions. Source now means "distutils-based source", binary "bdist format archive". Also fixed various lurking bugs. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** pimp.py 12 Feb 2003 16:37:00 -0000 1.9 --- pimp.py 14 Feb 2003 14:11:59 -0000 1.10 *************** *** 32,35 **** --- 32,38 ---- PIMP_VERSION="0.1" + # Flavors: + # source: setup-based package + # binary: tar (or other) archive created with setup.py bdist. DEFAULT_FLAVORORDER=['source', 'binary'] DEFAULT_DOWNLOADDIR='/tmp' *************** *** 39,47 **** ARCHIVE_FORMATS = [ ! (".tar.Z", "zcat \"%s\" | tar xf -"), ! (".taz", "zcat \"%s\" | tar xf -"), ! (".tar.gz", "zcat \"%s\" | tar xf -"), ! (".tgz", "zcat \"%s\" | tar xf -"), ! (".tar.bz", "bzcat \"%s\" | tar xf -"), ] --- 42,50 ---- ARCHIVE_FORMATS = [ ! (".tar.Z", "zcat \"%s\" | tar -xf -"), ! (".taz", "zcat \"%s\" | tar -xf -"), ! (".tar.gz", "zcat \"%s\" | tar -xf -"), ! (".tgz", "zcat \"%s\" | tar -xf -"), ! (".tar.bz", "bzcat \"%s\" | tar -xf -"), ] *************** *** 133,136 **** --- 136,144 ---- self._description = "" + def close(self): + """Clean up""" + self._packages = [] + self.preferences = None + def appendURL(self, url, included=0): """Append packages from the database with the given URL. *************** *** 162,166 **** for p in packages: ! pkg = PimpPackage(self, dict(p)) self._packages.append(pkg) --- 170,181 ---- for p in packages: ! p = dict(p) ! flavor = p.get('Flavor') ! if flavor == 'source': ! pkg = PimpPackage_source(self, p) ! elif flavor == 'binary': ! pkg = PimpPackage_binary(self, p) ! else: ! pkg = PimpPackage(self, dict(p)) self._packages.append(pkg) *************** *** 176,179 **** --- 191,195 ---- for pkg in self._packages: rv.append(pkg.fullname()) + rv.sort() return rv *************** *** 267,271 **** def flavor(self): return self._dict['Flavor'] def description(self): return self._dict['Description'] ! def homepage(self): return self._dict['Home-page'] def downloadURL(self): return self._dict['Download-URL'] --- 283,287 ---- def flavor(self): return self._dict['Flavor'] def description(self): return self._dict['Description'] ! def homepage(self): return self._dict.get('Home-page') def downloadURL(self): return self._dict['Download-URL'] *************** *** 343,347 **** if not self._dict.get('Download-URL'): return [(None, "This package needs to be installed manually")] ! if not self._dict['Prerequisites']: return [] for item in self._dict['Prerequisites']: --- 359,363 ---- if not self._dict.get('Download-URL'): return [(None, "This package needs to be installed manually")] ! if not self._dict.get('Prerequisites'): return [] for item in self._dict['Prerequisites']: *************** *** 382,386 **** return rv ! def downloadSinglePackage(self, output=None): """Download a single package, if needed. --- 398,402 ---- return rv ! def downloadPackageOnly(self, output=None): """Download a single package, if needed. *************** *** 423,427 **** return checksum == self._dict['MD5Sum'] ! def unpackSinglePackage(self, output=None): """Unpack a downloaded package archive.""" --- 439,443 ---- return checksum == self._dict['MD5Sum'] ! def unpackPackageOnly(self, output=None): """Unpack a downloaded package archive.""" *************** *** 434,443 **** basename = filename[:-len(ext)] cmd = cmd % self.archiveFilename - self._buildDirname = os.path.join(self._db.preferences.buildDir, basename) if self._cmd(output, self._db.preferences.buildDir, cmd): return "unpack command failed" ! setupname = os.path.join(self._buildDirname, "setup.py") ! if not os.path.exists(setupname) and not NO_EXECUTE: ! return "no setup.py found after unpack of archive" def installSinglePackage(self, output=None): --- 450,459 ---- basename = filename[:-len(ext)] cmd = cmd % self.archiveFilename if self._cmd(output, self._db.preferences.buildDir, cmd): return "unpack command failed" ! ! def installPackageOnly(self, output=None): ! """Default install method, to be overridden by subclasses""" ! return "Cannot automatically install package %s" % self.fullname() def installSinglePackage(self, output=None): *************** *** 449,485 **** if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) ! msg = self.downloadSinglePackage(output) if msg: return "download %s: %s" % (self.fullname(), msg) ! msg = self.unpackSinglePackage(output) if msg: return "unpack %s: %s" % (self.fullname(), msg) ! if self._dict.has_key('Pre-install-command'): ! if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): ! return "pre-install %s: running \"%s\" failed" % \ ! (self.fullname(), self._dict['Pre-install-command']) ! ! old_contents = os.listdir(self._db.preferences.installDir) ! installcmd = self._dict.get('Install-command') ! if not installcmd: ! installcmd = '"%s" setup.py install' % sys.executable ! if self._cmd(output, self._buildDirname, installcmd): ! return "install %s: running \"%s\" failed" % self.fullname() ! ! new_contents = os.listdir(self._db.preferences.installDir) ! self._interpretPthFiles(old_contents, new_contents) ! if self._dict.has_key('Post-install-command'): ! if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): ! return "post-install %s: running \"%s\" failed" % \ ! (self.fullname(), self._dict['Post-install-command']) ! return None ! def _interpretPthFiles(self, old_contents, new_contents): ! """Evaluate any new .pth files that have appeared after installing""" for fn in new_contents: ! if fn in old_contents: continue if fn[-4:] != '.pth': --- 465,489 ---- if not self._dict['Download-URL']: return "%s: This package needs to be installed manually" % _fmtpackagename(self) ! msg = self.downloadPackageOnly(output) if msg: return "download %s: %s" % (self.fullname(), msg) ! msg = self.unpackPackageOnly(output) if msg: return "unpack %s: %s" % (self.fullname(), msg) ! return self.installPackageOnly(output) ! def beforeInstall(self): ! """Bookkeeping before installation: remember what we have in site-packages""" ! self._old_contents = os.listdir(self._db.preferences.installDir) ! def afterInstall(self): ! """Bookkeeping after installation: interpret any new .pth files that have ! appeared""" ! ! new_contents = os.listdir(self._db.preferences.installDir) for fn in new_contents: ! if fn in self._old_contents: continue if fn[-4:] != '.pth': *************** *** 501,507 **** line = os.path.realpath(line) if not line in sys.path: ! sys.path.append(line) ! class PimpInstaller: """Installer engine: computes dependencies and installs --- 505,593 ---- line = os.path.realpath(line) if not line in sys.path: ! sys.path.append(line) + class PimpPackage_binary(PimpPackage): + + def unpackPackageOnly(self, output=None): + """We don't unpack binary packages until installing""" + pass + + def installPackageOnly(self, output=None): + """Install a single source package. + + If output is given it should be a file-like object and it + will receive a log of what happened.""" + + msgs = [] + if self._dict.has_key('Pre-install-command'): + msg.append("%s: Pre-install-command ignored" % self.fullname()) + if self._dict.has_key('Install-command'): + msgs.append("%s: Install-command ignored" % self.fullname()) + if self._dict.has_key('Post-install-command'): + msgs.append("%s: Post-install-command ignored" % self.fullname()) + + self.beforeInstall() + + # Install by unpacking + filename = os.path.split(self.archiveFilename)[1] + for ext, cmd in ARCHIVE_FORMATS: + if filename[-len(ext):] == ext: + break + else: + return "unknown extension for archive file: %s" % filename + + # Modify where the files are extracted + prefixmod = '-C /' + cmd = cmd % self.archiveFilename + if self._cmd(output, self._db.preferences.buildDir, cmd, prefixmod): + return "unpack command failed" + + self.afterInstall() + + if self._dict.has_key('Post-install-command'): + if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): + return "post-install %s: running \"%s\" failed" % \ + (self.fullname(), self._dict['Post-install-command']) + return None + + + class PimpPackage_source(PimpPackage): + + def unpackPackageOnly(self, output=None): + """Unpack a source package and check that setup.py exists""" + PimpPackage.unpackPackageOnly(self, output) + # Test that a setup script has been create + self._buildDirname = os.path.join(self._db.preferences.buildDir, basename) + setupname = os.path.join(self._buildDirname, "setup.py") + if not os.path.exists(setupname) and not NO_EXECUTE: + return "no setup.py found after unpack of archive" + + def installPackageOnly(self, output=None): + """Install a single source package. + + If output is given it should be a file-like object and it + will receive a log of what happened.""" + + if self._dict.has_key('Pre-install-command'): + if self._cmd(output, self._buildDirname, self._dict['Pre-install-command']): + return "pre-install %s: running \"%s\" failed" % \ + (self.fullname(), self._dict['Pre-install-command']) + + self.beforeInstall() + installcmd = self._dict.get('Install-command') + if not installcmd: + installcmd = '"%s" setup.py install' % sys.executable + if self._cmd(output, self._buildDirname, installcmd): + return "install %s: running \"%s\" failed" % self.fullname() + + self.afterInstall() + + if self._dict.has_key('Post-install-command'): + if self._cmd(output, self._buildDirname, self._dict['Post-install-command']): + return "post-install %s: running \"%s\" failed" % \ + (self.fullname(), self._dict['Post-install-command']) + return None + + class PimpInstaller: """Installer engine: computes dependencies and installs From jackjansen@users.sourceforge.net Fri Feb 14 14:13:27 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 06:13:27 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PackageManager.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv10098 Modified Files: PackageManager.py Log Message: Allow opening of alternate databases. Index: PackageManager.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PackageManager.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PackageManager.py 12 Feb 2003 15:39:56 -0000 1.2 --- PackageManager.py 14 Feb 2003 14:13:25 -0000 1.3 *************** *** 42,45 **** --- 42,46 ---- import string import os + import urllib import pimp *************** *** 79,90 **** def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") ! ## newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') ! ## openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') ! ## openbynameitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openbyname') FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') ## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') ## saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') ! FrameWork.Separator(m) m = Wapplication.Menu(self.menubar, "Edit") --- 80,91 ---- def makeusermenus(self): m = Wapplication.Menu(self.menubar, "File") ! newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') ! openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') ! openURLitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openURL') FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') ## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') ## saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') ! ## FrameWork.Separator(m) m = Wapplication.Menu(self.menubar, "Edit") *************** *** 138,142 **** def do_about(self, id, item, window, event): EasyDialogs.Message("Package Install Manager for Python") ! def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) --- 139,146 ---- def do_about(self, id, item, window, event): EasyDialogs.Message("Package Install Manager for Python") ! ! def domenu_openstandard(self, *args): ! self.opendoc(None) ! def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) *************** *** 144,147 **** --- 148,162 ---- filename = urllib.pathname2url(filename) self.opendoc(filename) + + def domenu_openURL(self, *args): + ok = EasyDialogs.AskYesNoCancel( + "Warning: by opening a non-standard database " + "you are trusting the maintainer of it " + "to run arbitrary code on your machine.", + yes="OK", no="") + if ok <= 0: return + url = EasyDialogs.AskString("URL of database to open:", ok="Open") + if url: + self.opendoc(url) def domenu_openbyname(self, *args): *************** *** 209,213 **** if not url: url = self.pimpprefs.pimpDatabase ! self.pimpdb.appendURL(url) def getbrowserdata(self): --- 224,239 ---- if not url: url = self.pimpprefs.pimpDatabase ! try: ! self.pimpdb.appendURL(url) ! except IOError, arg: ! return "Cannot open %s: %s" % (url, arg) ! return None ! ! def closepimp(self): ! self.pimpdb.close() ! self.pimpprefs = None ! self.pimpdb = None ! self.pimpinstaller = None ! self.packages = [] def getbrowserdata(self): *************** *** 237,243 **** def __init__(self, url = None): self.ic = None ! self.setuppimp(url) self.setupwidgets() self.updatestatus() def setupwidgets(self): --- 263,274 ---- def __init__(self, url = None): self.ic = None ! msg = self.setuppimp(url) ! if msg: ! EasyDialogs.Message(msg) self.setupwidgets() self.updatestatus() + + def close(self): + self.closepimp() def setupwidgets(self): From goodger@users.sourceforge.net Fri Feb 14 14:50:56 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Fri, 14 Feb 2003 06:50:56 -0800 Subject: [Python-checkins] python/nondist/peps pep-0242.txt,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28399 Modified Files: pep-0242.txt Log Message: rejected by the author Index: pep-0242.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0242.txt,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** pep-0242.txt 17 Apr 2001 22:12:46 -0000 1.3 --- pep-0242.txt 14 Feb 2003 14:50:54 -0000 1.4 *************** *** 2,7 **** Title: Numeric Kinds Version: $Revision$ Author: paul@pfdubois.com (Paul F. Dubois) ! Status: Draft Type: Standards Track Created: 17-Mar-2001 --- 2,8 ---- Title: Numeric Kinds Version: $Revision$ + Last-Modified: $Date$ Author: paul@pfdubois.com (Paul F. Dubois) ! Status: Rejected Type: Standards Track Created: 17-Mar-2001 *************** *** 208,211 **** --- 209,226 ---- No open issues have been raised at this time. + + + Rejection + + This PEP has been closed by the author. The kinds module will not + be added to the standard library. + + There was no opposition to the proposal but only mild interest in + using it, not enough to justify adding the module to the standard + library. Instead, it will be made available as a separate + distribution item at the Numerical Python site. At the next + release of Numerical Python, it will no longer be a part of the + Numeric distribution. + Copyright From goodger@users.sourceforge.net Fri Feb 14 14:51:29 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Fri, 14 Feb 2003 06:51:29 -0800 Subject: [Python-checkins] python/nondist/peps pep-0311.txt,1.1,1.2 pep-0312.txt,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28608 Modified Files: pep-0311.txt pep-0312.txt Log Message: editorial tweaks Index: pep-0311.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0311.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pep-0311.txt 14 Feb 2003 04:03:52 -0000 1.1 --- pep-0311.txt 14 Feb 2003 14:51:27 -0000 1.2 *************** *** 1,15 **** PEP: 311 ! Title: Simplified Global Interpreter Lock acquisition for extensions Version: $Revision$ Last-Modified: $Date$ Author: Mark Hammond Status: Draft ! Type: Content-Type: text/plain Created: 05-Feb-2003 Post-History: 05-Feb-2003 14-Feb-2003 Open Issues ! This is where I note comments from people that are yet to be resolved. - JustvR prefers a PyGIL prefix over PyAutoThreadState. - JackJ notes that the "Auto" prefix will look a little silly --- 1,19 ---- PEP: 311 ! Title: Simplified Global Interpreter Lock Acquisition for Extensions Version: $Revision$ Last-Modified: $Date$ Author: Mark Hammond Status: Draft ! Type: Standards Track Content-Type: text/plain Created: 05-Feb-2003 Post-History: 05-Feb-2003 14-Feb-2003 + Open Issues ! ! This is where I note comments from people that are yet to be ! resolved. ! - JustvR prefers a PyGIL prefix over PyAutoThreadState. - JackJ notes that the "Auto" prefix will look a little silly *************** *** 26,29 **** --- 30,34 ---- - Is my "Limitation" regarding PyEval_InitThreads() OK? + Abstract *************** *** 39,42 **** --- 44,48 ---- implementation. + Rationale *************** *** 97,100 **** --- 103,107 ---- advantage of Python's threading mechanisms. + Limitations and Exclusions *************** *** 109,121 **** This API will not perform automatic initialization of Python, or initialize Python for multi-threaded operation. Extension authors ! must continue to call Py_Initialize(), and for multi-threaded applications, PyEval_InitThreads(). The reason for this is that the first thread to call PyEval_InitThreads() is nominated as the "main thread" by Python, and so forcing the extension author to ! specifiy the main thread (by forcing her to make this first call) removes ambiguity. As Py_Initialize() must be called before ! PyEval_InitThreads(), and as both of these functions currently support ! being called multiple times, the burden this places on extension ! authors is considered reasonable. It is intended that this API be all that is necessary to acquire --- 116,128 ---- This API will not perform automatic initialization of Python, or initialize Python for multi-threaded operation. Extension authors ! must continue to call Py_Initialize(), and for multi-threaded applications, PyEval_InitThreads(). The reason for this is that the first thread to call PyEval_InitThreads() is nominated as the "main thread" by Python, and so forcing the extension author to ! specify the main thread (by forcing her to make this first call) removes ambiguity. As Py_Initialize() must be called before ! PyEval_InitThreads(), and as both of these functions currently ! support being called multiple times, the burden this places on ! extension authors is considered reasonable. It is intended that this API be all that is necessary to acquire *************** *** 126,129 **** --- 133,137 ---- are free to continue to use the existing thread state API. + Proposal *************** *** 170,174 **** state will be unknown to the caller, hence the use of the AutoThreadState API.) ! Every call to PyAutoThreadState_Ensure must be matched by a call to PyAutoThreadState_Release on the same thread. --- 178,182 ---- state will be unknown to the caller, hence the use of the AutoThreadState API.) ! Every call to PyAutoThreadState_Ensure must be matched by a call to PyAutoThreadState_Release on the same thread. *************** *** 188,204 **** } Design and Implementation The general operation of PyAutoThreadState_Ensure() will be: - assert Python is initialized. ! - Get a PyThreadState for the current thread, creating and saving if ! necessary. - remember the current state of the lock (owned/not owned) - If the current state does not own the GIL, acquire it. ! - Increment a counter for how many calls to PyAutoThreadState_Ensure ! have been made on the current thread. - return The general operation of PyAutoThreadState_Release() will be: - assert our thread currently holds the lock. - If old state indicates lock as previously unlocked, release GIL. --- 196,215 ---- } + Design and Implementation The general operation of PyAutoThreadState_Ensure() will be: + - assert Python is initialized. ! - Get a PyThreadState for the current thread, creating and saving ! if necessary. - remember the current state of the lock (owned/not owned) - If the current state does not own the GIL, acquire it. ! - Increment a counter for how many calls to ! PyAutoThreadState_Ensure have been made on the current thread. - return The general operation of PyAutoThreadState_Release() will be: + - assert our thread currently holds the lock. - If old state indicates lock as previously unlocked, release GIL. *************** *** 220,230 **** desired. Implementation ! An implementation of this proposal can be found at http://www.python.org/sf/684256 References [1] http://mail.python.org/pipermail/python-dev/2002-December/031424.html Copyright --- 231,245 ---- desired. + Implementation ! ! An implementation of this proposal can be found at http://www.python.org/sf/684256 + References [1] http://mail.python.org/pipermail/python-dev/2002-December/031424.html + Copyright Index: pep-0312.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0312.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pep-0312.txt 14 Feb 2003 05:49:58 -0000 1.1 --- pep-0312.txt 14 Feb 2003 14:51:27 -0000 1.2 *************** *** 11,14 **** --- 11,15 ---- Post-History: + Abstract *************** *** 16,27 **** some cases where it is not grammatically ambiguous. Motivation Lambdas are useful for defining anonymous functions, e.g. for use as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas ! are not used when they would be appropriate, just because the keyword ! "lambda" makes code look complex. Omitting lambda in some special ! cases is possible, with small and backwards compatible changes to ! the grammar, and provides a cheap cure against such "lambdaphobia". Rationale --- 17,31 ---- some cases where it is not grammatically ambiguous. + Motivation Lambdas are useful for defining anonymous functions, e.g. for use as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas ! are not used when they would be appropriate, just because the ! keyword "lambda" makes code look complex. Omitting lambda in some ! special cases is possible, with small and backwards compatible ! changes to the grammar, and provides a cheap cure against such ! "lambdaphobia". ! Rationale *************** *** 32,44 **** itself. Implementation can be done simply changing grammar so it lets the "lambda" keyword be implied in a few well-known cases. ! In particular, adding surrounding brackets lets you specify nullary ! lambda anywhere. Syntax ! An argumentless "lambda" keyword can be omitted in the following cases: ! * immediately after "=" in named parameter assignment or default value ! assignment; * immediately after "(" in any expression; --- 36,50 ---- itself. Implementation can be done simply changing grammar so it lets the "lambda" keyword be implied in a few well-known cases. ! In particular, adding surrounding brackets lets you specify ! nullary lambda anywhere. ! Syntax ! An argumentless "lambda" keyword can be omitted in the following ! cases: ! * immediately after "=" in named parameter assignment or default ! value assignment; * immediately after "(" in any expression; *************** *** 46,53 **** * immediately after a "," in a function argument list; ! * immediately after a ":" in a dictionary literal; (not implemented) * in an assignment statement; (not implemented) Examples of Use --- 52,61 ---- * immediately after a "," in a function argument list; ! * immediately after a ":" in a dictionary literal; (not ! implemented) * in an assignment statement; (not implemented) + Examples of Use *************** *** 80,90 **** with(mylock, :x(y(), 23, z(), 'foo')) Implementation Implementation requires some tweaking of the Grammar/Grammar file ! in the Python sources, and some adjustment of Modules/parsermodule.c ! to make syntactic and pragmatic changes. ! (Some grammar/parser guru is needed to make a full implementation.) Here are the changes needed to Grammar to allow implicit lambda: --- 88,100 ---- with(mylock, :x(y(), 23, z(), 'foo')) + Implementation Implementation requires some tweaking of the Grammar/Grammar file ! in the Python sources, and some adjustment of ! Modules/parsermodule.c to make syntactic and pragmatic changes. ! (Some grammar/parser guru is needed to make a full ! implementation.) Here are the changes needed to Grammar to allow implicit lambda: *************** *** 96,115 **** imptest: test | implambdef ! atom: '(' [imptestlist] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+ implambdef: ':' test ! imptestlist: imptest (',' imptest)* [','] argument: [test '='] imptest ! Three new non-terminals are needed: imptest for the place where implicit ! lambda may occur, implambdef for the implicit lambda definition itself, ! imptestlist for a place where imptest's may occur. - This implementation is not complete. First, because some files in Parser - module need to be updated. Second, some additional places aren't - implemented, see Syntax section above. Discussion --- 106,127 ---- imptest: test | implambdef ! atom: '(' [imptestlist] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+ implambdef: ':' test ! imptestlist: imptest (',' imptest)* [','] argument: [test '='] imptest ! Three new non-terminals are needed: imptest for the place where ! implicit lambda may occur, implambdef for the implicit lambda ! definition itself, imptestlist for a place where imptest's may ! occur. ! ! This implementation is not complete. First, because some files in ! Parser module need to be updated. Second, some additional places ! aren't implemented, see Syntax section above. Discussion *************** *** 140,143 **** --- 152,156 ---- do not justify the removal of the lambda keyword in such cases. + Credits *************** *** 146,153 **** --- 159,168 ---- thread "For review: PEP 308 - If-then-else expression". + Copyright This document has been placed in the public domain. + Local Variables: *************** *** 157,159 **** fill-column: 70 End: - --- 172,173 ---- From goodger@users.sourceforge.net Fri Feb 14 14:51:52 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Fri, 14 Feb 2003 06:51:52 -0800 Subject: [Python-checkins] python/nondist/peps pep-0000.txt,1.230,1.231 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv28745 Modified Files: pep-0000.txt Log Message: updated Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.230 retrieving revision 1.231 diff -C2 -d -r1.230 -r1.231 *** pep-0000.txt 11 Feb 2003 06:32:52 -0000 1.230 --- pep-0000.txt 14 Feb 2003 14:51:50 -0000 1.231 *************** *** 113,116 **** --- 113,118 ---- S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore + S 311 Simplified GIL Acquisition for Extensions Hammond + S 312 Simple Implicit Lambda Suzi, Martelli Finished PEPs (done, implemented in CVS) *************** *** 313,316 **** --- 315,320 ---- S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore + S 311 Simplified GIL Acquisition for Extensions Hammond + S 312 Simple Implicit Lambda Suzi, Martelli SR 666 Reject Foolish Indentation Creighton *************** *** 353,356 **** --- 357,361 ---- Goodger, David goodger@python.org Griffin, Grant g2@iowegian.com + Hammond, Mark mhammond@skippinet.com.au Harris, Peter scav@blueyonder.co.uk Heller, Thomas theller@python.net *************** *** 387,390 **** --- 392,396 ---- Schneider-Kamp, Peter nowonder@nowonder.de Stein, Greg gstein@lyra.org + Suzi, Roman rnd@onego.ru Tirosh, Oren oren at hishome.net Warsaw, Barry barry@zope.com From goodger@users.sourceforge.net Fri Feb 14 15:37:26 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Fri, 14 Feb 2003 07:37:26 -0800 Subject: [Python-checkins] python/nondist/peps pep-0000.txt,1.231,1.232 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv15604 Modified Files: pep-0000.txt Log Message: updated Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.231 retrieving revision 1.232 diff -C2 -d -r1.231 -r1.232 *** pep-0000.txt 14 Feb 2003 14:51:50 -0000 1.231 --- pep-0000.txt 14 Feb 2003 15:37:24 -0000 1.232 *************** *** 73,77 **** S 239 Adding a Rational Type to Python Craig, Zadka S 240 Adding a Rational Literal to Python Craig, Zadka - S 242 Numeric Kinds Dubois S 243 Module Repository Upload Mechanism Reifschneider S 245 Python Interface Syntax Pelletier --- 73,76 ---- *************** *** 171,174 **** --- 170,174 ---- SR 231 __findattr__() Warsaw SD 233 Python Online Help Prescod + SR 242 Numeric Kinds Dubois SR 244 The `directive' Statement von Loewis SR 259 Omit printing newline after newline GvR *************** *** 247,251 **** S 240 Adding a Rational Literal to Python Craig, Zadka SF 241 Metadata for Python Software Packages Kuchling ! S 242 Numeric Kinds Dubois S 243 Module Repository Upload Mechanism Reifschneider SR 244 The `directive' Statement von Loewis --- 247,251 ---- S 240 Adding a Rational Literal to Python Craig, Zadka SF 241 Metadata for Python Software Packages Kuchling ! SR 242 Numeric Kinds Dubois S 243 Module Repository Upload Mechanism Reifschneider SR 244 The `directive' Statement von Loewis From gvanrossum@users.sourceforge.net Fri Feb 14 19:29:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 14 Feb 2003 11:29:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_linuxaudiodev.py,1.8,1.9 test_ossaudiodev.py,1.3,1.4 regrtest.py,1.125,1.126 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv16303/Lib/test Modified Files: test_linuxaudiodev.py test_ossaudiodev.py regrtest.py Log Message: - The audio driver tests (test_ossaudiodev.py and test_linuxaudiodev.py) are no longer run by default. This is because they don't always work, depending on your hardware and software. To run these tests, you must use an invocation like ./python Lib/test/regrtest.py -u audio test_ossaudiodev Index: test_linuxaudiodev.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_linuxaudiodev.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** test_linuxaudiodev.py 23 Jul 2002 19:03:56 -0000 1.8 --- test_linuxaudiodev.py 14 Feb 2003 19:29:22 -0000 1.9 *************** *** 1,2 **** --- 1,5 ---- + from test import test_support + test_support.requires('audio') + from test.test_support import verbose, findfile, TestFailed, TestSkipped Index: test_ossaudiodev.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_ossaudiodev.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_ossaudiodev.py 8 Jan 2003 07:09:43 -0000 1.3 --- test_ossaudiodev.py 14 Feb 2003 19:29:22 -0000 1.4 *************** *** 1,2 **** --- 1,5 ---- + from test import test_support + test_support.requires('audio') + from test.test_support import verbose, findfile, TestFailed, TestSkipped Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.125 retrieving revision 1.126 diff -C2 -d -r1.125 -r1.126 *** regrtest.py 13 Feb 2003 16:12:21 -0000 1.125 --- regrtest.py 14 Feb 2003 19:29:22 -0000 1.126 *************** *** 592,597 **** --- 592,599 ---- test_imgfile test_largefile + test_linuxaudiodev test_nis test_ntpath + test_ossaudiodev test_socketserver test_sunaudiodev From gvanrossum@users.sourceforge.net Fri Feb 14 19:29:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 14 Feb 2003 11:29:24 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.659,1.660 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv16303/Misc Modified Files: NEWS Log Message: - The audio driver tests (test_ossaudiodev.py and test_linuxaudiodev.py) are no longer run by default. This is because they don't always work, depending on your hardware and software. To run these tests, you must use an invocation like ./python Lib/test/regrtest.py -u audio test_ossaudiodev Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.659 retrieving revision 1.660 diff -C2 -d -r1.659 -r1.660 *** NEWS 13 Feb 2003 22:19:20 -0000 1.659 --- NEWS 14 Feb 2003 19:29:21 -0000 1.660 *************** *** 285,288 **** --- 285,294 ---- ----- + - The audio driver tests (test_ossaudiodev.py and + test_linuxaudiodev.py) are no longer run by default. This is + because they don't always work, depending on your hardware and + software. To run these tests, you must use an invocation like + ./python Lib/test/regrtest.py -u audio test_ossaudiodev + - On systems which build using the configure script, compiler flags which used to be lumped together using the OPT flag have been split into two From montanaro@users.sourceforge.net Fri Feb 14 19:35:33 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 14 Feb 2003 11:35:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-riscos riscospath.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-riscos In directory sc8-pr-cvs1:/tmp/cvs-serv18517/Lib/plat-riscos Modified Files: riscospath.py Log Message: Migrate definitions of several platform-dependent path-related variables into the relevant path modules. See patch #686397. Index: riscospath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-riscos/riscospath.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** riscospath.py 15 Dec 2001 22:12:47 -0000 1.8 --- riscospath.py 14 Feb 2003 19:35:30 -0000 1.9 *************** *** 13,16 **** --- 13,24 ---- """ + # strings representing various path-related bits and pieces + curdir = '@' + pardir = '^' + extsep = '.' + sep = '.' + pathsep = ',' + defpath = '' + altsep = None # Imports - make an error-generating swi object if the swi module is not From montanaro@users.sourceforge.net Fri Feb 14 19:35:32 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 14 Feb 2003 11:35:32 -0800 Subject: [Python-checkins] python/dist/src/Lib os.py,1.66,1.67 os2emxpath.py,1.9,1.10 posixpath.py,1.57,1.58 macpath.py,1.45,1.46 ntpath.py,1.54,1.55 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv18517/Lib Modified Files: os.py os2emxpath.py posixpath.py macpath.py ntpath.py Log Message: Migrate definitions of several platform-dependent path-related variables into the relevant path modules. See patch #686397. Index: os.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/os.py,v retrieving revision 1.66 retrieving revision 1.67 diff -C2 -d -r1.66 -r1.67 *** os.py 29 Jan 2003 03:49:43 -0000 1.66 --- os.py 14 Feb 2003 19:35:29 -0000 1.67 *************** *** 27,34 **** _names = sys.builtin_module_names - altsep = None - __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", ! "defpath", "name"] def _get_exports_list(module): --- 27,32 ---- _names = sys.builtin_module_names __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", ! "defpath", "name", "path"] def _get_exports_list(module): *************** *** 41,46 **** name = 'posix' linesep = '\n' - curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':' - defpath = ':/bin:/usr/bin' from posix import * try: --- 39,42 ---- *************** *** 48,55 **** except ImportError: pass ! import posixpath ! path = posixpath ! del posixpath ! import posix __all__.extend(_get_exports_list(posix)) --- 44,49 ---- except ImportError: pass ! import posixpath as path ! import posix __all__.extend(_get_exports_list(posix)) *************** *** 59,64 **** name = 'nt' linesep = '\r\n' - curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';' - defpath = '.;C:\\bin' from nt import * try: --- 53,56 ---- *************** *** 66,73 **** except ImportError: pass ! import ntpath ! path = ntpath ! del ntpath ! import nt __all__.extend(_get_exports_list(nt)) --- 58,63 ---- except ImportError: pass ! import ntpath as path ! import nt __all__.extend(_get_exports_list(nt)) *************** *** 77,88 **** name = 'os2' linesep = '\r\n' - curdir = '.'; pardir = '..'; pathsep = ';' - if sys.version.find('EMX GCC') == -1: - # standard OS/2 compiler (VACPP or Watcom?) - sep = '\\'; altsep = '/' - else: - # EMX - sep = '/'; altsep = '\\' - defpath = '.;C:\\bin' from os2 import * try: --- 67,70 ---- *************** *** 91,102 **** pass if sys.version.find('EMX GCC') == -1: ! import ntpath ! path = ntpath ! del ntpath else: ! import os2emxpath ! path = os2emxpath ! del os2emxpath ! import os2 __all__.extend(_get_exports_list(os2)) --- 73,80 ---- pass if sys.version.find('EMX GCC') == -1: ! import ntpath as path else: ! import os2emxpath as path ! import os2 __all__.extend(_get_exports_list(os2)) *************** *** 106,111 **** name = 'mac' linesep = '\r' - curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n' - defpath = ':' from mac import * try: --- 84,87 ---- *************** *** 113,120 **** except ImportError: pass ! import macpath ! path = macpath ! del macpath ! import mac __all__.extend(_get_exports_list(mac)) --- 89,94 ---- except ImportError: pass ! import macpath as path ! import mac __all__.extend(_get_exports_list(mac)) *************** *** 124,129 **** name = 'ce' linesep = '\r\n' - curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';' - defpath = '\\Windows' from ce import * try: --- 98,101 ---- *************** *** 132,139 **** pass # We can use the standard Windows path. ! import ntpath ! path = ntpath ! del ntpath ! import ce __all__.extend(_get_exports_list(ce)) --- 104,109 ---- pass # We can use the standard Windows path. ! import ntpath as path ! import ce __all__.extend(_get_exports_list(ce)) *************** *** 143,148 **** name = 'riscos' linesep = '\n' - curdir = '@'; pardir = '^'; sep = '.'; pathsep = ',' - defpath = '' from riscos import * try: --- 113,116 ---- *************** *** 150,157 **** except ImportError: pass ! import riscospath ! path = riscospath ! del riscospath ! import riscos __all__.extend(_get_exports_list(riscos)) --- 118,123 ---- except ImportError: pass ! import riscospath as path ! import riscos __all__.extend(_get_exports_list(riscos)) *************** *** 161,175 **** raise ImportError, 'no os specific module found' ! ! if sep=='.': ! extsep = '/' ! else: ! extsep = '.' ! ! __all__.append("path") del _names - - sys.modules['os.path'] = path #' --- 127,134 ---- raise ImportError, 'no os specific module found' ! sys.modules['os.path'] = path ! from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep del _names #' Index: os2emxpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/os2emxpath.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** os2emxpath.py 3 Jan 2003 18:01:57 -0000 1.9 --- os2emxpath.py 14 Feb 2003 19:35:30 -0000 1.10 *************** *** 13,17 **** --- 13,27 ---- "getatime","getctime", "islink","exists","isdir","isfile","ismount", "walk","expanduser","expandvars","normpath","abspath","splitunc", + "curdir","pardir","sep","pathsep","defpath","altsep","extsep", "realpath","supports_unicode_filenames"] + + # strings representing various path-related bits and pieces + curdir = '.' + pardir = '..' + extsep = '.' + sep = '/' + altsep = '\\' + pathsep = ';' + defpath = '.;C:\\bin' # Normalize the case of a pathname and map slashes to backslashes. Index: posixpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/posixpath.py,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** posixpath.py 3 Jan 2003 18:01:57 -0000 1.57 --- posixpath.py 14 Feb 2003 19:35:30 -0000 1.58 *************** *** 19,23 **** --- 19,33 ---- "walk","expanduser","expandvars","normpath","abspath", "samefile","sameopenfile","samestat", + "curdir","pardir","sep","pathsep","defpath","altsep","extsep", "realpath","supports_unicode_filenames"] + + # strings representing various path-related bits and pieces + curdir = '.' + pardir = '..' + extsep = '.' + sep = '/' + pathsep = ':' + defpath = ':/bin:/usr/bin' + altsep = None # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac. Index: macpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/macpath.py,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** macpath.py 29 Jan 2003 03:49:43 -0000 1.45 --- macpath.py 14 Feb 2003 19:35:30 -0000 1.46 *************** *** 8,12 **** --- 8,22 ---- "getatime","getctime", "islink","exists","isdir","isfile", "walk","expanduser","expandvars","normpath","abspath", + "curdir","pardir","sep","pathsep","defpath","altsep","extsep", "realpath","supports_unicode_filenames"] + + # strings representing various path-related bits and pieces + curdir = ':' + pardir = '::' + extsep = '.' + sep = ':' + pathsep = '\n' + defpath = ':' + altsep = None # Normalize the case of a pathname. Dummy in Posix, but .lower() here. Index: ntpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/ntpath.py,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** ntpath.py 3 Jan 2003 18:01:56 -0000 1.54 --- ntpath.py 14 Feb 2003 19:35:30 -0000 1.55 *************** *** 14,18 **** --- 14,34 ---- "getatime","getctime", "islink","exists","isdir","isfile","ismount", "walk","expanduser","expandvars","normpath","abspath","splitunc", + "curdir","pardir","sep","pathsep","defpath","altsep","extsep", "realpath","supports_unicode_filenames"] + + # strings representing various path-related bits and pieces + curdir = '.' + pardir = '..' + extsep = '.' + sep = '\\' + pathsep = ';' + altsep = None + if 'ce' in sys.builtin_module_names: + defpath = '\\Windows' + elif 'os2' in sys.builtin_module_names: + # OS/2 w/ EMX + altsep = '/' + else: + defpath = '.;C:\\bin' # Normalize the case of a pathname and map slashes to backslashes. From montanaro@users.sourceforge.net Fri Feb 14 19:35:34 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 14 Feb 2003 11:35:34 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.113,1.114 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv18517/Doc/lib Modified Files: libos.tex Log Message: Migrate definitions of several platform-dependent path-related variables into the relevant path modules. See patch #686397. Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.113 retrieving revision 1.114 diff -C2 -d -r1.113 -r1.114 *** libos.tex 14 Feb 2003 06:39:37 -0000 1.113 --- libos.tex 14 Feb 2003 19:35:31 -0000 1.114 *************** *** 1621,1624 **** --- 1621,1625 ---- directory. For example: \code{'.'} for \POSIX{} or \code{':'} for the Macintosh. + Also available via \module{os.path}. \end{datadesc} *************** *** 1627,1630 **** --- 1628,1632 ---- directory. For example: \code{'..'} for \POSIX{} or \code{'::'} for the Macintosh. + Also available via \module{os.path}. \end{datadesc} *************** *** 1635,1638 **** --- 1637,1641 ---- parse or concatenate pathnames --- use \function{os.path.split()} and \function{os.path.join()} --- but it is occasionally useful. + Also available via \module{os.path}. \end{datadesc} *************** *** 1642,1645 **** --- 1645,1649 ---- set to \character{/} on Windows systems where \code{sep} is a backslash. + Also available via \module{os.path}. \end{datadesc} *************** *** 1647,1650 **** --- 1651,1655 ---- The character which separates the base filename from the extension; for example, the \character{.} in \file{os.py}. + Also available via \module{os.path}. \versionadded{2.2} \end{datadesc} *************** *** 1654,1657 **** --- 1659,1663 ---- search patch components (as in \envvar{PATH}), such as \character{:} for \POSIX{} or \character{;} for Windows. + Also available via \module{os.path}. \end{datadesc} *************** *** 1660,1663 **** --- 1666,1670 ---- \function{spawn*p*()} if the environment doesn't have a \code{'PATH'} key. + Also available via \module{os.path}. \end{datadesc} From lemburg@users.sourceforge.net Fri Feb 14 20:25:59 2003 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Fri, 14 Feb 2003 12:25:59 -0800 Subject: [Python-checkins] python/dist/src/Python codecs.c,2.19,2.20 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv7431/Python Modified Files: codecs.c Log Message: Patch for bug reported in patch #686627: import race condition in codecs registry startup. Index: codecs.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/codecs.c,v retrieving revision 2.19 retrieving revision 2.20 diff -C2 -d -r2.19 -r2.20 *** codecs.c 21 Nov 2002 23:53:25 -0000 2.19 --- codecs.c 14 Feb 2003 20:25:56 -0000 2.20 *************** *** 39,43 **** import_encodings_called = 1; ! mod = PyImport_ImportModule("encodings"); if (mod == NULL) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { --- 39,43 ---- import_encodings_called = 1; ! mod = PyImport_ImportModuleEx("encodings", NULL, NULL, NULL); if (mod == NULL) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { From tim_one@users.sourceforge.net Fri Feb 14 23:05:30 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 15:05:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.50,1.51 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23870/Lib/test Modified Files: pickletester.py Log Message: cPickle produces NEWOBJ appropriately now. It still doesn't know how to unpickle the new slot-full state tuples. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.50 retrieving revision 1.51 diff -C2 -d -r1.50 -r1.51 *** pickletester.py 13 Feb 2003 19:30:57 -0000 1.50 --- pickletester.py 14 Feb 2003 23:05:26 -0000 1.51 *************** *** 719,728 **** self.failUnless(num_setitems >= 2) - # XXX Temporary hack, so long as the C implementation of pickle protocol - # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests - # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests - # XXX along with the references to it in test_pickle.py. - class TempAbstractPickleTests(unittest.TestCase): - def test_simple_newobj(self): x = object.__new__(SimpleNewObj) # avoid __init__ --- 719,722 ---- *************** *** 734,737 **** --- 728,737 ---- self.assertEqual(y.abc, 666) self.assertEqual(x.__dict__, y.__dict__) + + # XXX Temporary hack, so long as the C implementation of pickle protocol + # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests + # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests + # XXX along with the references to it in test_pickle.py. + class TempAbstractPickleTests(unittest.TestCase): def test_newobj_list_slots(self): From tim_one@users.sourceforge.net Fri Feb 14 23:05:30 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 15:05:30 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.135,2.136 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv23870/Modules Modified Files: cPickle.c Log Message: cPickle produces NEWOBJ appropriately now. It still doesn't know how to unpickle the new slot-full state tuples. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.135 retrieving revision 2.136 diff -C2 -d -r2.135 -r2.136 *** cPickle.c 13 Feb 2003 23:00:26 -0000 2.135 --- cPickle.c 14 Feb 2003 23:05:28 -0000 2.136 *************** *** 120,123 **** --- 120,129 ---- static PyObject *two_tuple; + /* object.__reduce__, the default reduce callable. */ + PyObject *object_reduce; + + /* copy_reg._better_reduce, the protocol 2 reduction function. */ + PyObject *better_reduce; + static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, *************** *** 2182,2201 **** } ! static int ! save_reduce(Picklerobject *self, PyObject *callable, ! PyObject *tup, PyObject *state, PyObject *ob) { ! static char reduce = REDUCE, build = BUILD; ! if (save(self, callable, 0) < 0) ! return -1; ! if (save(self, tup, 0) < 0) ! return -1; ! if (self->write_func(self, &reduce, 1) < 0) return -1; if (ob != NULL) { if (state && !PyDict_Check(state)) { --- 2188,2308 ---- } ! /* We're saving ob, and args is the 2-thru-5 tuple returned by the ! * appropriate __reduce__ method for ob. ! */ static int ! save_reduce(Picklerobject *self, PyObject *args, PyObject *ob) { ! PyObject *callable; ! PyObject *argtup; ! PyObject *state = NULL; ! PyObject *listitems = NULL; ! PyObject *dictitems = NULL; ! int use_newobj = self->proto >= 2; ! static char reduce = REDUCE; ! static char build = BUILD; ! static char newobj = NEWOBJ; ! if (! PyArg_UnpackTuple(args, "save_reduce", 2, 5, ! &callable, ! &argtup, ! &state, ! &listitems, ! &dictitems)) return -1; + if (state == Py_None) + state = NULL; + if (listitems == Py_None) + listitems = NULL; + if (dictitems == Py_None) + dictitems = NULL; + + /* Protocol 2 special case: if callable's name is __newobj__, use + * NEWOBJ. This consumes a lot of code. + */ + if (use_newobj) { + PyObject *temp = PyObject_GetAttr(callable, __name___str); + + if (temp == NULL) { + PyErr_Clear(); + use_newobj = 0; + } + else { + use_newobj = PyString_Check(temp) && + strcmp(PyString_AS_STRING(temp), + "__newobj__") == 0; + Py_DECREF(temp); + } + } + if (use_newobj) { + PyObject *cls; + PyObject *newargtup; + int n, i; + + /* Sanity checks. */ + n = PyTuple_Size(argtup); + if (n < 1) { + PyErr_SetString(PicklingError, "__newobj__ arglist " + "is empty"); + return -1; + } + + cls = PyTuple_GET_ITEM(argtup, 0); + if (! PyObject_HasAttrString(cls, "__new__")) { + PyErr_SetString(PicklingError, "args[0] from " + "__newobj__ args has no __new__"); + return -1; + } + + /* XXX How could ob be NULL? */ + if (ob != NULL) { + PyObject *ob_dot_class; + + ob_dot_class = PyObject_GetAttr(ob, __class___str); + if (ob_dot_class == NULL) + PyErr_Clear(); + i = ob_dot_class != cls; /* true iff a problem */ + Py_XDECREF(ob_dot_class); + if (i) { + PyErr_SetString(PicklingError, "args[0] from " + "__newobj__ args has the wrong class"); + return -1; + } + } + + /* Save the class and its __new__ arguments. */ + if (save(self, cls, 0) < 0) + return -1; + + newargtup = PyTuple_New(n-1); /* argtup[1:] */ + if (newargtup == NULL) + return -1; + for (i = 1; i < n; ++i) { + PyObject *temp = PyTuple_GET_ITEM(argtup, i); + Py_INCREF(temp); + PyTuple_SET_ITEM(newargtup, i-1, temp); + } + i = save(self, newargtup, 0) < 0; + Py_DECREF(newargtup); + if (i < 0) + return -1; + + /* Add NEWOBJ opcode. */ + if (self->write_func(self, &newobj, 1) < 0) + return -1; + } + else { + /* Not using NEWOBJ. */ + if (save(self, callable, 0) < 0 || + save(self, argtup, 0) < 0 || + self->write_func(self, &reduce, 1) < 0) + return -1; + } + + /* Memoize. */ + /* XXX How can ob be NULL? */ if (ob != NULL) { if (state && !PyDict_Check(state)) { *************** *** 2203,2217 **** return -1; } ! else { ! if (put(self, ob) < 0) return -1; - } } - if (state) { - if (save(self, state, 0) < 0) - return -1; ! if (self->write_func(self, &build, 1) < 0) return -1; } --- 2310,2327 ---- return -1; } ! else if (put(self, ob) < 0) return -1; } ! if (listitems && batch_list(self, listitems) < 0) ! return -1; ! ! if (dictitems && batch_dict(self, dictitems) < 0) ! return -1; ! ! if (state) { ! if (save(self, state, 0) < 0 || ! self->write_func(self, &build, 1) < 0) return -1; } *************** *** 2224,2230 **** { PyTypeObject *type; ! PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0, *arg_tup = 0, ! *callable = 0, *state = 0; ! int res = -1, tmp, size; if (self->nesting++ > Py_GetRecursionLimit()){ --- 2334,2341 ---- { PyTypeObject *type; ! PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0; ! PyObject *arg_tup; ! int res = -1; ! int tmp, size; if (self->nesting++ > Py_GetRecursionLimit()){ *************** *** 2393,2462 **** } ! assert(t == NULL); /* just a reminder */ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type); if (__reduce__ != NULL) { Py_INCREF(__reduce__); - Py_INCREF(args); - ARG_TUP(self, args); - if (self->arg) { - t = PyObject_Call(__reduce__, self->arg, NULL); - FREE_ARG_TUP(self); - } - if (! t) goto finally; } else { ! __reduce__ = PyObject_GetAttr(args, __reduce___str); ! if (__reduce__ == NULL) PyErr_Clear(); ! else { ! t = PyObject_Call(__reduce__, empty_tuple, NULL); ! if (!t) ! goto finally; ! } ! } ! ! if (t) { ! if (PyString_Check(t)) { ! res = save_global(self, args, t); ! goto finally; ! } ! ! if (!PyTuple_Check(t)) { ! cPickle_ErrFormat(PicklingError, "Value returned by " ! "%s must be a tuple", ! "O", __reduce__); goto finally; } ! size = PyTuple_Size(t); ! ! if (size != 3 && size != 2) { ! cPickle_ErrFormat(PicklingError, "tuple returned by " ! "%s must contain only two or three elements", ! "O", __reduce__); ! goto finally; } ! callable = PyTuple_GET_ITEM(t, 0); ! arg_tup = PyTuple_GET_ITEM(t, 1); ! if (size > 2) { ! state = PyTuple_GET_ITEM(t, 2); ! if (state == Py_None) ! state = NULL; ! } ! if (!( PyTuple_Check(arg_tup) || arg_tup==Py_None )) { ! cPickle_ErrFormat(PicklingError, "Second element of " ! "tuple returned by %s must be a tuple", "O", __reduce__); ! goto finally; ! } ! res = save_reduce(self, callable, arg_tup, state, args); goto finally; } ! PyErr_SetObject(UnpickleableError, args); finally: --- 2504,2581 ---- } ! /* Get a reduction callable. This may come from ! * copy_reg.dispatch_table, the object's __reduce__ method, ! * the default object.__reduce__, or copy_reg._better_reduce. ! */ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type); if (__reduce__ != NULL) { Py_INCREF(__reduce__); } else { ! /* Check for a __reduce__ method. ! * Subtle: get the unbound method from the class, so that ! * protocol 2 can override the default __reduce__ that all ! * classes inherit from object. ! * XXX object.__reduce__ should really be rewritten so that ! * XXX we don't need to call back into Python code here ! * XXX (better_reduce), but no time to do that. ! */ ! __reduce__ = PyObject_GetAttr((PyObject *)type, ! __reduce___str); ! if (__reduce__ == NULL) { PyErr_Clear(); ! PyErr_SetObject(UnpickleableError, args); goto finally; } ! if (self->proto >= 2 && __reduce__ == object_reduce) { ! /* Proto 2 can do better than the default. */ ! Py_DECREF(__reduce__); ! Py_INCREF(better_reduce); ! __reduce__ = better_reduce; } + } ! /* Call the reduction callable, setting t to the result. */ ! assert(__reduce__ != NULL); ! assert(t == NULL); ! Py_INCREF(args); ! ARG_TUP(self, args); ! if (self->arg) { ! t = PyObject_Call(__reduce__, self->arg, NULL); ! FREE_ARG_TUP(self); ! } ! if (t == NULL) ! goto finally; ! if (PyString_Check(t)) { ! res = save_global(self, args, t); ! goto finally; ! } ! if (! PyTuple_Check(t)) { ! cPickle_ErrFormat(PicklingError, "Value returned by " ! "%s must be string or tuple", "O", __reduce__); ! goto finally; ! } ! size = PyTuple_Size(t); ! if (size < 2 || size > 5) { ! cPickle_ErrFormat(PicklingError, "tuple returned by " ! "%s must contain 2 through 5 elements", ! "O", __reduce__); goto finally; } ! arg_tup = PyTuple_GET_ITEM(t, 1); ! if (!(PyTuple_Check(arg_tup) || arg_tup == Py_None)) { ! cPickle_ErrFormat(PicklingError, "Second element of " ! "tuple returned by %s must be a tuple", ! "O", __reduce__); ! goto finally; ! } ! ! res = save_reduce(self, t, args); finally: *************** *** 5448,5452 **** --- 5567,5578 ---- if (!extension_cache) return -1; + better_reduce = PyObject_GetAttrString(copy_reg, "_better_reduce"); + if (!better_reduce) return -1; + Py_DECREF(copy_reg); + + object_reduce = PyObject_GetAttrString((PyObject *)&PyBaseObject_Type, + "__reduce__"); + if (object_reduce == NULL) return -1; if (!(empty_tuple = PyTuple_New(0))) From jackjansen@users.sourceforge.net Fri Feb 14 23:45:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 15:45:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/Doc - New directory Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv6965/Doc Log Message: Directory /cvsroot/python/python/dist/src/Mac/OSX/Doc added to the repository From jackjansen@users.sourceforge.net Fri Feb 14 23:46:24 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 15:46:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/Doc setup.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv7170/Doc Added Files: setup.py Log Message: Moved setupDocs.py to Doc/setup.py and did some cleanup. It now at least allows bdist, but it's still one big hack:-( --- NEW FILE: setup.py --- # Build and install an Apple Help Viewer compatible version of the Python # documentation into the framework. # Code by Bill Fancher, with some modifications by Jack Jansen. # # You must run this as a two-step process # 1. python setupDocs.py build # 2. Wait for Apple Help Indexing Tool to finish # 3. python setupDocs.py install # # To do: # - test whether the docs are available locally before downloading # - fix buildDocsFromSource # - Get documentation version from sys.version, fallback to 2.2.1 # - See if we can somehow detect that Apple Help Indexing Tool is finished # - data_files to setup() doesn't seem the right way to pass the arguments # import sys, os, re from distutils.cmd import Command from distutils.command.build import build from distutils.core import setup from distutils.file_util import copy_file from distutils.dir_util import copy_tree from distutils.log import log from distutils.spawn import spawn from distutils import sysconfig, dep_util from distutils.util import change_root class DocBuild(build): def initialize_options(self): build.initialize_options(self) self.build_html = None self.build_dest = None self.download = 1 self.doc_version = '2.2.1' def finalize_options(self): build.finalize_options(self) if self.build_html is None: self.build_html = os.path.join(self.build_base, 'html') if self.build_dest is None: self.build_dest = os.path.join(self.build_base, 'processed-html') def spawn(self, *args): spawn(args, 1, self.verbose, self.dry_run) def downloadDocs(self): workdir = os.getcwd() self.mkpath(self.build_html) os.chdir(self.build_base) self.spawn('curl','-O', 'http://www.python.org/ftp/python/doc/%s/html-%s.tgz' % (self.doc_version,self.doc_version)) os.chdir(workdir) os.chdir(self.build_html) self.spawn('tar', '-xzf', '../html-%s.tgz' % self.doc_version) os.chdir(workdir) def buildDocsFromSource(self): srcdir = '../../..' docdir = os.path.join(srcdir, 'Doc') htmldir = os.path.join(docdir, 'html') spawn(('make','--directory', docdir, 'html'), 1, self.verbose, self.dry_run) self.mkpath(self.build_html) copy_tree(htmldir, self.build_html) def ensureHtml(self): if not os.path.exists(self.build_html): if self.download: self.downloadDocs() else: self.buildDocsFromSource() def hackIndex(self): ind_html = 'index.html' #print 'self.build_dest =', self.build_dest hackedIndex = file(os.path.join(self.build_dest, ind_html),'w') origIndex = file(os.path.join(self.build_html,ind_html)) r = re.compile('', re.DOTALL) hackedIndex.write(r.sub('',origIndex.read())) def hackFile(self,d,f): origPath = os.path.join(d,f) assert(origPath[:len(self.build_html)] == self.build_html) outPath = os.path.join(self.build_dest, d[len(self.build_html)+1:], f) (name, ext) = os.path.splitext(f) if os.path.isdir(origPath): self.mkpath(outPath) elif ext == '.html': if self.verbose: print 'hacking %s to %s' % (origPath,outPath) hackedFile = file(outPath, 'w') origFile = file(origPath,'r') hackedFile.write(self.r.sub('
', origFile.read())) else: copy_file(origPath, outPath) def hackHtml(self): self.r = re.compile('
') os.path.walk(self.build_html, self.visit, None) def visit(self, dummy, dirname, filenames): for f in filenames: self.hackFile(dirname, f) def makeHelpIndex(self): app = '/Developer/Applications/Apple Help Indexing Tool.app' self.spawn('open', '-a', app , self.build_dest) print "Please wait until Apple Help Indexing Tool finishes before installing" def run(self): self.ensure_finalized() self.ensureHtml() if not os.path.isdir(self.build_html): raise RuntimeError, \ "Can't find source folder for documentation." self.mkpath(self.build_dest) if dep_util.newer(os.path.join(self.build_html,'index.html'), os.path.join(self.build_dest,'index.html')): self.mkpath(self.build_dest) self.hackHtml() self.hackIndex() self.makeHelpIndex() class AHVDocInstall(Command): description = "install Apple Help Viewer html files" user_options = [('install-doc=', 'd', 'directory to install HTML tree'), ('root=', None, "install everything relative to this alternate root directory"), ] def initialize_options(self): self.build_dest = None self.install_doc = None self.prefix = None self.root = None def finalize_options(self): self.set_undefined_options('install', ('prefix', 'prefix'), ('root', 'root')) # import pdb ; pdb.set_trace() build_cmd = self.get_finalized_command('build') if self.build_dest == None: build_cmd = self.get_finalized_command('build') self.build_dest = build_cmd.build_dest if self.install_doc == None: self.install_doc = os.path.join(self.prefix, 'Resources/English.lproj/Documentation') print 'INSTALL', self.build_dest, '->', self.install_doc def run(self): self.finalize_options() self.ensure_finalized() print "Running Installer" instloc = self.install_doc if self.root: instloc = change_root(self.root, instloc) self.mkpath(instloc) copy_tree(self.build_dest, instloc) print "Installation complete" def mungeVersion(infile, outfile): i = file(infile,'r') o = file(outfile,'w') o.write(re.sub('\$\(VERSION\)',sysconfig.get_config_var('VERSION'),i.read())) i.close() o.close() def main(): # turn off warnings when deprecated modules are imported ## import warnings ## warnings.filterwarnings("ignore",category=DeprecationWarning) setup(name = 'Documentation', version = '%d.%d' % sys.version_info[:2], cmdclass = {'install_data':AHVDocInstall, 'build':DocBuild}, data_files = ['dummy'], ) if __name__ == '__main__': main() From jackjansen@users.sourceforge.net Fri Feb 14 23:46:24 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 14 Feb 2003 15:46:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX setupDocs.py,1.2,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv7170 Removed Files: setupDocs.py Log Message: Moved setupDocs.py to Doc/setup.py and did some cleanup. It now at least allows bdist, but it's still one big hack:-( --- setupDocs.py DELETED --- From montanaro@users.sourceforge.net Sat Feb 15 00:52:13 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 14 Feb 2003 16:52:13 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv30473 Modified Files: test_csv.py Log Message: test for strings w/ NUL bytes Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** test_csv.py 13 Feb 2003 17:21:15 -0000 1.33 --- test_csv.py 15 Feb 2003 00:52:11 -0000 1.34 *************** *** 129,132 **** --- 129,135 ---- self.assertRaises(csv.Error, self._read_test, ['"ab"c'], None, strict = 1) + # cannot handle null bytes for the moment + self.assertRaises(csv.Error, self._read_test, + ['ab\0c'], None, strict = 1) self._read_test(['"ab"c'], [['abc']], doublequote = 0) From montanaro@users.sourceforge.net Sat Feb 15 00:53:02 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Fri, 14 Feb 2003 16:53:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv30739 Modified Files: _csv.c Log Message: test for NUL bytes in strings Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** _csv.c 14 Feb 2003 06:32:40 -0000 1.31 --- _csv.c 15 Feb 2003 00:52:59 -0000 1.32 *************** *** 643,650 **** --- 643,657 ---- } line = PyString_AsString(lineobj); + if (line == NULL) { Py_DECREF(lineobj); return NULL; } + if (strlen(line) < PyString_GET_SIZE(lineobj)) { + self->had_parse_error = 1; + Py_DECREF(lineobj); + return PyErr_Format(error_obj, + "string with NUL bytes"); + } /* Process line of text - send '\0' to processing code to From tim_one@users.sourceforge.net Sat Feb 15 03:01:13 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 19:01:13 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.136,2.137 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv13821/python/Modules Modified Files: cPickle.c Log Message: cPickle.c, load_build(): Taught cPickle how to pick apart the optional proto 2 slot state. pickle.py, load_build(): CAUTION: Noted that cPickle's load_build and pickle's load_build really don't do the same things with the state, and didn't before this patch either. cPickle never tries to do .update(), and has no backoff if instance.__dict__ can't be retrieved. There are no tests that can tell the difference, and part of what cPickle's load_build() did looked accidental to me, so I don't know what the true intent is here. pickletester.py, test_pickle.py: Got rid of the hack for exempting cPickle from running some of the proto 2 tests. dictobject.c, PyDict_Next(): documented intended use. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.136 retrieving revision 2.137 diff -C2 -d -r2.136 -r2.137 *** cPickle.c 14 Feb 2003 23:05:28 -0000 2.136 --- cPickle.c 15 Feb 2003 03:01:10 -0000 2.137 *************** *** 4310,4324 **** load_build(Unpicklerobject *self) { ! PyObject *value = 0, *inst = 0, *instdict = 0, *d_key = 0, *d_value = 0, ! *junk = 0, *__setstate__ = 0; ! int i, r = 0; ! if (self->stack->length < 2) return stackUnderflow(); ! PDATA_POP(self->stack, value); ! if (! value) return -1; ! inst=self->stack->data[self->stack->length-1]; ! if ((__setstate__ = PyObject_GetAttr(inst, __setstate___str))) { ! ARG_TUP(self, value); if (self->arg) { junk = PyObject_Call(__setstate__, self->arg, NULL); --- 4310,4335 ---- load_build(Unpicklerobject *self) { ! PyObject *state, *inst, *slotstate; ! PyObject *__setstate__; ! PyObject *d_key, *d_value; ! int i; ! int res = -1; ! /* Stack is ... instance, state. We want to leave instance at ! * the stack top, possibly mutated via instance.__setstate__(state). ! */ ! if (self->stack->length < 2) ! return stackUnderflow(); ! PDATA_POP(self->stack, state); ! if (state == NULL) ! return -1; ! inst = self->stack->data[self->stack->length - 1]; ! __setstate__ = PyObject_GetAttr(inst, __setstate___str); ! if (__setstate__ != NULL) { ! PyObject *junk = NULL; ! ! /* The explicit __setstate__ is responsible for everything. */ ! ARG_TUP(self, state); if (self->arg) { junk = PyObject_Call(__setstate__, self->arg, NULL); *************** *** 4326,4350 **** } Py_DECREF(__setstate__); ! if (! junk) return -1; Py_DECREF(junk); return 0; } - PyErr_Clear(); ! if ((instdict = PyObject_GetAttr(inst, __dict___str))) { i = 0; ! while (PyDict_Next(value, &i, &d_key, &d_value)) { ! if (PyObject_SetItem(instdict, d_key, d_value) < 0) { ! r=-1; ! break; ! } } ! Py_DECREF(instdict); } - else r=-1; ! Py_XDECREF(value); ! return r; } --- 4337,4400 ---- } Py_DECREF(__setstate__); ! if (junk == NULL) ! return -1; Py_DECREF(junk); return 0; } PyErr_Clear(); ! ! /* A default __setstate__. First see whether state embeds a ! * slot state dict too (a proto 2 addition). ! */ ! if (PyTuple_Check(state) && PyTuple_Size(state) == 2) { ! PyObject *temp = state; ! state = PyTuple_GET_ITEM(temp, 0); ! slotstate = PyTuple_GET_ITEM(temp, 1); ! Py_INCREF(state); ! Py_INCREF(slotstate); ! Py_DECREF(temp); ! } ! else ! slotstate = NULL; ! ! /* Set inst.__dict__ from the state dict (if any). */ ! if (state != Py_None) { ! PyObject *dict; ! if (! PyDict_Check(state)) { ! PyErr_SetString(UnpicklingError, "state is not a " ! "dictionary"); ! goto finally; ! } ! dict = PyObject_GetAttr(inst, __dict___str); ! if (dict == NULL) ! goto finally; ! i = 0; ! while (PyDict_Next(state, &i, &d_key, &d_value)) { ! if (PyObject_SetItem(dict, d_key, d_value) < 0) ! goto finally; } ! Py_DECREF(dict); } ! /* Also set instance attributes from the slotstate dict (if any). */ ! if (slotstate != NULL) { ! if (! PyDict_Check(slotstate)) { ! PyErr_SetString(UnpicklingError, "slot state is not " ! "a dictionary"); ! goto finally; ! } ! i = 0; ! while (PyDict_Next(slotstate, &i, &d_key, &d_value)) { ! if (PyObject_SetAttr(inst, d_key, d_value) < 0) ! goto finally; ! } ! } ! res = 0; ! finally: ! Py_DECREF(state); ! Py_XDECREF(slotstate); ! return res; } From tim_one@users.sourceforge.net Sat Feb 15 03:01:15 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 19:01:15 -0800 Subject: [Python-checkins] python/dist/src/Objects dictobject.c,2.138,2.139 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv13821/python/Objects Modified Files: dictobject.c Log Message: cPickle.c, load_build(): Taught cPickle how to pick apart the optional proto 2 slot state. pickle.py, load_build(): CAUTION: Noted that cPickle's load_build and pickle's load_build really don't do the same things with the state, and didn't before this patch either. cPickle never tries to do .update(), and has no backoff if instance.__dict__ can't be retrieved. There are no tests that can tell the difference, and part of what cPickle's load_build() did looked accidental to me, so I don't know what the true intent is here. pickletester.py, test_pickle.py: Got rid of the hack for exempting cPickle from running some of the proto 2 tests. dictobject.c, PyDict_Next(): documented intended use. Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.138 retrieving revision 2.139 diff -C2 -d -r2.138 -r2.139 *** dictobject.c 29 Dec 2002 16:33:11 -0000 2.138 --- dictobject.c 15 Feb 2003 03:01:11 -0000 2.139 *************** *** 643,647 **** } ! /* CAUTION: In general, it isn't safe to use PyDict_Next in a loop that * mutates the dict. One exception: it is safe if the loop merely changes * the values associated with the keys (but doesn't insert new keys or --- 643,657 ---- } ! /* ! * Iterate over a dict. Use like so: ! * ! * int i; ! * PyObject *key, *value; ! * i = 0; # important! i should not otherwise be changed by you ! * while (PyDict_Next(yourdict, &i, &key, &value) { ! * Refer to borrowed references in key and value. ! * } ! * ! * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that * mutates the dict. One exception: it is safe if the loop merely changes * the values associated with the keys (but doesn't insert new keys or From tim_one@users.sourceforge.net Sat Feb 15 03:01:45 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 19:01:45 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.152,1.153 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv13821/python/Lib Modified Files: pickle.py Log Message: cPickle.c, load_build(): Taught cPickle how to pick apart the optional proto 2 slot state. pickle.py, load_build(): CAUTION: Noted that cPickle's load_build and pickle's load_build really don't do the same things with the state, and didn't before this patch either. cPickle never tries to do .update(), and has no backoff if instance.__dict__ can't be retrieved. There are no tests that can tell the difference, and part of what cPickle's load_build() did looked accidental to me, so I don't know what the true intent is here. pickletester.py, test_pickle.py: Got rid of the hack for exempting cPickle from running some of the proto 2 tests. dictobject.c, PyDict_Next(): documented intended use. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.152 retrieving revision 1.153 diff -C2 -d -r1.152 -r1.153 *** pickle.py 13 Feb 2003 15:44:39 -0000 1.152 --- pickle.py 15 Feb 2003 03:01:08 -0000 1.153 *************** *** 1250,1253 **** --- 1250,1257 ---- # difference when unpickling in restricted # vs. unrestricted modes. + # Note, however, that cPickle has never tried to do the + # .update() business, and always uses + # PyObject_SetItem(inst.__dict__, key, value) in a + # loop over state.items(). for k, v in state.items(): setattr(inst, k, v) From tim_one@users.sourceforge.net Sat Feb 15 03:01:45 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 14 Feb 2003 19:01:45 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.51,1.52 test_pickle.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv13821/python/Lib/test Modified Files: pickletester.py test_pickle.py Log Message: cPickle.c, load_build(): Taught cPickle how to pick apart the optional proto 2 slot state. pickle.py, load_build(): CAUTION: Noted that cPickle's load_build and pickle's load_build really don't do the same things with the state, and didn't before this patch either. cPickle never tries to do .update(), and has no backoff if instance.__dict__ can't be retrieved. There are no tests that can tell the difference, and part of what cPickle's load_build() did looked accidental to me, so I don't know what the true intent is here. pickletester.py, test_pickle.py: Got rid of the hack for exempting cPickle from running some of the proto 2 tests. dictobject.c, PyDict_Next(): documented intended use. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** pickletester.py 14 Feb 2003 23:05:26 -0000 1.51 --- pickletester.py 15 Feb 2003 03:01:09 -0000 1.52 *************** *** 729,738 **** self.assertEqual(x.__dict__, y.__dict__) - # XXX Temporary hack, so long as the C implementation of pickle protocol - # XXX 2 isn't ready. When it is, move the methods in TempAbstractPickleTests - # XXX into AbstractPickleTests above, and get rid of TempAbstractPickleTests - # XXX along with the references to it in test_pickle.py. - class TempAbstractPickleTests(unittest.TestCase): - def test_newobj_list_slots(self): x = SlotList([1, 2, 3]) --- 729,732 ---- *************** *** 745,748 **** --- 739,743 ---- self.assertEqual(x.foo, y.foo) self.assertEqual(x.bar, y.bar) + class MyInt(int): Index: test_pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pickle.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_pickle.py 30 Jan 2003 21:27:37 -0000 1.16 --- test_pickle.py 15 Feb 2003 03:01:09 -0000 1.17 *************** *** 6,14 **** from test.pickletester import AbstractPickleTests - from test.pickletester import TempAbstractPickleTests as XXXTemp from test.pickletester import AbstractPickleModuleTests from test.pickletester import AbstractPersistentPicklerTests ! class PickleTests(AbstractPickleTests, AbstractPickleModuleTests, XXXTemp): def dumps(self, arg, proto=0, fast=0): --- 6,13 ---- from test.pickletester import AbstractPickleTests from test.pickletester import AbstractPickleModuleTests from test.pickletester import AbstractPersistentPicklerTests ! class PickleTests(AbstractPickleTests, AbstractPickleModuleTests): def dumps(self, arg, proto=0, fast=0): From nnorwitz@users.sourceforge.net Sat Feb 15 14:45:16 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sat, 15 Feb 2003 06:45:16 -0800 Subject: [Python-checkins] python/dist/src/Objects dictobject.c,2.139,2.140 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv26167/Objects Modified Files: dictobject.c Log Message: Add closing ) in comment Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.139 retrieving revision 2.140 diff -C2 -d -r2.139 -r2.140 *** dictobject.c 15 Feb 2003 03:01:11 -0000 2.139 --- dictobject.c 15 Feb 2003 14:45:12 -0000 2.140 *************** *** 649,653 **** * PyObject *key, *value; * i = 0; # important! i should not otherwise be changed by you ! * while (PyDict_Next(yourdict, &i, &key, &value) { * Refer to borrowed references in key and value. * } --- 649,653 ---- * PyObject *key, *value; * i = 0; # important! i should not otherwise be changed by you ! * while (PyDict_Next(yourdict, &i, &key, &value)) { * Refer to borrowed references in key and value. * } From nnorwitz@users.sourceforge.net Sat Feb 15 15:07:21 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sat, 15 Feb 2003 07:07:21 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.137,2.138 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv1414/Modules Modified Files: cPickle.c Log Message: Make 2 module variables static. Assuming this is correct. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.137 retrieving revision 2.138 diff -C2 -d -r2.137 -r2.138 *** cPickle.c 15 Feb 2003 03:01:10 -0000 2.137 --- cPickle.c 15 Feb 2003 15:07:17 -0000 2.138 *************** *** 121,128 **** /* object.__reduce__, the default reduce callable. */ ! PyObject *object_reduce; /* copy_reg._better_reduce, the protocol 2 reduction function. */ ! PyObject *better_reduce; static PyObject *__class___str, *__getinitargs___str, *__dict___str, --- 121,128 ---- /* object.__reduce__, the default reduce callable. */ ! static PyObject *object_reduce; /* copy_reg._better_reduce, the protocol 2 reduction function. */ ! static PyObject *better_reduce; static PyObject *__class___str, *__getinitargs___str, *__dict___str, From tim.one@comcast.net Sat Feb 15 17:35:03 2003 From: tim.one@comcast.net (Tim Peters) Date: Sat, 15 Feb 2003 12:35:03 -0500 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.137,2.138 In-Reply-To: Message-ID: [nnorwitz@users.sourceforge.net] > Update of /cvsroot/python/python/dist/src/Modules > In directory sc8-pr-cvs1:/tmp/cvs-serv1414/Modules > > Modified Files: > cPickle.c > Log Message: > Make 2 module variables static. Assuming this is correct. Yes it is, and thank you! From gvanrossum@users.sourceforge.net Sun Feb 16 01:12:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sat, 15 Feb 2003 17:12:35 -0800 Subject: [Python-checkins] python/dist/src/Lib pydoc.py,1.76,1.77 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv29488 Modified Files: pydoc.py Log Message: Fix for SF 686380, from SF patch 686771 by Ping. (errors trying to get help on os attributes) Index: pydoc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pydoc.py,v retrieving revision 1.76 retrieving revision 1.77 diff -C2 -d -r1.76 -r1.77 *** pydoc.py 7 Feb 2003 20:49:40 -0000 1.76 --- pydoc.py 16 Feb 2003 01:12:32 -0000 1.77 *************** *** 1304,1308 **** def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" ! parts = split(path, '.') module, n = None, 0 while n < len(parts): --- 1304,1308 ---- def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" ! parts = [part for part in split(path, '.') if part] module, n = None, 0 while n < len(parts): From davecole@users.sourceforge.net Sun Feb 16 11:05:02 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 16 Feb 2003 03:05:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv19742 Modified Files: _csv.c Log Message: Use '\n' to signal end of line, not '\0' (idiot). Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** _csv.c 15 Feb 2003 00:52:59 -0000 1.32 --- _csv.c 16 Feb 2003 11:04:58 -0000 1.33 *************** *** 464,468 **** case START_RECORD: /* start of record */ ! if (c == '\0') /* empty line - return [] */ break; --- 464,468 ---- case START_RECORD: /* start of record */ ! if (c == '\n') /* empty line - return [] */ break; *************** *** 472,476 **** case START_FIELD: /* expecting field */ ! if (c == '\0') { /* save empty field - return [fields] */ parse_save_field(self); --- 472,476 ---- case START_FIELD: /* expecting field */ ! if (c == '\n') { /* save empty field - return [fields] */ parse_save_field(self); *************** *** 510,514 **** case IN_FIELD: /* in unquoted field */ ! if (c == '\0') { /* end of line - return [fields] */ parse_save_field(self); --- 510,514 ---- case IN_FIELD: /* in unquoted field */ ! if (c == '\n') { /* end of line - return [fields] */ parse_save_field(self); *************** *** 532,536 **** case IN_QUOTED_FIELD: /* in quoted field */ ! if (c == '\0') { /* end of line - save '\n' in field */ parse_add_char(self, '\n'); --- 532,536 ---- case IN_QUOTED_FIELD: /* in quoted field */ ! if (c == '\n') { /* end of line - save '\n' in field */ parse_add_char(self, '\n'); *************** *** 578,582 **** self->state = START_FIELD; } ! else if (c == '\0') { /* end of line - return [fields] */ parse_save_field(self); --- 578,582 ---- self->state = START_FIELD; } ! else if (c == '\n') { /* end of line - return [fields] */ parse_save_field(self); *************** *** 655,659 **** } ! /* Process line of text - send '\0' to processing code to represent end of line. End of line which is not at end of string is an error. */ --- 655,659 ---- } ! /* Process line of text - send '\n' to processing code to represent end of line. End of line which is not at end of string is an error. */ *************** *** 694,698 **** } } ! parse_process_char(self, '\0'); Py_DECREF(lineobj); } while (self->state != START_RECORD); --- 694,698 ---- } } ! parse_process_char(self, '\n'); Py_DECREF(lineobj); } while (self->state != START_RECORD); From davecole@users.sourceforge.net Sun Feb 16 11:25:19 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 16 Feb 2003 03:25:19 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv24912 Modified Files: _csv.c Log Message: Get Python to determine whether or not field data is numeric when quoting is QUOTE_NONNUMERIC by trying to convert to float. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** _csv.c 16 Feb 2003 11:04:58 -0000 1.33 --- _csv.c 16 Feb 2003 11:25:17 -0000 1.34 *************** *** 880,887 **** *quoted = 1; rec_len++; ! } else if (dialect->quoting == QUOTE_NONNUMERIC && ! !*quoted && ! !(isdigit(c) || c == '+' || c == '-' || c == '.')) ! *quoted = 1; /* Some special characters need to be escaped. If we have a --- 880,884 ---- *quoted = 1; rec_len++; ! } /* Some special characters need to be escaped. If we have a *************** *** 965,974 **** static int ! join_append(WriterObj *self, char *field, int quote_empty) { ! int rec_len, quoted; ! quoted = 0; ! rec_len = join_append_data(self, field, quote_empty, "ed, 0); if (rec_len < 0) return 0; --- 962,970 ---- static int ! join_append(WriterObj *self, char *field, int *quoted, int quote_empty) { ! int rec_len; ! rec_len = join_append_data(self, field, quote_empty, quoted, 0); if (rec_len < 0) return 0; *************** *** 978,982 **** return 0; ! self->rec_len = join_append_data(self, field, quote_empty, "ed, 1); self->num_fields++; --- 974,978 ---- return 0; ! self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); self->num_fields++; *************** *** 1012,1015 **** --- 1008,1012 ---- csv_writerow(WriterObj *self, PyObject *seq) { + DialectObj *dialect = self->dialect; int len, i; *************** *** 1027,1030 **** --- 1024,1028 ---- PyObject *field; int append_ok; + int quoted; field = PySequence_GetItem(seq, i); *************** *** 1032,1042 **** return NULL; if (PyString_Check(field)) { append_ok = join_append(self, PyString_AsString(field), ! len == 1); Py_DECREF(field); } else if (field == Py_None) { ! append_ok = join_append(self, "", len == 1); Py_DECREF(field); } --- 1030,1053 ---- return NULL; + quoted = 0; + if (dialect->quoting == QUOTE_NONNUMERIC) { + PyObject *num; + + num = PyNumber_Float(field); + if (num == NULL) { + quoted = 1; + PyErr_Clear(); + } else { + Py_DECREF(num); + } + } + if (PyString_Check(field)) { append_ok = join_append(self, PyString_AsString(field), ! "ed, len == 1); Py_DECREF(field); } else if (field == Py_None) { ! append_ok = join_append(self, "", "ed, len == 1); Py_DECREF(field); } *************** *** 1050,1054 **** append_ok = join_append(self, PyString_AsString(str), ! len == 1); Py_DECREF(str); } --- 1061,1065 ---- append_ok = join_append(self, PyString_AsString(str), ! "ed, len == 1); Py_DECREF(str); } From davecole@users.sourceforge.net Sun Feb 16 11:26:03 2003 From: davecole@users.sourceforge.net (davecole@users.sourceforge.net) Date: Sun, 16 Feb 2003 03:26:03 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv _csv.c,1.34,1.35 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv25253 Modified Files: _csv.c Log Message: Fixed my non-Guido formatting. Index: _csv.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/_csv.c,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** _csv.c 16 Feb 2003 11:25:17 -0000 1.34 --- _csv.c 16 Feb 2003 11:26:01 -0000 1.35 *************** *** 1038,1042 **** quoted = 1; PyErr_Clear(); ! } else { Py_DECREF(num); } --- 1038,1043 ---- quoted = 1; PyErr_Clear(); ! } ! else { Py_DECREF(num); } From jackjansen@users.sourceforge.net Sun Feb 16 21:28:55 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 16 Feb 2003 13:28:55 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyEdit.py,1.36,1.37 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv17048 Modified Files: PyEdit.py Log Message: When building an applet clear out the tempfile and dir afterwards. Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** PyEdit.py 12 Feb 2003 15:38:37 -0000 1.36 --- PyEdit.py 16 Feb 2003 21:28:51 -0000 1.37 *************** *** 473,476 **** --- 473,481 ---- template = buildtools.findtemplate() buildtools.process(template, filename, destname, rsrcname=rsrcname, progress=None) + try: + os.remove(filename) + os.rmdir(tmpdir) + except os.error: + pass def domenu_gotoline(self, *args): From jackjansen@users.sourceforge.net Sun Feb 16 23:00:59 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 16 Feb 2003 15:00:59 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.660,1.661 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv21478 Modified Files: NEWS Log Message: Added notes about pimp and bundlebuilder to the Mac section. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.660 retrieving revision 1.661 diff -C2 -d -r1.660 -r1.661 *** NEWS 14 Feb 2003 19:29:21 -0000 1.660 --- NEWS 16 Feb 2003 23:00:53 -0000 1.661 *************** *** 359,362 **** --- 359,370 ---- - Type Carbon.File.FSCatalogInfo and supporting methods have been implemented. This also makes macfs.FSSpec.SetDates() work again. + + - There is a new module pimp, the package install manager for Python, and + accompanying applet PackageManager. These allow you to easily download + and install pretested extension packages either in source or binary + form. Only in MacPython-OSX. + + - Applets are now built with bundlebuilder in MacPython-OSX, which should make + them more robust and also provides a path towards BuildApplication. From jackjansen@users.sourceforge.net Sun Feb 16 23:03:10 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 16 Feb 2003 15:03:10 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv23814 Modified Files: pimp.py Log Message: Better error messages and warnings. Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** pimp.py 14 Feb 2003 14:11:59 -0000 1.10 --- pimp.py 16 Feb 2003 23:03:04 -0000 1.11 *************** *** 358,362 **** rv = [] if not self._dict.get('Download-URL'): ! return [(None, "This package needs to be installed manually")] if not self._dict.get('Prerequisites'): return [] --- 358,364 ---- rv = [] if not self._dict.get('Download-URL'): ! return [(None, ! "%s: This package needs to be installed manually (no Download-URL field)" % ! self.fullname())] if not self._dict.get('Prerequisites'): return [] *************** *** 448,452 **** else: return "unknown extension for archive file: %s" % filename ! basename = filename[:-len(ext)] cmd = cmd % self.archiveFilename if self._cmd(output, self._db.preferences.buildDir, cmd): --- 450,454 ---- else: return "unknown extension for archive file: %s" % filename ! self.basename = filename[:-len(ext)] cmd = cmd % self.archiveFilename if self._cmd(output, self._db.preferences.buildDir, cmd): *************** *** 455,459 **** def installPackageOnly(self, output=None): """Default install method, to be overridden by subclasses""" ! return "Cannot automatically install package %s" % self.fullname() def installSinglePackage(self, output=None): --- 457,462 ---- def installPackageOnly(self, output=None): """Default install method, to be overridden by subclasses""" ! return "%s: This package needs to be installed manually (no support for flavor=\"%s\")" \ ! % (self.fullname(), self._dict.get(flavor, "")) def installSinglePackage(self, output=None): *************** *** 464,475 **** if not self._dict['Download-URL']: ! return "%s: This package needs to be installed manually" % _fmtpackagename(self) msg = self.downloadPackageOnly(output) if msg: ! return "download %s: %s" % (self.fullname(), msg) msg = self.unpackPackageOnly(output) if msg: ! return "unpack %s: %s" % (self.fullname(), msg) return self.installPackageOnly(output) --- 467,478 ---- if not self._dict['Download-URL']: ! return "%s: This package needs to be installed manually (no Download-URL field)" % _fmtpackagename(self) msg = self.downloadPackageOnly(output) if msg: ! return "%s: download: %s" % (self.fullname(), msg) msg = self.unpackPackageOnly(output) if msg: ! return "%s: unpack: %s" % (self.fullname(), msg) return self.installPackageOnly(output) *************** *** 518,521 **** --- 521,525 ---- If output is given it should be a file-like object and it will receive a log of what happened.""" + print 'PimpPackage_binary installPackageOnly' msgs = [] *************** *** 558,562 **** PimpPackage.unpackPackageOnly(self, output) # Test that a setup script has been create ! self._buildDirname = os.path.join(self._db.preferences.buildDir, basename) setupname = os.path.join(self._buildDirname, "setup.py") if not os.path.exists(setupname) and not NO_EXECUTE: --- 562,566 ---- PimpPackage.unpackPackageOnly(self, output) # Test that a setup script has been create ! self._buildDirname = os.path.join(self._db.preferences.buildDir, self.basename) setupname = os.path.join(self._buildDirname, "setup.py") if not os.path.exists(setupname) and not NO_EXECUTE: From jhylton@users.sourceforge.net Mon Feb 17 04:31:30 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Sun, 16 Feb 2003 20:31:30 -0800 Subject: [Python-checkins] python/dist/src/Python newcompile.c,1.1.2.16,1.1.2.17 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv10430/Python Modified Files: Tag: ast-branch newcompile.c Log Message: Add code generation for Compare(). Index: newcompile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/Attic/newcompile.c,v retrieving revision 1.1.2.16 retrieving revision 1.1.2.17 diff -C2 -d -r1.1.2.16 -r1.1.2.17 *** newcompile.c 21 Oct 2002 22:36:16 -0000 1.1.2.16 --- newcompile.c 17 Feb 2003 04:31:27 -0000 1.1.2.17 *************** *** 38,42 **** int u_nalloc; int u_curblock; - struct basicblock u_entry; struct basicblock u_exit; struct basicblock **u_blocks; --- 38,41 ---- *************** *** 1061,1064 **** --- 1060,1099 ---- return 1; } + + static int + compiler_compare(struct compiler *c, expr_ty e) + { + int i, n, cleanup; + + VISIT(c, expr, e->v.Compare.left); + n = asdl_seq_LEN(e->v.Compare.ops); + if (n > 1) + cleanup = compiler_new_block(c); + for (i = 1; i < n; i++) { + ADDOP(c, DUP_TOP); + ADDOP(c, ROT_THREE); + ADDOP_I(c, COMPARE_OP, + asdl_seq_GET(e->v.Compare.ops, i - 1)); + ADDOP_JREL(c, JUMP_IF_FALSE, cleanup); + NEXT_BLOCK(c); + ADDOP(c, POP_TOP); + } + if (n) { + VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1)); + ADDOP_I(c, COMPARE_OP, + (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)); + } + if (n > 1) { + int end = compiler_new_block(c); + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_block(c, cleanup); + ADDOP(c, ROT_TWO); + ADDOP(c, POP_TOP); + compiler_use_block(c, end); + } + return 1; + } + + static int *************** *** 1099,1102 **** --- 1134,1138 ---- break; case Compare_kind: + return compiler_compare(c, e); break; case Call_kind: *************** *** 1627,1629 **** "CALL_FUNCTION_VAR_KW", "EXTENDED_ARG", ! }; --- 1663,1666 ---- "CALL_FUNCTION_VAR_KW", "EXTENDED_ARG", ! }; ! From aimacintyre@users.sourceforge.net Mon Feb 17 09:17:54 2003 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Mon, 17 Feb 2003 01:17:54 -0800 Subject: [Python-checkins] python/dist/src/Lib ntpath.py,1.55,1.56 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv11910 Modified Files: ntpath.py Log Message: Tweak to Skip's checkin of patch 686397: - 'os2' references in ntpath.py relate to the VACPP port, not the EMX port; - the VACPP port uses the same defpath as all other ntpath.py supported platforms except 'ce'. Index: ntpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/ntpath.py,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** ntpath.py 14 Feb 2003 19:35:30 -0000 1.55 --- ntpath.py 17 Feb 2003 09:17:50 -0000 1.56 *************** *** 24,34 **** pathsep = ';' altsep = None if 'ce' in sys.builtin_module_names: defpath = '\\Windows' elif 'os2' in sys.builtin_module_names: ! # OS/2 w/ EMX altsep = '/' - else: - defpath = '.;C:\\bin' # Normalize the case of a pathname and map slashes to backslashes. --- 24,33 ---- pathsep = ';' altsep = None + defpath = '.;C:\\bin' if 'ce' in sys.builtin_module_names: defpath = '\\Windows' elif 'os2' in sys.builtin_module_names: ! # OS/2 w/ VACPP altsep = '/' # Normalize the case of a pathname and map slashes to backslashes. From aimacintyre@users.sourceforge.net Mon Feb 17 09:20:31 2003 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Mon, 17 Feb 2003 01:20:31 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.661,1.662 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv12762 Modified Files: NEWS Log Message: Patch 686397: move definition of platform dependent path related variables from os.py to platform dependent path modules (ntpath, etc). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.661 retrieving revision 1.662 diff -C2 -d -r1.661 -r1.662 *** NEWS 16 Feb 2003 23:00:53 -0000 1.661 --- NEWS 17 Feb 2003 09:20:23 -0000 1.662 *************** *** 225,228 **** --- 225,234 ---- ------- + - the platform dependent path related variables sep, altsep, extsep, + pathsep, curdir, pardir and defpath are now defined in the platform + dependent path modules (e.g. ntpath.py) rather than os.py. These + variables continue to be available via os.path (see + ). + - array.array was added to the types repr.py knows about (see ). From jackjansen@users.sourceforge.net Mon Feb 17 12:21:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 04:21:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac pimp.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv1380 Modified Files: pimp.py Log Message: - Added support for zip archives - Better messages in case of a crash of the install-test script Index: pimp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/pimp.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** pimp.py 16 Feb 2003 23:03:04 -0000 1.11 --- pimp.py 17 Feb 2003 12:21:05 -0000 1.12 *************** *** 47,50 **** --- 47,51 ---- (".tgz", "zcat \"%s\" | tar -xf -"), (".tar.bz", "bzcat \"%s\" | tar -xf -"), + (".zip", "unzip \"%s\""), ] *************** *** 344,347 **** --- 345,358 ---- return "bad", str(arg) except: + sys.stderr.write("-------------------------------------\n") + sys.stderr.write("---- %s: install test got exception\n" % self.fullname()) + sys.stderr.write("---- source:\n") + sys.stderr.write(installTest) + sys.stderr.write("---- exception:\n") + import traceback + traceback.print_exc(file=sys.stderr) + if self._db._maintainer: + sys.stderr.write("---- Please copy this and mail to %s\n" % self._db._maintainer) + sys.stderr.write("-------------------------------------\n") return "bad", "Package install test got exception" return "yes", "" *************** *** 541,548 **** return "unknown extension for archive file: %s" % filename ! # Modify where the files are extracted ! prefixmod = '-C /' cmd = cmd % self.archiveFilename ! if self._cmd(output, self._db.preferences.buildDir, cmd, prefixmod): return "unpack command failed" --- 552,558 ---- return "unknown extension for archive file: %s" % filename ! # Extract the files in the root folder. cmd = cmd % self.archiveFilename ! if self._cmd(output, "/", cmd): return "unpack command failed" From mwh@users.sourceforge.net Mon Feb 17 12:26:26 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Mon, 17 Feb 2003 04:26:26 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.662,1.663 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv3879 Modified Files: NEWS Log Message: Reword section about moving variables to os.path to match intent (or at least, what I thought the intent was). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.662 retrieving revision 1.663 diff -C2 -d -r1.662 -r1.663 *** NEWS 17 Feb 2003 09:20:23 -0000 1.662 --- NEWS 17 Feb 2003 12:26:23 -0000 1.663 *************** *** 227,233 **** - the platform dependent path related variables sep, altsep, extsep, pathsep, curdir, pardir and defpath are now defined in the platform ! dependent path modules (e.g. ntpath.py) rather than os.py. These ! variables continue to be available via os.path (see ! ). - array.array was added to the types repr.py knows about (see --- 227,234 ---- - the platform dependent path related variables sep, altsep, extsep, pathsep, curdir, pardir and defpath are now defined in the platform ! dependent path modules (e.g. ntpath.py) rather than os.py, so these ! variables are now available via os.path. They continue to be ! available from the os module. ! (see ). - array.array was added to the types repr.py knows about (see From nnorwitz@users.sourceforge.net Mon Feb 17 14:51:44 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 06:51:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_imp.py,1.1,1.2 test_importhooks.py,1.1,1.2 test_multifile.py,1.2,1.3 test_netrc.py,1.4,1.5 test_tarfile.py,1.1,1.2 test_timeout.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22333 Modified Files: test_imp.py test_importhooks.py test_multifile.py test_netrc.py test_tarfile.py test_timeout.py Log Message: Actually run these tests from regrtest.py. There was no test_main() and the main body was protected by if __name__ == '__main__' so the test didn't happen on import either. Index: test_imp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_imp.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_imp.py 12 Feb 2003 23:02:21 -0000 1.1 --- test_imp.py 17 Feb 2003 14:51:40 -0000 1.2 *************** *** 2,6 **** import imp import unittest ! from test_support import TestFailed class ImpLock(unittest.TestCase): --- 2,6 ---- import imp import unittest ! from test_support import TestFailed, run_unittest class ImpLock(unittest.TestCase): *************** *** 23,26 **** "release_lock() without lock should raise RuntimeError" if __name__ == "__main__": ! test_support.run_unittest(ImpLock) --- 23,29 ---- "release_lock() without lock should raise RuntimeError" + def test_main(): + run_unittest(ImpLock) + if __name__ == "__main__": ! test_main() Index: test_importhooks.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_importhooks.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_importhooks.py 30 Dec 2002 22:08:03 -0000 1.1 --- test_importhooks.py 17 Feb 2003 14:51:41 -0000 1.2 *************** *** 200,204 **** m.__loader__ # to make sure we actually handled the import if __name__ == "__main__": ! test_support.run_unittest(ImportHooksTestCase) --- 200,206 ---- m.__loader__ # to make sure we actually handled the import + def test_main(): + test_support.run_unittest(ImportHooksTestCase) if __name__ == "__main__": ! test_main() Index: test_multifile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_multifile.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_multifile.py 29 Sep 2002 00:25:51 -0000 1.2 --- test_multifile.py 17 Feb 2003 14:51:41 -0000 1.3 *************** *** 57,61 **** linecount += len(lines) ! def main(): f = cStringIO.StringIO(msg) getMIMEMsg(multifile.MultiFile(f)) --- 57,61 ---- linecount += len(lines) ! def test_main(): f = cStringIO.StringIO(msg) getMIMEMsg(multifile.MultiFile(f)) *************** *** 64,66 **** if __name__ == '__main__': ! main() --- 64,66 ---- if __name__ == '__main__': ! test_main() Index: test_netrc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_netrc.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_netrc.py 9 Aug 2002 16:37:35 -0000 1.4 --- test_netrc.py 17 Feb 2003 14:51:41 -0000 1.5 *************** *** 39,43 **** self.assert_(self.netrc.hosts['default'] == ('log2', None, 'pass2')) if __name__ == "__main__": ! test_support.run_unittest(NetrcTestCase) --- 39,45 ---- self.assert_(self.netrc.hosts['default'] == ('log2', None, 'pass2')) + def test_main(): + test_support.run_unittest(NetrcTestCase) if __name__ == "__main__": ! test_main() Index: test_tarfile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_tarfile.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_tarfile.py 5 Jan 2003 23:19:43 -0000 1.1 --- test_tarfile.py 17 Feb 2003 14:51:41 -0000 1.2 *************** *** 232,236 **** del WriteStreamTestGzip ! if __name__ == "__main__": if gzip: # create testtar.tar.gz --- 232,236 ---- del WriteStreamTestGzip ! def test_main(): if gzip: # create testtar.tar.gz *************** *** 241,245 **** try: ! unittest.main() finally: if gzip: --- 241,264 ---- try: ! suite = unittest.TestSuite() ! ! suite.addTest(unittest.makeSuite(ReadTest)) ! suite.addTest(unittest.makeSuite(ReadStreamTest)) ! suite.addTest(unittest.makeSuite(WriteTest)) ! suite.addTest(unittest.makeSuite(WriteStreamTest)) ! ! if gzip: ! suite.addTest(unittest.makeSuite(ReadTestGzip)) ! suite.addTest(unittest.makeSuite(ReadStreamTestGzip)) ! suite.addTest(unittest.makeSuite(WriteTestGzip)) ! suite.addTest(unittest.makeSuite(WriteStreamTestGzip)) ! ! if bz2: ! suite.addTest(unittest.makeSuite(ReadTestBzip2)) ! suite.addTest(unittest.makeSuite(ReadStreamTestBzip2)) ! suite.addTest(unittest.makeSuite(WriteTestBzip2)) ! suite.addTest(unittest.makeSuite(WriteStreamTestBzip2)) ! ! test_support.run_suite(suite) finally: if gzip: *************** *** 252,253 **** --- 271,274 ---- os.remove(tempname) + if __name__ == "__main__": + test_main() Index: test_timeout.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_timeout.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** test_timeout.py 3 Sep 2002 19:17:47 -0000 1.9 --- test_timeout.py 17 Feb 2003 14:51:41 -0000 1.10 *************** *** 176,180 **** ! def main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CreationTestCase)) --- 176,180 ---- ! def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CreationTestCase)) *************** *** 183,185 **** if __name__ == "__main__": ! main() --- 183,185 ---- if __name__ == "__main__": ! test_main() From jackjansen@users.sourceforge.net Mon Feb 17 15:40:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 07:40:03 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/PythonLauncher/English.lproj/MyDocument.nib classes.nib,1.1,1.2 info.nib,1.1,1.2 objects.nib,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/English.lproj/MyDocument.nib In directory sc8-pr-cvs1:/tmp/cvs-serv21319/PythonLauncher/English.lproj/MyDocument.nib Modified Files: classes.nib info.nib objects.nib Log Message: Optionally honour #! paths in scripts. Fixes #676358. Index: classes.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/English.lproj/MyDocument.nib/classes.nib,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** classes.nib 29 Jul 2002 21:36:35 -0000 1.1 --- classes.nib 17 Feb 2003 15:40:00 -0000 1.2 *************** *** 3,7 **** {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, { ! ACTIONS = {do_apply = id; do_cancel = id; do_reset = id; do_run = id; }; CLASS = MyDocument; LANGUAGE = ObjC; --- 3,7 ---- {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, { ! ACTIONS = {"do_apply" = id; "do_cancel" = id; "do_reset" = id; "do_run" = id; }; CLASS = MyDocument; LANGUAGE = ObjC; *************** *** 9,12 **** --- 9,13 ---- commandline = NSTextField; debug = NSButton; + honourhashbang = NSButton; inspect = NSButton; interpreter = NSTextField; *************** *** 16,20 **** tabs = NSButton; verbose = NSButton; ! with_terminal = NSButton; }; SUPERCLASS = NSDocument; --- 17,21 ---- tabs = NSButton; verbose = NSButton; ! "with_terminal" = NSButton; }; SUPERCLASS = NSDocument; Index: info.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/English.lproj/MyDocument.nib/info.nib,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** info.nib 29 Jul 2002 21:36:35 -0000 1.1 --- info.nib 17 Feb 2003 15:40:00 -0000 1.2 *************** *** 1,10 **** ! ! IBDocumentLocation ! 265 40 356 240 0 0 800 578 IBFramework Version ! 263.2 IBOpenObjects --- 1,10 ---- ! ! IBDocumentLocation ! 551 90 356 240 0 0 1280 1002 IBFramework Version ! 286.0 IBOpenObjects *************** *** 12,16 **** IBSystem Version ! 5S66 --- 12,16 ---- IBSystem Version ! 6I32 Index: objects.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/English.lproj/MyDocument.nib/objects.nib,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 Binary files /tmp/cvs1laePu and /tmp/cvs6QMMpP differ From jackjansen@users.sourceforge.net Mon Feb 17 15:40:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 07:40:03 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/PythonLauncher/PreferenceWindow.nib classes.nib,1.2,1.3 info.nib,1.2,1.3 objects.nib,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferenceWindow.nib In directory sc8-pr-cvs1:/tmp/cvs-serv21319/PythonLauncher/PreferenceWindow.nib Modified Files: classes.nib info.nib objects.nib Log Message: Optionally honour #! paths in scripts. Fixes #676358. Index: classes.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferenceWindow.nib/classes.nib,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** classes.nib 26 Dec 2002 22:10:53 -0000 1.2 --- classes.nib 17 Feb 2003 15:40:00 -0000 1.3 *************** *** 10,13 **** --- 10,14 ---- debug = NSButton; filetype = NSPopUpButton; + honourhashbang = NSButton; inspect = NSButton; interpreter = NSTextField; Index: info.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferenceWindow.nib/info.nib,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** info.nib 26 Dec 2002 22:10:53 -0000 1.2 --- info.nib 17 Feb 2003 15:40:00 -0000 1.3 *************** *** 4,10 **** IBDocumentLocation ! 126 59 356 240 0 0 1024 746 IBFramework Version ! 291.0 IBOpenObjects --- 4,10 ---- IBDocumentLocation ! 660 84 519 534 0 0 1280 1002 IBFramework Version ! 286.0 IBOpenObjects *************** *** 12,16 **** IBSystem Version ! 6G30 --- 12,16 ---- IBSystem Version ! 6I32 Index: objects.nib =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferenceWindow.nib/objects.nib,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 Binary files /tmp/cvslcZKeu and /tmp/cvs0vfzfO differ From jackjansen@users.sourceforge.net Mon Feb 17 15:40:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 07:40:03 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/PythonLauncher/PythonLauncher.pbproj project.pbxproj,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PythonLauncher.pbproj In directory sc8-pr-cvs1:/tmp/cvs-serv21319/PythonLauncher/PythonLauncher.pbproj Modified Files: project.pbxproj Log Message: Optionally honour #! paths in scripts. Fixes #676358. Index: project.pbxproj =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PythonLauncher.pbproj/project.pbxproj,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** project.pbxproj 26 Dec 2002 22:10:53 -0000 1.8 --- project.pbxproj 17 Feb 2003 15:40:00 -0000 1.9 *************** *** 133,137 **** 4A9504D1FFE6A4CB11CA0CBA, ); - hasScannedForEncodings = 1; isa = PBXProject; mainGroup = 2A37F4AAFDCFA73011CA2CEA; --- 133,136 ---- *************** *** 405,408 **** --- 404,408 ---- "; + shouldUseHeadermap = 0; }; 2A37F4C7FDCFA73011CA2CEA = { From jackjansen@users.sourceforge.net Mon Feb 17 15:40:03 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 07:40:03 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/PythonLauncher FileSettings.h,1.3,1.4 FileSettings.m,1.5,1.6 MyDocument.h,1.1,1.2 MyDocument.m,1.3,1.4 PreferencesWindowController.h,1.2,1.3 PreferencesWindowController.m,1.3,1.4 factorySettings.plist,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher In directory sc8-pr-cvs1:/tmp/cvs-serv21319/PythonLauncher Modified Files: FileSettings.h FileSettings.m MyDocument.h MyDocument.m PreferencesWindowController.h PreferencesWindowController.m factorySettings.plist Log Message: Optionally honour #! paths in scripts. Fixes #676358. Index: FileSettings.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/FileSettings.h,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FileSettings.h 26 Dec 2002 22:10:53 -0000 1.3 --- FileSettings.h 17 Feb 2003 15:39:59 -0000 1.4 *************** *** 11,14 **** --- 11,15 ---- @protocol FileSettingsSource - (NSString *) interpreter; + - (BOOL) honourhashbang; - (BOOL) debug; - (BOOL) verbose; *************** *** 25,28 **** --- 26,30 ---- NSString *interpreter; // The pathname of the interpreter to use NSArray *interpreters; // List of known interpreters + BOOL honourhashbang; // #! line overrides interpreter BOOL debug; // -d option: debug parser BOOL verbose; // -v option: verbose import Index: FileSettings.m =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/FileSettings.m,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** FileSettings.m 26 Dec 2002 22:10:53 -0000 1.5 --- FileSettings.m 17 Feb 2003 15:39:59 -0000 1.6 *************** *** 70,73 **** --- 70,74 ---- interpreter = [source->interpreter retain]; + honourhashbang = source->honourhashbang; debug = source->debug; verbose = source->verbose; *************** *** 183,186 **** --- 184,188 ---- { interpreter = [[source interpreter] retain]; + honourhashbang = [source honourhashbang]; debug = [source debug]; verbose = [source verbose]; *************** *** 197,200 **** --- 199,203 ---- NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: interpreter, @"interpreter", + [NSNumber numberWithBool: honourhashbang], @"honourhashbang", [NSNumber numberWithBool: debug], @"debug", [NSNumber numberWithBool: verbose], @"verbose", *************** *** 217,220 **** --- 220,225 ---- value = [dict objectForKey: @"interpreter"]; if (value) interpreter = [value retain]; + value = [dict objectForKey: @"honourhashbang"]; + if (value) honourhashbang = [value boolValue]; value = [dict objectForKey: @"debug"]; if (value) debug = [value boolValue]; *************** *** 237,243 **** - (NSString *)commandLineForScript: (NSString *)script { return [NSString stringWithFormat: @"\"%@\"%s%s%s%s%s%s %@ \"%@\" %s", ! interpreter, debug?" -d":"", verbose?" -v":"", --- 242,266 ---- - (NSString *)commandLineForScript: (NSString *)script { + NSString *cur_interp = NULL; + char hashbangbuf[1024]; + FILE *fp; + char *p; + + if (honourhashbang && + (fp=fopen([script cString], "r")) && + fgets(hashbangbuf, sizeof(hashbangbuf), fp) && + strncmp(hashbangbuf, "#!", 2) == 0 && + (p=strchr(hashbangbuf, '\n'))) { + *p = '\0'; + p = hashbangbuf + 2; + while (*p == ' ') p++; + cur_interp = [NSString stringWithCString: p]; + } + if (!cur_interp) + cur_interp = interpreter; + return [NSString stringWithFormat: @"\"%@\"%s%s%s%s%s%s %@ \"%@\" %s", ! cur_interp, debug?" -d":"", verbose?" -v":"", *************** *** 255,258 **** --- 278,282 ---- // FileSettingsSource protocol - (NSString *) interpreter { return interpreter;}; + - (BOOL) honourhashbang { return honourhashbang; }; - (BOOL) debug { return debug;}; - (BOOL) verbose { return verbose;}; Index: MyDocument.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/MyDocument.h,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** MyDocument.h 29 Jul 2002 21:36:35 -0000 1.1 --- MyDocument.h 17 Feb 2003 15:39:59 -0000 1.2 *************** *** 15,18 **** --- 15,19 ---- { IBOutlet NSTextField *interpreter; + IBOutlet NSButton *honourhashbang; IBOutlet NSButton *debug; IBOutlet NSButton *verbose; Index: MyDocument.m =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/MyDocument.m,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** MyDocument.m 25 Nov 2002 13:11:05 -0000 1.3 --- MyDocument.m 17 Feb 2003 15:39:59 -0000 1.4 *************** *** 53,56 **** --- 53,57 ---- [interpreter setStringValue: [settings interpreter]]; + [honourhashbang setState: [settings honourhashbang]]; [debug setState: [settings debug]]; [verbose setState: [settings verbose]]; *************** *** 153,156 **** --- 154,158 ---- // FileSettingsSource protocol - (NSString *) interpreter { return [interpreter stringValue];}; + - (BOOL) honourhashbang { return [honourhashbang state];}; - (BOOL) debug { return [debug state];}; - (BOOL) verbose { return [verbose state];}; Index: PreferencesWindowController.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferencesWindowController.h,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PreferencesWindowController.h 26 Dec 2002 22:10:53 -0000 1.2 --- PreferencesWindowController.h 17 Feb 2003 15:39:59 -0000 1.3 *************** *** 9,12 **** --- 9,13 ---- IBOutlet NSPopUpButton *filetype; IBOutlet NSTextField *interpreter; + IBOutlet NSButton *honourhashbang; IBOutlet NSButton *debug; IBOutlet NSButton *verbose; Index: PreferencesWindowController.m =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/PreferencesWindowController.m,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PreferencesWindowController.m 26 Dec 2002 22:10:53 -0000 1.3 --- PreferencesWindowController.m 17 Feb 2003 15:39:59 -0000 1.4 *************** *** 31,34 **** --- 31,35 ---- [interpreter setStringValue: [settings interpreter]]; + [honourhashbang setState: [settings honourhashbang]]; [debug setState: [settings debug]]; [verbose setState: [settings verbose]]; *************** *** 75,78 **** --- 76,80 ---- // FileSettingsSource protocol - (NSString *) interpreter { return [interpreter stringValue];}; + - (BOOL) honourhashbang { return [honourhashbang state]; }; - (BOOL) debug { return [debug state];}; - (BOOL) verbose { return [verbose state];}; Index: factorySettings.plist =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/factorySettings.plist,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** factorySettings.plist 26 Dec 2002 22:10:53 -0000 1.2 --- factorySettings.plist 17 Feb 2003 15:40:00 -0000 1.3 *************** *** 17,20 **** --- 17,22 ---- /Applications/MacPython-OSX/python-additions/Python.app/Contents/MacOS/python + honourhashbang + nosite *************** *** 46,50 **** /Applications/MacPython-OSX/python-additions/Python.app/Contents/MacOS/python ! nosite optimize --- 48,54 ---- /Applications/MacPython-OSX/python-additions/Python.app/Contents/MacOS/python ! honourhashbang ! ! nosite optimize *************** *** 70,74 **** /usr/bin/python ! nosite optimize --- 74,80 ---- /usr/bin/python ! honourhashbang ! ! nosite optimize From jackjansen@users.sourceforge.net Mon Feb 17 16:47:18 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 17 Feb 2003 08:47:18 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.7,1.8 macresource.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv29649 Modified Files: bundlebuilder.py macresource.py Log Message: When installing resource files whose name ends in .rsrc use the "copy anything to a data fork based resource file" trick of macresource. Fixes #688007. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** bundlebuilder.py 12 Feb 2003 16:19:39 -0000 1.7 --- bundlebuilder.py 17 Feb 2003 16:47:12 -0000 1.8 *************** *** 37,40 **** --- 37,41 ---- from plistlib import Plist from types import FunctionType as function + import macresource *************** *** 189,192 **** --- 190,195 ---- if self.symlink: symlink(src, dst, mkdirs=1) + elif os.path.splitext(src)[1] == '.rsrc': + macresource.install(src, dst, mkdirs=1) else: copy(src, dst, mkdirs=1) Index: macresource.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/macresource.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** macresource.py 6 Jan 2003 11:15:05 -0000 1.2 --- macresource.py 17 Feb 2003 16:47:12 -0000 1.3 *************** *** 4,7 **** --- 4,9 ---- import os import sys + import MacOS + import macostools class ArgumentError(TypeError): pass *************** *** 100,109 **** need('Estr', 1, filename="errors.rsrc", modname=__name__) ! def _decode(pathname, verbose=0): # Decode an AppleSingle resource file, return the new pathname. ! newpathname = pathname + '.df.rsrc' ! if os.path.exists(newpathname) and \ os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime: ! return newpathname if verbose: print 'Decoding', pathname --- 102,112 ---- need('Estr', 1, filename="errors.rsrc", modname=__name__) ! def _decode(pathname, verbose=0, newpathname=None): # Decode an AppleSingle resource file, return the new pathname. ! if not newpathname: ! newpathname = pathname + '.df.rsrc' ! if os.path.exists(newpathname) and \ os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime: ! return newpathname if verbose: print 'Decoding', pathname *************** *** 112,114 **** return newpathname ! \ No newline at end of file --- 115,151 ---- return newpathname ! def install(src, dst, mkdirs=0): ! """Copy a resource file. The result will always be a datafork-based ! resource file, whether the source is datafork-based, resource-fork ! based or AppleSingle-encoded.""" ! if mkdirs: ! macostools.mkdirs(os.path.split(dst)[0]) ! try: ! refno = Res.FSOpenResourceFile(src, u'', 1) ! except Res.Error, arg: ! if arg[0] != -199: ! # -199 is "bad resource map" ! raise ! else: ! # Resource-fork based. Simply copy. ! Res.CloseResFile(refno) ! macostools.copy(src, dst) ! ! try: ! refno = Res.FSpOpenResFile(src, 1) ! except Res.Error, arg: ! if not arg[0] in (-37, -39): ! raise ! else: ! Res.CloseResFile(refno) ! BUFSIZ=0x80000 # Copy in 0.5Mb chunks ! ifp = MacOS.openrf(src, '*rb') ! ofp = open(dst, 'wb') ! d = ifp.read(BUFSIZ) ! while d: ! ofp.write(d) ! d = ifp.read(BUFSIZ) ! ifp.close() ! ofp.close() ! ! _decode(src, newpathname=dst) From nnorwitz@users.sourceforge.net Mon Feb 17 18:05:24 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:05:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_zipimport.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv9924/Lib/test Modified Files: test_zipimport.py Log Message: Use correct function name to PyArg_ParseTuple("is_package"). Fix off-by-1 error in normalize_line_endings(): when *p == '\0' the NUL was copied into q and q was auto-incremented, the loop was broken out of, then a newline was appended followed by a NUL. So the function, in effect, was strcpy() but added two extra chars which was caught by obmalloc in debug mode, since there was only room for 1 additional newline. Get test working under regrtest (added test_main). Index: test_zipimport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_zipimport.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_zipimport.py 9 Jan 2003 22:27:10 -0000 1.5 --- test_zipimport.py 17 Feb 2003 18:05:20 -0000 1.6 *************** *** 187,191 **** ! if __name__ == "__main__": test_support.run_unittest(UncompressedZipImportTestCase) test_support.run_unittest(CompressedZipImportTestCase) --- 187,194 ---- ! def test_main(): test_support.run_unittest(UncompressedZipImportTestCase) test_support.run_unittest(CompressedZipImportTestCase) + + if __name__ == "__main__": + test_main() From nnorwitz@users.sourceforge.net Mon Feb 17 18:05:23 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:05:23 -0800 Subject: [Python-checkins] python/dist/src/Modules zipimport.c,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9924/Modules Modified Files: zipimport.c Log Message: Use correct function name to PyArg_ParseTuple("is_package"). Fix off-by-1 error in normalize_line_endings(): when *p == '\0' the NUL was copied into q and q was auto-incremented, the loop was broken out of, then a newline was appended followed by a NUL. So the function, in effect, was strcpy() but added two extra chars which was caught by obmalloc in debug mode, since there was only room for 1 additional newline. Get test working under regrtest (added test_main). Index: zipimport.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/zipimport.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** zipimport.c 3 Jan 2003 11:18:55 -0000 1.8 --- zipimport.c 17 Feb 2003 18:05:19 -0000 1.9 *************** *** 372,376 **** enum module_info mi; ! if (!PyArg_ParseTuple(args, "s:zipimporter.find_module", &fullname)) return NULL; --- 372,376 ---- enum module_info mi; ! if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", &fullname)) return NULL; *************** *** 948,952 **** } /* replace "\r\n?" by "\n" */ ! for (q = buf;;) { if (*p == '\r') { *q++ = '\n'; --- 948,952 ---- } /* replace "\r\n?" by "\n" */ ! for (q = buf; *p != '\0'; p++) { if (*p == '\r') { *q++ = '\n'; *************** *** 956,962 **** else *q++ = *p; - if (*p == '\0') - break; - p++; } *q++ = '\n'; /* add trailing \n */ --- 956,959 ---- From nnorwitz@users.sourceforge.net Mon Feb 17 18:17:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:17:08 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_posix.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv21363/Lib/test Added Files: test_posix.py Log Message: Added test_posix (hopefully it works on Windows). Remove PyArg_ParseTuple() for methods which take no args, use METH_NOARGS instead --- NEW FILE: test_posix.py --- "Test posix functions" from test_support import TestSkipped, TestFailed, TESTFN, run_suite try: import posix except ImportError: raise TestSkipped, "posix is not available" import time import os import sys import unittest import warnings warnings.filterwarnings('ignore', '.* potential security risk .*', RuntimeWarning) class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(TESTFN, 'w+') fp.close() def tearDown(self): os.unlink(TESTFN) def testNoArgFunctions(self): # test posix functions which take no arguments and have # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", "times", "getlogin", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] for name in NO_ARG_FUNCTIONS: posix_func = getattr(posix, name, None) if posix_func is not None: posix_func() try: posix_func(1) except TypeError: pass else: raise TestFailed, '%s should take no arguments' % name def test_statvfs(self): if hasattr(posix, 'statvfs'): posix.statvfs(os.curdir) def test_fstatvfs(self): if hasattr(posix, 'fstatvfs'): fp = open(TESTFN) try: posix.fstatvfs(fp.fileno()) finally: fp.close() def test_ftruncate(self): if hasattr(posix, 'ftruncate'): fp = open(TESTFN, 'w+') try: # we need to have some data to truncate fp.write('test') fp.flush() posix.ftruncate(fp.fileno(), 0) finally: fp.close() def test_dup(self): if hasattr(posix, 'dup'): fp = open(TESTFN) try: fd = posix.dup(fp.fileno()) os.close(fd) finally: fp.close() def test_dup2(self): if hasattr(posix, 'dup2'): fp1 = open(TESTFN) fp2 = open(TESTFN) try: posix.dup2(fp1.fileno(), fp2.fileno()) finally: fp1.close() fp2.close() def fdopen_helper(self, *args): fd = os.open(TESTFN, os.O_RDONLY) fp2 = posix.fdopen(fd, *args) fp2.close() def test_fdopen(self): if hasattr(posix, 'fdopen'): self.fdopen_helper() self.fdopen_helper('r') self.fdopen_helper('r', 100) def test_fstat(self): if hasattr(posix, 'fstat'): fp = open(TESTFN) try: posix.fstat(fp.fileno()) finally: fp.close() def test_stat(self): if hasattr(posix, 'stat'): posix.stat(TESTFN) def test_chdir(self): if hasattr(posix, 'chdir'): posix.chdir(os.curdir) try: posix.chdir(TESTFN) except OSError: pass else: raise TestFailed, \ 'should not be able to change directory to a file' def test_lsdir(self): if hasattr(posix, 'lsdir'): if TESTFN not in posix.lsdir(os.curdir): raise TestFailed, \ '%s should exist in current directory' % TESTFN def test_access(self): if hasattr(posix, 'access'): if not posix.access(TESTFN, os.R_OK): raise TestFailed, 'should have read access to: %s' % TESTFN def test_umask(self): if hasattr(posix, 'umask'): old_mask = posix.umask(0) posix.umask(old_mask) def test_strerror(self): if hasattr(posix, 'strerror'): posix.strerror(0) def test_pipe(self): if hasattr(posix, 'pipe'): reader, writer = posix.pipe() os.close(reader) os.close(writer) def test_tempnam(self): if hasattr(posix, 'tempnam'): posix.tempnam() posix.tempnam(os.curdir) posix.tempnam(os.curdir, 'blah') def test_tmpfile(self): if hasattr(posix, 'tmpfile'): fp = posix.tmpfile() fp.close() def test_utime(self): if hasattr(posix, 'utime'): now = time.time() posix.utime(TESTFN, None) posix.utime(TESTFN, (now, now)) def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(PosixTester)) run_suite(suite) if __name__ == '__main__': test_main() From nnorwitz@users.sourceforge.net Mon Feb 17 18:17:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:17:08 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.284,2.285 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv21363/Modules Modified Files: posixmodule.c Log Message: Added test_posix (hopefully it works on Windows). Remove PyArg_ParseTuple() for methods which take no args, use METH_NOARGS instead Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.284 retrieving revision 2.285 diff -C2 -d -r2.284 -r2.285 *** posixmodule.c 11 Feb 2003 23:05:39 -0000 2.284 --- posixmodule.c 17 Feb 2003 18:17:03 -0000 2.285 *************** *** 1314,1325 **** static PyObject * ! posix_ctermid(PyObject *self, PyObject *args) { char *ret; char buffer[L_ctermid]; - if (!PyArg_ParseTuple(args, ":ctermid")) - return NULL; - #ifdef USE_CTERMID_R ret = ctermid_r(buffer); --- 1314,1322 ---- static PyObject * ! posix_ctermid(PyObject *self, PyObject *noargs) { char *ret; char buffer[L_ctermid]; #ifdef USE_CTERMID_R ret = ctermid_r(buffer); *************** *** 1480,1484 **** res = lchown(path, (uid_t) uid, (gid_t) gid); Py_END_ALLOW_THREADS ! if (res < 0) return posix_error_with_allocated_filename(path); PyMem_Free(path); --- 1477,1481 ---- res = lchown(path, (uid_t) uid, (gid_t) gid); Py_END_ALLOW_THREADS ! if (res < 0) return posix_error_with_allocated_filename(path); PyMem_Free(path); *************** *** 1495,1504 **** static PyObject * ! posix_getcwd(PyObject *self, PyObject *args) { char buf[1026]; char *res; ! if (!PyArg_ParseTuple(args, ":getcwd")) ! return NULL; Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) --- 1492,1500 ---- static PyObject * ! posix_getcwd(PyObject *self, PyObject *noargs) { char buf[1026]; char *res; ! Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) *************** *** 1524,1533 **** static PyObject * ! posix_getcwdu(PyObject *self, PyObject *args) { char buf[1026]; char *res; - if (!PyArg_ParseTuple(args, ":getcwd")) - return NULL; #ifdef Py_WIN_WIDE_FILENAMES --- 1520,1527 ---- static PyObject * ! posix_getcwdu(PyObject *self, PyObject *noargs) { char buf[1026]; char *res; #ifdef Py_WIN_WIDE_FILENAMES *************** *** 2055,2064 **** static PyObject * ! posix_uname(PyObject *self, PyObject *args) { struct utsname u; int res; ! if (!PyArg_ParseTuple(args, ":uname")) ! return NULL; Py_BEGIN_ALLOW_THREADS res = uname(&u); --- 2049,2057 ---- static PyObject * ! posix_uname(PyObject *self, PyObject *noargs) { struct utsname u; int res; ! Py_BEGIN_ALLOW_THREADS res = uname(&u); *************** *** 2686,2697 **** static PyObject * ! posix_fork1(self, args) ! PyObject *self; ! PyObject *args; { ! int pid; ! if (!PyArg_ParseTuple(args, ":fork1")) ! return NULL; ! pid = fork1(); if (pid == -1) return posix_error(); --- 2679,2685 ---- static PyObject * ! posix_fork1(PyObject *self, PyObject *noargs) { ! int pid = fork1(); if (pid == -1) return posix_error(); *************** *** 2709,2718 **** static PyObject * ! posix_fork(PyObject *self, PyObject *args) { ! int pid; ! if (!PyArg_ParseTuple(args, ":fork")) ! return NULL; ! pid = fork(); if (pid == -1) return posix_error(); --- 2697,2703 ---- static PyObject * ! posix_fork(PyObject *self, PyObject *noargs) { ! int pid = fork(); if (pid == -1) return posix_error(); *************** *** 2742,2746 **** static PyObject * ! posix_openpty(PyObject *self, PyObject *args) { int master_fd, slave_fd; --- 2727,2731 ---- static PyObject * ! posix_openpty(PyObject *self, PyObject *noargs) { int master_fd, slave_fd; *************** *** 2755,2761 **** #endif - if (!PyArg_ParseTuple(args, ":openpty")) - return NULL; - #ifdef HAVE_OPENPTY if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) --- 2740,2743 ---- *************** *** 2813,2822 **** static PyObject * ! posix_forkpty(PyObject *self, PyObject *args) { int master_fd, pid; - if (!PyArg_ParseTuple(args, ":forkpty")) - return NULL; pid = forkpty(&master_fd, NULL, NULL, NULL); if (pid == -1) --- 2795,2802 ---- static PyObject * ! posix_forkpty(PyObject *self, PyObject *noargs) { int master_fd, pid; pid = forkpty(&master_fd, NULL, NULL, NULL); if (pid == -1) *************** *** 2834,2841 **** static PyObject * ! posix_getegid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getegid")) - return NULL; return PyInt_FromLong((long)getegid()); } --- 2814,2819 ---- static PyObject * ! posix_getegid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)getegid()); } *************** *** 2849,2856 **** static PyObject * ! posix_geteuid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":geteuid")) - return NULL; return PyInt_FromLong((long)geteuid()); } --- 2827,2832 ---- static PyObject * ! posix_geteuid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)geteuid()); } *************** *** 2864,2871 **** static PyObject * ! posix_getgid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getgid")) - return NULL; return PyInt_FromLong((long)getgid()); } --- 2840,2845 ---- static PyObject * ! posix_getgid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)getgid()); } *************** *** 2878,2885 **** static PyObject * ! posix_getpid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getpid")) - return NULL; return PyInt_FromLong((long)getpid()); } --- 2852,2857 ---- static PyObject * ! posix_getpid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)getpid()); } *************** *** 2892,2900 **** static PyObject * ! posix_getgroups(PyObject *self, PyObject *args) { PyObject *result = NULL; - if (PyArg_ParseTuple(args, ":getgroups")) { #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX --- 2864,2871 ---- static PyObject * ! posix_getgroups(PyObject *self, PyObject *noargs) { PyObject *result = NULL; #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX *************** *** 2912,2919 **** result = PyList_New(n); if (result != NULL) { - PyObject *o; int i; for (i = 0; i < n; ++i) { ! o = PyInt_FromLong((long)grouplist[i]); if (o == NULL) { Py_DECREF(result); --- 2883,2889 ---- result = PyList_New(n); if (result != NULL) { int i; for (i = 0; i < n; ++i) { ! PyObject *o = PyInt_FromLong((long)grouplist[i]); if (o == NULL) { Py_DECREF(result); *************** *** 2925,2929 **** } } ! } return result; } --- 2895,2899 ---- } } ! return result; } *************** *** 2955,2962 **** static PyObject * ! posix_getpgrp(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getpgrp")) - return NULL; #ifdef GETPGRP_HAVE_ARG return PyInt_FromLong((long)getpgrp(0)); --- 2925,2930 ---- static PyObject * ! posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG return PyInt_FromLong((long)getpgrp(0)); *************** *** 2974,2981 **** static PyObject * ! posix_setpgrp(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":setpgrp")) - return NULL; #ifdef SETPGRP_HAVE_ARG if (setpgrp(0, 0) < 0) --- 2942,2947 ---- static PyObject * ! posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG if (setpgrp(0, 0) < 0) *************** *** 2996,3003 **** static PyObject * ! posix_getppid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getppid")) - return NULL; return PyInt_FromLong((long)getppid()); } --- 2962,2967 ---- static PyObject * ! posix_getppid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)getppid()); } *************** *** 3011,3019 **** static PyObject * ! posix_getlogin(PyObject *self, PyObject *args) { ! PyObject *result = NULL; ! ! if (PyArg_ParseTuple(args, ":getlogin")) { char *name; int old_errno = errno; --- 2975,2981 ---- static PyObject * ! posix_getlogin(PyObject *self, PyObject *noargs) { ! PyObject *result = NULL; char *name; int old_errno = errno; *************** *** 3031,3035 **** result = PyString_FromString(name); errno = old_errno; ! } return result; } --- 2993,2997 ---- result = PyString_FromString(name); errno = old_errno; ! return result; } *************** *** 3042,3049 **** static PyObject * ! posix_getuid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getuid")) - return NULL; return PyInt_FromLong((long)getuid()); } --- 3004,3009 ---- static PyObject * ! posix_getuid(PyObject *self, PyObject *noargs) { return PyInt_FromLong((long)getuid()); } *************** *** 4902,4906 **** static PyObject * ! posix_wait(PyObject *self, PyObject *args) { int pid; --- 4862,4866 ---- static PyObject * ! posix_wait(PyObject *self, PyObject *noargs) { int pid; *************** *** 4912,4917 **** #define status_i status #endif ! if (!PyArg_ParseTuple(args, ":wait")) ! return NULL; status_i = 0; Py_BEGIN_ALLOW_THREADS --- 4872,4876 ---- #define status_i status #endif ! status_i = 0; Py_BEGIN_ALLOW_THREADS *************** *** 5001,5009 **** static PyObject * ! posix_times(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":times")) - return NULL; - /* Currently Only Uptime is Provided -- Others Later */ return Py_BuildValue("ddddd", --- 4960,4965 ---- static PyObject * ! posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ return Py_BuildValue("ddddd", *************** *** 5016,5025 **** #else /* not OS2 */ static PyObject * ! posix_times(PyObject *self, PyObject *args) { struct tms t; clock_t c; - if (!PyArg_ParseTuple(args, ":times")) - return NULL; errno = 0; c = times(&t); --- 4972,4979 ---- #else /* not OS2 */ static PyObject * ! posix_times(PyObject *self, PyObject *noargs) { struct tms t; clock_t c; errno = 0; c = times(&t); *************** *** 5040,5049 **** #define HAVE_TIMES /* so the method table will pick it up */ static PyObject * ! posix_times(PyObject *self, PyObject *args) { FILETIME create, exit, kernel, user; HANDLE hProc; - if (!PyArg_ParseTuple(args, ":times")) - return NULL; hProc = GetCurrentProcess(); GetProcessTimes(hProc, &create, &exit, &kernel, &user); --- 4994,5001 ---- #define HAVE_TIMES /* so the method table will pick it up */ static PyObject * ! posix_times(PyObject *self, PyObject *noargs) { FILETIME create, exit, kernel, user; HANDLE hProc; hProc = GetCurrentProcess(); GetProcessTimes(hProc, &create, &exit, &kernel, &user); *************** *** 5078,5085 **** static PyObject * ! posix_setsid(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":setsid")) - return NULL; if (setsid() < 0) return posix_error(); --- 5030,5035 ---- static PyObject * ! posix_setsid(PyObject *self, PyObject *noargs) { if (setsid() < 0) return posix_error(); *************** *** 5425,5429 **** static PyObject * ! posix_pipe(PyObject *self, PyObject *args) { #if defined(PYOS_OS2) --- 5375,5379 ---- static PyObject * ! posix_pipe(PyObject *self, PyObject *noargs) { #if defined(PYOS_OS2) *************** *** 5431,5437 **** APIRET rc; - if (!PyArg_ParseTuple(args, ":pipe")) - return NULL; - Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); --- 5381,5384 ---- *************** *** 5445,5450 **** int fds[2]; int res; - if (!PyArg_ParseTuple(args, ":pipe")) - return NULL; Py_BEGIN_ALLOW_THREADS #if defined(__VMS) --- 5392,5395 ---- *************** *** 5461,5466 **** int read_fd, write_fd; BOOL ok; - if (!PyArg_ParseTuple(args, ":pipe")) - return NULL; Py_BEGIN_ALLOW_THREADS ok = CreatePipe(&read, &write, NULL, 0); --- 5406,5409 ---- *************** *** 6105,6114 **** static PyObject * ! posix_tmpfile(PyObject *self, PyObject *args) { FILE *fp; - if (!PyArg_ParseTuple(args, ":tmpfile")) - return NULL; fp = tmpfile(); if (fp == NULL) --- 6048,6055 ---- static PyObject * ! posix_tmpfile(PyObject *self, PyObject *noargs) { FILE *fp; fp = tmpfile(); if (fp == NULL) *************** *** 6125,6136 **** static PyObject * ! posix_tmpnam(PyObject *self, PyObject *args) { char buffer[L_tmpnam]; char *name; - if (!PyArg_ParseTuple(args, ":tmpnam")) - return NULL; - if (PyErr_Warn(PyExc_RuntimeWarning, "tmpnam is a potential security risk to your program") < 0) --- 6066,6074 ---- static PyObject * ! posix_tmpnam(PyObject *self, PyObject *noargs) { char buffer[L_tmpnam]; char *name; if (PyErr_Warn(PyExc_RuntimeWarning, "tmpnam is a potential security risk to your program") < 0) *************** *** 7136,7143 **** static PyObject * ! posix_abort(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":abort")) - return NULL; abort(); /*NOTREACHED*/ --- 7074,7079 ---- static PyObject * ! posix_abort(PyObject *self, PyObject *noargs) { abort(); /*NOTREACHED*/ *************** *** 7187,7195 **** static PyObject * ! posix_getloadavg(PyObject *self, PyObject *args) { double loadavg[3]; - if (!PyArg_ParseTuple(args, ":getloadavg")) - return NULL; if (getloadavg(loadavg, 3)!=3) { PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); --- 7123,7129 ---- static PyObject * ! posix_getloadavg(PyObject *self, PyObject *noargs) { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); *************** *** 7218,7227 **** #endif #ifdef HAVE_CTERMID ! {"ctermid", posix_ctermid, METH_VARARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD ! {"getcwd", posix_getcwd, METH_VARARGS, posix_getcwd__doc__}, #ifdef Py_USING_UNICODE ! {"getcwdu", posix_getcwdu, METH_VARARGS, posix_getcwdu__doc__}, #endif #endif --- 7152,7161 ---- #endif #ifdef HAVE_CTERMID ! {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD ! {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, #ifdef Py_USING_UNICODE ! {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, #endif #endif *************** *** 7250,7254 **** {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME ! {"uname", posix_uname, METH_VARARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, --- 7184,7188 ---- {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME ! {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, *************** *** 7256,7260 **** {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES ! {"times", posix_times, METH_VARARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, --- 7190,7194 ---- {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES ! {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, *************** *** 7268,7306 **** #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 ! {"fork1", posix_fork1, METH_VARARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK ! {"fork", posix_fork, METH_VARARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) ! {"openpty", posix_openpty, METH_VARARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY ! {"forkpty", posix_forkpty, METH_VARARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID ! {"getegid", posix_getegid, METH_VARARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID ! {"geteuid", posix_geteuid, METH_VARARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID ! {"getgid", posix_getgid, METH_VARARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS ! {"getgroups", posix_getgroups, METH_VARARGS, posix_getgroups__doc__}, #endif ! {"getpid", posix_getpid, METH_VARARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP ! {"getpgrp", posix_getpgrp, METH_VARARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID ! {"getppid", posix_getppid, METH_VARARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID ! {"getuid", posix_getuid, METH_VARARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN ! {"getlogin", posix_getlogin, METH_VARARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL --- 7202,7240 ---- #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 ! {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK ! {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) ! {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY ! {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID ! {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID ! {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID ! {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS ! {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif ! {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP ! {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID ! {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID ! {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN ! {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL *************** *** 7353,7360 **** #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP ! {"setpgrp", posix_setpgrp, METH_VARARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT ! {"wait", posix_wait, METH_VARARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) --- 7287,7294 ---- #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP ! {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT ! {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) *************** *** 7362,7366 **** #endif /* HAVE_WAITPID */ #ifdef HAVE_SETSID ! {"setsid", posix_setsid, METH_VARARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID --- 7296,7300 ---- #endif /* HAVE_WAITPID */ #ifdef HAVE_SETSID ! {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID *************** *** 7384,7388 **** {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE ! {"pipe", posix_pipe, METH_VARARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO --- 7318,7322 ---- {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE ! {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO *************** *** 7451,7455 **** #endif #ifdef HAVE_TMPFILE ! {"tmpfile", posix_tmpfile, METH_VARARGS, posix_tmpfile__doc__}, #endif #ifdef HAVE_TEMPNAM --- 7385,7389 ---- #endif #ifdef HAVE_TMPFILE ! {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, #endif #ifdef HAVE_TEMPNAM *************** *** 7457,7461 **** #endif #ifdef HAVE_TMPNAM ! {"tmpnam", posix_tmpnam, METH_VARARGS, posix_tmpnam__doc__}, #endif #ifdef HAVE_CONFSTR --- 7391,7395 ---- #endif #ifdef HAVE_TMPNAM ! {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, #endif #ifdef HAVE_CONFSTR *************** *** 7471,7480 **** {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif ! {"abort", posix_abort, METH_VARARGS, posix_abort__doc__}, #ifdef MS_WINDOWS {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG ! {"getloadavg", posix_getloadavg, METH_VARARGS, posix_getloadavg__doc__}, #endif {NULL, NULL} /* Sentinel */ --- 7405,7414 ---- {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif ! {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG ! {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif {NULL, NULL} /* Sentinel */ From nnorwitz@users.sourceforge.net Mon Feb 17 18:18:05 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:18:05 -0800 Subject: [Python-checkins] python/dist/src/Python import.c,2.218,2.219 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv22629a/Python Modified Files: import.c Log Message: Remove PyArg_ParseTuple() for methods which take no args, use METH_NOARGS instead Index: import.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/import.c,v retrieving revision 2.218 retrieving revision 2.219 diff -C2 -d -r2.218 -r2.219 *** import.c 12 Feb 2003 23:02:19 -0000 2.218 --- import.c 17 Feb 2003 18:18:00 -0000 2.219 *************** *** 287,294 **** static PyObject * ! imp_lock_held(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":lock_held")) - return NULL; #ifdef WITH_THREAD return PyBool_FromLong(import_lock_thread != -1); --- 287,292 ---- static PyObject * ! imp_lock_held(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD return PyBool_FromLong(import_lock_thread != -1); *************** *** 299,306 **** static PyObject * ! imp_acquire_lock(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":acquire_lock")) - return NULL; #ifdef WITH_THREAD lock_import(); --- 297,302 ---- static PyObject * ! imp_acquire_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD lock_import(); *************** *** 311,318 **** static PyObject * ! imp_release_lock(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":release_lock")) - return NULL; #ifdef WITH_THREAD if (unlock_import() < 0) { --- 307,312 ---- static PyObject * ! imp_release_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD if (unlock_import() < 0) { *************** *** 2429,2438 **** static PyObject * ! imp_get_magic(PyObject *self, PyObject *args) { char buf[4]; - if (!PyArg_ParseTuple(args, ":get_magic")) - return NULL; buf[0] = (char) ((pyc_magic >> 0) & 0xff); buf[1] = (char) ((pyc_magic >> 8) & 0xff); --- 2423,2430 ---- static PyObject * ! imp_get_magic(PyObject *self, PyObject *noargs) { char buf[4]; buf[0] = (char) ((pyc_magic >> 0) & 0xff); buf[1] = (char) ((pyc_magic >> 8) & 0xff); *************** *** 2444,2454 **** static PyObject * ! imp_get_suffixes(PyObject *self, PyObject *args) { PyObject *list; struct filedescr *fdp; - if (!PyArg_ParseTuple(args, ":get_suffixes")) - return NULL; list = PyList_New(0); if (list == NULL) --- 2436,2444 ---- static PyObject * ! imp_get_suffixes(PyObject *self, PyObject *noargs) { PyObject *list; struct filedescr *fdp; list = PyList_New(0); if (list == NULL) *************** *** 2792,2803 **** static PyMethodDef imp_methods[] = { ! {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, ! {"get_magic", imp_get_magic, METH_VARARGS, doc_get_magic}, ! {"get_suffixes", imp_get_suffixes, METH_VARARGS, doc_get_suffixes}, ! {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, ! {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, ! {"lock_held", imp_lock_held, METH_VARARGS, doc_lock_held}, ! {"acquire_lock", imp_acquire_lock, METH_VARARGS, doc_acquire_lock}, ! {"release_lock", imp_release_lock, METH_VARARGS, doc_release_lock}, /* The rest are obsolete */ {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, --- 2782,2793 ---- static PyMethodDef imp_methods[] = { ! {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, ! {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, ! {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, ! {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, ! {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, ! {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, ! {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, ! {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, /* The rest are obsolete */ {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, From andymac@bullseye.apana.org.au Mon Feb 17 13:31:56 2003 From: andymac@bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 17 Feb 2003 23:31:56 +1000 (est) Subject: [Python-checkins] python/dist/src/Misc NEWS,1.662,1.663 In-Reply-To: Message-ID: On Mon, 17 Feb 2003 mwh@users.sourceforge.net wrote: > Modified Files: > NEWS > Log Message: > Reword section about moving variables to os.path to match intent (or > at least, what I thought the intent was). Ta muchly. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac@bullseye.apana.org.au | Snail: PO Box 370 andymac@pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From lemburg@users.sourceforge.net Mon Feb 17 18:31:59 2003 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:31:59 -0800 Subject: [Python-checkins] python/dist/src/Parser tokenizer.c,2.72,2.73 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv437/Parser Modified Files: tokenizer.c Log Message: Add URL for PEP to the source code encoding warning. Remove the usage of PyErr_WarnExplicit() since this could cause sensitive information from the source files to appear in e.g. log files. Index: tokenizer.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/tokenizer.c,v retrieving revision 2.72 retrieving revision 2.73 diff -C2 -d -r2.72 -r2.73 *** tokenizer.c 9 Feb 2003 20:38:48 -0000 2.72 --- tokenizer.c 17 Feb 2003 18:31:57 -0000 2.73 *************** *** 463,474 **** } if (badchar) { ! char buf[200]; ! sprintf(buf, "Non-ASCII character '\\x%.2x', " ! "but no declared encoding", badchar); /* Need to add 1 to the line number, since this line has not been counted, yet. */ ! PyErr_WarnExplicit(PyExc_DeprecationWarning, ! buf, tok->filename, tok->lineno + 1, ! NULL, NULL); tok->issued_encoding_warning = 1; } --- 463,480 ---- } if (badchar) { ! char buf[500]; /* Need to add 1 to the line number, since this line has not been counted, yet. */ ! sprintf(buf, ! "Non-ASCII character '\\x%.2x' " ! "in file %.200s on line %i, " ! "but no encoding declared; " ! "see http://www.python.org/peps/pep-0263.html for details", ! badchar, tok->filename, tok->lineno + 1); ! /* We don't use PyErr_WarnExplicit() here because ! printing the line in question to e.g. a log file ! could result in sensitive information being ! exposed. */ ! PyErr_Warn(PyExc_DeprecationWarning, buf); tok->issued_encoding_warning = 1; } From walter@livinglogic.de Mon Feb 17 18:37:55 2003 From: walter@livinglogic.de (=?ISO-8859-15?Q?Walter_D=F6rwald?=) Date: Mon, 17 Feb 2003 19:37:55 +0100 Subject: [Python-checkins] python/dist/src/Lib/test test_posix.py,NONE,1.1 In-Reply-To: References: Message-ID: <3E512C03.502@livinglogic.de> nnorwitz@users.sourceforge.net wrote: > Update of /cvsroot/python/python/dist/src/Lib/test > In directory sc8-pr-cvs1:/tmp/cvs-serv21363/Lib/test > > Added Files: > test_posix.py > Log Message: > Added test_posix (hopefully it works on Windows). > Remove PyArg_ParseTuple() for methods which take no args, > use METH_NOARGS instead > [...] > try: > posix_func(1) > except TypeError: > pass > else: > raise TestFailed, '%s should take no arguments' % name Why not write this as self.assertRaises(TypeError, posix_func, 1) ? The same could be done for test_chdir() > def test_lsdir(self): > if hasattr(posix, 'lsdir'): > if TESTFN not in posix.lsdir(os.curdir): > raise TestFailed, \ > '%s should exist in current directory' % TESTFN This could be self.assert_(TESTFN in posix.lsdir(os.curdir)) > def test_access(self): > if hasattr(posix, 'access'): > if not posix.access(TESTFN, os.R_OK): > raise TestFailed, 'should have read access to: %s' % TESTFN This could be self.assert_(posix.access(TESTFN, os.R_OK)) Bye, Walter Dörwald From neal@metaslash.com Mon Feb 17 18:48:39 2003 From: neal@metaslash.com (Neal Norwitz) Date: Mon, 17 Feb 2003 13:48:39 -0500 Subject: [Python-checkins] python/dist/src/Lib/test test_posix.py,NONE,1.1 In-Reply-To: <3E512C03.502@livinglogic.de> References: <3E512C03.502@livinglogic.de> Message-ID: <20030217184839.GQ31973@epoch.metaslash.com> On Mon, Feb 17, 2003 at 07:37:55PM +0100, Walter D=F6rwald wrote: >=20 > Why not write this as > self.assertRaises(TypeError, posix_func, 1) > ? The same could be done for test_chdir() Because I'm dumb and forgetful. :-) I thought I could make the changes you recommend, but forgot to go back and check after writing the tests. I will make the modification= s you suggest. Thanks! Neal From nnorwitz@users.sourceforge.net Mon Feb 17 18:59:59 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:59:59 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libstdtypes.tex,1.80.6.18,1.80.6.19 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv22615/Doc/lib Modified Files: Tag: release22-maint libstdtypes.tex Log Message: Fix SF bug #687655, String formatting conversions misleading Index: libstdtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libstdtypes.tex,v retrieving revision 1.80.6.18 retrieving revision 1.80.6.19 diff -C2 -d -r1.80.6.18 -r1.80.6.19 *** libstdtypes.tex 13 Jan 2003 04:33:36 -0000 1.80.6.18 --- libstdtypes.tex 17 Feb 2003 18:59:54 -0000 1.80.6.19 *************** *** 793,797 **** \lineii{\#}{The value conversion will use the ``alternate form'' (where defined below).} ! \lineii{0}{The conversion will be zero padded.} \lineii{-}{The converted value is left adjusted (overrides the \character{0} conversion if both are given).} --- 793,797 ---- \lineii{\#}{The value conversion will use the ``alternate form'' (where defined below).} ! \lineii{0}{The conversion will be zero padded for numeric values.} \lineii{-}{The converted value is left adjusted (overrides the \character{0} conversion if both are given).} From nnorwitz@users.sourceforge.net Mon Feb 17 18:57:09 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 10:57:09 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libstdtypes.tex,1.117,1.118 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv20939/Doc/lib Modified Files: libstdtypes.tex Log Message: Fix SF bug #687655, String formatting conversions misleading Index: libstdtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libstdtypes.tex,v retrieving revision 1.117 retrieving revision 1.118 diff -C2 -d -r1.117 -r1.118 *** libstdtypes.tex 13 Jan 2003 04:29:19 -0000 1.117 --- libstdtypes.tex 17 Feb 2003 18:57:06 -0000 1.118 *************** *** 801,805 **** \lineii{\#}{The value conversion will use the ``alternate form'' (where defined below).} ! \lineii{0}{The conversion will be zero padded.} \lineii{-}{The converted value is left adjusted (overrides the \character{0} conversion if both are given).} --- 801,805 ---- \lineii{\#}{The value conversion will use the ``alternate form'' (where defined below).} ! \lineii{0}{The conversion will be zero padded for numeric values.} \lineii{-}{The converted value is left adjusted (overrides the \character{0} conversion if both are given).} From tim_one@users.sourceforge.net Mon Feb 17 21:48:51 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 17 Feb 2003 13:48:51 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.126,1.127 test_posix.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15332/Lib/test Modified Files: regrtest.py test_posix.py Log Message: test_posix is an expected skip on Win32. Also fixed test_posix to import from test.test_support instead of directly from test_support. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.126 retrieving revision 1.127 diff -C2 -d -r1.126 -r1.127 *** regrtest.py 14 Feb 2003 19:29:22 -0000 1.126 --- regrtest.py 17 Feb 2003 21:48:47 -0000 1.127 *************** *** 573,576 **** --- 573,577 ---- test_ossaudiodev test_poll + test_posix test_pty test_pwd Index: test_posix.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_posix.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_posix.py 17 Feb 2003 18:17:05 -0000 1.1 --- test_posix.py 17 Feb 2003 21:48:48 -0000 1.2 *************** *** 1,5 **** "Test posix functions" ! from test_support import TestSkipped, TestFailed, TESTFN, run_suite try: --- 1,5 ---- "Test posix functions" ! from test.test_support import TestSkipped, TestFailed, TESTFN, run_suite try: From nnorwitz@users.sourceforge.net Mon Feb 17 22:39:01 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 14:39:01 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_imp.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv16036/Lib/test Modified Files: test_imp.py Log Message: Import test_support properly Index: test_imp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_imp.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_imp.py 17 Feb 2003 14:51:40 -0000 1.2 --- test_imp.py 17 Feb 2003 22:38:56 -0000 1.3 *************** *** 2,6 **** import imp import unittest ! from test_support import TestFailed, run_unittest class ImpLock(unittest.TestCase): --- 2,6 ---- import imp import unittest ! from test.test_support import TestFailed, run_unittest class ImpLock(unittest.TestCase): From nnorwitz@users.sourceforge.net Mon Feb 17 22:40:35 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 14:40:35 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_posix.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv16710/Lib/test Modified Files: test_posix.py Log Message: Make changes suggested by Walter to use self.assert*() methods. Index: test_posix.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_posix.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_posix.py 17 Feb 2003 21:48:48 -0000 1.2 --- test_posix.py 17 Feb 2003 22:40:31 -0000 1.3 *************** *** 38,51 **** if posix_func is not None: posix_func() ! try: ! posix_func(1) ! except TypeError: ! pass ! else: ! raise TestFailed, '%s should take no arguments' % name def test_statvfs(self): if hasattr(posix, 'statvfs'): ! posix.statvfs(os.curdir) def test_fstatvfs(self): --- 38,46 ---- if posix_func is not None: posix_func() ! self.assertRaises(TypeError, posix_func, 1) def test_statvfs(self): if hasattr(posix, 'statvfs'): ! self.assert_(posix.statvfs(os.curdir)) def test_fstatvfs(self): *************** *** 53,57 **** fp = open(TESTFN) try: ! posix.fstatvfs(fp.fileno()) finally: fp.close() --- 48,52 ---- fp = open(TESTFN) try: ! self.assert_(posix.fstatvfs(fp.fileno())) finally: fp.close() *************** *** 73,76 **** --- 68,72 ---- try: fd = posix.dup(fp.fileno()) + self.assert_(isinstance(fd, int)) os.close(fd) finally: *************** *** 102,106 **** fp = open(TESTFN) try: ! posix.fstat(fp.fileno()) finally: fp.close() --- 98,102 ---- fp = open(TESTFN) try: ! self.assert_(posix.fstat(fp.fileno())) finally: fp.close() *************** *** 108,143 **** def test_stat(self): if hasattr(posix, 'stat'): ! posix.stat(TESTFN) def test_chdir(self): if hasattr(posix, 'chdir'): posix.chdir(os.curdir) ! try: ! posix.chdir(TESTFN) ! except OSError: ! pass ! else: ! raise TestFailed, \ ! 'should not be able to change directory to a file' def test_lsdir(self): if hasattr(posix, 'lsdir'): ! if TESTFN not in posix.lsdir(os.curdir): ! raise TestFailed, \ ! '%s should exist in current directory' % TESTFN def test_access(self): if hasattr(posix, 'access'): ! if not posix.access(TESTFN, os.R_OK): ! raise TestFailed, 'should have read access to: %s' % TESTFN def test_umask(self): if hasattr(posix, 'umask'): old_mask = posix.umask(0) posix.umask(old_mask) def test_strerror(self): if hasattr(posix, 'strerror'): ! posix.strerror(0) def test_pipe(self): --- 104,131 ---- def test_stat(self): if hasattr(posix, 'stat'): ! self.assert_(posix.stat(TESTFN)) def test_chdir(self): if hasattr(posix, 'chdir'): posix.chdir(os.curdir) ! self.assertRaises(OSError, posix.chdir, TESTFN) def test_lsdir(self): if hasattr(posix, 'lsdir'): ! self.assert_(TESTFN in posix.lsdir(os.curdir)) def test_access(self): if hasattr(posix, 'access'): ! self.assert_(posix.access(TESTFN, os.R_OK)) def test_umask(self): if hasattr(posix, 'umask'): old_mask = posix.umask(0) + self.assert_(isinstance(old_mask, int)) posix.umask(old_mask) def test_strerror(self): if hasattr(posix, 'strerror'): ! self.assert_(posix.strerror(0)) def test_pipe(self): *************** *** 149,155 **** def test_tempnam(self): if hasattr(posix, 'tempnam'): ! posix.tempnam() ! posix.tempnam(os.curdir) ! posix.tempnam(os.curdir, 'blah') def test_tmpfile(self): --- 137,143 ---- def test_tempnam(self): if hasattr(posix, 'tempnam'): ! self.assert_(posix.tempnam()) ! self.assert_(posix.tempnam(os.curdir)) ! self.assert_(posix.tempnam(os.curdir, 'blah')) def test_tmpfile(self): From akuchling@users.sourceforge.net Tue Feb 18 00:43:26 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 17 Feb 2003 16:43:26 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.119,1.120 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv23111 Modified Files: whatsnew23.tex Log Message: [Bug #683416] Make PEP263 coverage a bit more explicit, and add it to the porting section Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.119 retrieving revision 1.120 diff -C2 -d -r1.119 -r1.120 *** whatsnew23.tex 11 Feb 2003 14:30:39 -0000 1.119 --- whatsnew23.tex 18 Feb 2003 00:43:24 -0000 1.120 *************** *** 286,296 **** Without such an encoding declaration, the default encoding used is ! ISO-8859-1, also known as Latin1. ! The encoding declaration only affects Unicode string literals; the ! text in the source code will be converted to Unicode using the ! specified encoding. Note that Python identifiers are still restricted ! to ASCII characters, so you can't have variable names that use ! characters outside of the usual alphanumerics. \begin{seealso} --- 286,299 ---- Without such an encoding declaration, the default encoding used is ! 7-bit ASCII. Executing or importing modules containing string ! literals with 8-bit characters and no encoding declaration will result ! in a \exception{DeprecationWarning} being signalled by Python 2.3; in ! 2.4 this will be a syntax error. ! The encoding declaration only affects Unicode string literals, which ! will be converted to Unicode using the specified encoding. Note that ! Python identifiers are still restricted to ASCII characters, so you ! can't have variable names that use characters outside of the usual ! alphanumerics. \begin{seealso} *************** *** 2079,2082 **** --- 2082,2090 ---- integer instead of raising an \exception{OverflowError} when a string or floating-point number is too large to fit into an integer. + + \item If you have Unicode strings that contain 8-bit characters, you + must declare the file's encoding (UTF-8, Latin-1, or whatever) by + adding a comment to the top of the file. See + section~\ref{section-encodings} for more information. \item Calling Tcl methods through \module{_tkinter} no longer From akuchling@users.sourceforge.net Tue Feb 18 00:48:28 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 17 Feb 2003 16:48:28 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.120,1.121 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv26325 Modified Files: whatsnew23.tex Log Message: [Bug #688261] Fix optparse example and output Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.120 retrieving revision 1.121 diff -C2 -d -r1.120 -r1.121 *** whatsnew23.tex 18 Feb 2003 00:43:24 -0000 1.120 --- whatsnew23.tex 18 Feb 2003 00:48:23 -0000 1.121 *************** *** 1736,1739 **** --- 1736,1740 ---- \begin{verbatim} + import sys from optparse import OptionParser *************** *** 1751,1755 **** \begin{verbatim} ! options, args = op.parse_args(sys.argv[1:]) print options print args --- 1752,1758 ---- \begin{verbatim} ! import optparse ! ! options, args = optparse.parse_args(sys.argv[1:]) print options print args *************** *** 1769,1773 **** $ ./python opt.py --input=data --length=4 ! ['arg1'] $ \end{verbatim} --- 1772,1776 ---- $ ./python opt.py --input=data --length=4 ! [] $ \end{verbatim} From akuchling@users.sourceforge.net Tue Feb 18 00:56:58 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 17 Feb 2003 16:56:58 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.121,1.122 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv32358 Modified Files: whatsnew23.tex Log Message: Add two acks; bump version number Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.121 retrieving revision 1.122 diff -C2 -d -r1.121 -r1.122 *** whatsnew23.tex 18 Feb 2003 00:48:23 -0000 1.121 --- whatsnew23.tex 18 Feb 2003 00:56:56 -0000 1.122 *************** *** 4,8 **** \title{What's New in Python 2.3} ! \release{0.08} \author{A.M.\ Kuchling} \authoraddress{\email{amk@amk.ca}} --- 4,8 ---- \title{What's New in Python 2.3} ! \release{0.09} \author{A.M.\ Kuchling} \authoraddress{\email{amk@amk.ca}} *************** *** 2145,2151 **** article: Simon Brunning, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael ! Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, ! Vinay Sajip, Neil Schemenauer, Jason Tishler, Just van~Rossum. \end{document} --- 2145,2151 ---- article: Simon Brunning, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael ! Hudson, Chris Lambert, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, ! Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler, Just van~Rossum. \end{document} From akuchling@users.sourceforge.net Tue Feb 18 01:28:54 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Mon, 17 Feb 2003 17:28:54 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command config.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv18130 Modified Files: config.py Log Message: [Patch #681504] Call customize_compiler in config command Index: config.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/config.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** config.py 3 Feb 2003 11:43:54 -0000 1.16 --- config.py 18 Feb 2003 01:28:51 -0000 1.17 *************** *** 18,21 **** --- 18,22 ---- from distutils.core import Command from distutils.errors import DistutilsExecError + from distutils.sysconfig import customize_compiler from distutils import log *************** *** 105,108 **** --- 106,110 ---- self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=1) + customize_compiler(self.compiler) if self.include_dirs: self.compiler.set_include_dirs(self.include_dirs) From nnorwitz@users.sourceforge.net Tue Feb 18 03:37:51 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 17 Feb 2003 19:37:51 -0800 Subject: [Python-checkins] python/dist/src/Modules zipimport.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv22604/Modules Modified Files: zipimport.c Log Message: Fix 64-bit problem, ParseTuple("i") needs C ints; ("l") needs C longs. Use "l" as that *probably* makes more sense (at least to me it does :-) And the test passes on the alpha. Index: zipimport.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/zipimport.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** zipimport.c 17 Feb 2003 18:05:19 -0000 1.9 --- zipimport.c 18 Feb 2003 03:37:49 -0000 1.10 *************** *** 797,801 **** long time, date, crc; ! if (!PyArg_ParseTuple(toc_entry, "siiiiiii", &datapath, &compress, &data_size, &file_size, &file_offset, &time, &date, &crc)) { --- 797,801 ---- long time, date, crc; ! if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, &data_size, &file_size, &file_offset, &time, &date, &crc)) { From jackjansen@users.sourceforge.net Tue Feb 18 10:24:37 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 02:24:37 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.145,1.146 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv25032 Modified Files: setup.py Log Message: Don't try to build dl on darwin. It doesn't build out of the box, and it wouldn't serve a useful purpose anyway. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.145 retrieving revision 1.146 diff -C2 -d -r1.145 -r1.146 *** setup.py 13 Feb 2003 16:11:27 -0000 1.145 --- setup.py 18 Feb 2003 10:24:34 -0000 1.146 *************** *** 735,739 **** # This requires sizeof(int) == sizeof(long) == sizeof(char*) dl_inc = find_file('dlfcn.h', [], inc_dirs) ! if (dl_inc is not None) and (platform not in ['atheos']): exts.append( Extension('dl', ['dlmodule.c']) ) --- 735,739 ---- # This requires sizeof(int) == sizeof(long) == sizeof(char*) dl_inc = find_file('dlfcn.h', [], inc_dirs) ! if (dl_inc is not None) and (platform not in ['atheos', 'darwin']): exts.append( Extension('dl', ['dlmodule.c']) ) From jackjansen@users.sourceforge.net Tue Feb 18 11:24:33 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 03:24:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv25951 Modified Files: bundlebuilder.py Log Message: Use "$@" to pass arguments to Python in stead of "${1}". This passes all arguments, and also does the right thing for the no argument case. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** bundlebuilder.py 17 Feb 2003 16:47:12 -0000 1.8 --- bundlebuilder.py 18 Feb 2003 11:24:31 -0000 1.9 *************** *** 264,268 **** PYTHONPATH="$resdir" export PYTHONPATH ! exec "${executable}" "${main}" "${1}" """ --- 264,268 ---- PYTHONPATH="$resdir" export PYTHONPATH ! exec "${executable}" "${main}" "$@" """ From jhylton@users.sourceforge.net Tue Feb 18 13:24:28 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Tue, 18 Feb 2003 05:24:28 -0800 Subject: [Python-checkins] python/dist/src/Python compile.txt,NONE,1.1.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv15472 Added Files: Tag: ast-branch compile.txt Log Message: Add a start at developer notes --- NEW FILE: compile.txt --- Developer Notes for Python Compiler =================================== Parsing ------- Abstract Syntax Tree (AST) -------------------------- The abstract syntax tree (AST) is a high-level description of the program structure with the syntactic details of the source text removed. It is specified using the Zephyr Abstract Syntax Definition Language (ASDL) [Wang97]_. The Python definition is found in the file ``Parser/Python.asdl``. The definition describes the structure of statements, expressions, and several specialized types, like list comprehensions and exception handlers. Most definitions in the AST correspond to a particular source construct, like an if statement or an attribute lookup. The definition is independent of its realization in any particular programming language. The AST has concrete representations in Python and C. There is also representation as a byte stream, so that AST objects can be passed between Python and C. (ASDL calls this format the pickle format, but I avoid that term to avoid confusion with Python pickles.) Each programming language has a generic representation for ASDL and a tool to generate a code for a specific abstract syntax. The following fragment of the Python abstract syntax demonstrates the approach. :: module Python { stmt = FunctionDef(identifier name, arguments args, stmt* body) | Return(expr? value) | Yield(expr value) attributes (int lineno) } The preceding example describes three different kinds of statements -- a function definition and return and yield statement. The function definition has three arguments -- its name, its argument list, and zero or more statements that make up its body. The return statement has an optional expression that is the return value. The yield statement requires an expression. The statement definitions above generate the following C structure type. :: typedef struct _stmt *stmt_ty; struct _stmt { enum { FunctionDef_kind=1, Return_kind=2, Yield_kind=3 } kind; union { struct { identifier name; arguments_ty args; asdl_seq *body; } FunctionDef; struct { expr_ty value; } Return; struct { expr_ty value; } Yield; } v; int lineno; } It also generates a series of constructor functions that generate a ``stmt_ty`` with the appropriate initialization. The ``kind`` field specifies which component of the union is initialized. The ``FunctionDef`` C function sets ``kind`` to ``FunctionDef_kind`` and initializes the ``name``, ``args``, and ``body`` fields. The parser generates a concrete syntax tree represented by a ``node *`` defined in ``Include/node.h``. The abstract syntax is generated from the concrete syntax in ``Python/ast.c`` using the function:: mod_ty PyAST_FromNode(const node *n); Code Generation and Basic Blocks -------------------------------- XXX Describe the structure of the code generator, the types involved, and the helper functions and macros. Code Objects ------------ XXX Describe Python code objects. .. [Wang97] Daniel C. Wang, Andrew W. Appel, Jeff L. Korn, and Chris S. Serra. `The Zephyr Abstract Syntax Description Language.`_ In Proceedings of the Conference on Domain-Specific Languages, pp. 213--227, 1997. .. _The Zephyr Abstract Syntax Description Language.: http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. From nnorwitz@users.sourceforge.net Tue Feb 18 14:20:11 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 06:20:11 -0800 Subject: [Python-checkins] python/dist/src/Lib/logging __init__.py,1.4,1.5 handlers.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/logging In directory sc8-pr-cvs1:/tmp/cvs-serv12493/Lib/logging Modified Files: __init__.py handlers.py Log Message: SF patch #687683, Patches to logging (updates from Vinay) Mostly rename WARN -> WARNING Other misc tweaks Update tests (not in original patch) Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/__init__.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** __init__.py 23 Jan 2003 18:29:29 -0000 1.4 --- __init__.py 18 Feb 2003 14:20:06 -0000 1.5 *************** *** 37,42 **** __author__ = "Vinay Sajip " __status__ = "alpha" ! __version__ = "0.4.7" ! __date__ = "27 August 2002" #--------------------------------------------------------------------------- --- 37,42 ---- __author__ = "Vinay Sajip " __status__ = "alpha" ! __version__ = "0.4.8" ! __date__ = "16 February 2003" #--------------------------------------------------------------------------- *************** *** 45,50 **** --- 45,58 ---- # + # _verinfo is used for when behaviour needs to be adjusted to the version + # of Python + # + + _verinfo = getattr(sys, "version_info", None) + + # #_srcfile is used when walking the stack to check when we've got the first # caller stack frame. + # if string.lower(__file__[-4:]) in ['.pyc', '.pyo']: _srcfile = __file__[:-4] + '.py' *************** *** 71,75 **** raiseExceptions = 1 - #--------------------------------------------------------------------------- # Level related stuff --- 79,82 ---- *************** *** 85,89 **** FATAL = CRITICAL ERROR = 40 ! WARN = 30 INFO = 20 DEBUG = 10 --- 92,97 ---- FATAL = CRITICAL ERROR = 40 ! WARNING = 30 ! WARN = WARNING INFO = 20 DEBUG = 10 *************** *** 93,97 **** CRITICAL : 'CRITICAL', ERROR : 'ERROR', ! WARN : 'WARN', INFO : 'INFO', DEBUG : 'DEBUG', --- 101,105 ---- CRITICAL : 'CRITICAL', ERROR : 'ERROR', ! WARNING : 'WARNING', INFO : 'INFO', DEBUG : 'DEBUG', *************** *** 99,103 **** 'CRITICAL' : CRITICAL, 'ERROR' : ERROR, ! 'WARN' : WARN, 'INFO' : INFO, 'DEBUG' : DEBUG, --- 107,112 ---- 'CRITICAL' : CRITICAL, 'ERROR' : ERROR, ! 'WARN' : WARNING, ! 'WARNING' : WARNING, 'INFO' : INFO, 'DEBUG' : DEBUG, *************** *** 109,113 **** Return the textual representation of logging level 'level'. ! If the level is one of the predefined levels (CRITICAL, ERROR, WARN, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have --- 118,122 ---- Return the textual representation of logging level 'level'. ! If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have *************** *** 205,208 **** --- 214,218 ---- else: self.thread = None + self.process = os.getpid() def __str__(self): *************** *** 217,221 **** arguments with the message. """ ! msg = str(self.msg) if self.args: msg = msg % self.args --- 227,237 ---- arguments with the message. """ ! if not hasattr(types, "UnicodeType"): #if no unicode support... ! msg = str(self.msg) ! else: ! try: ! msg = str(self.msg) ! except UnicodeError: ! msg = self.msg #Defer encoding till later if self.args: msg = msg % self.args *************** *** 244,250 **** %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, ! WARN, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", ! "WARN", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) --- 260,266 ---- %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, ! WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", ! "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) *************** *** 261,264 **** --- 277,281 ---- (typically at application startup time) %(thread)d Thread ID (if available) + %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted *************** *** 559,565 **** Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of ! the I/O thread lock. """ ! if self.filter(record): self.acquire() try: --- 576,584 ---- Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of ! the I/O thread lock. Returns whether the filter passed the record for ! emission. """ ! rv = self.filter(record) ! if rv: self.acquire() try: *************** *** 567,570 **** --- 586,590 ---- finally: self.release() + return rv def setFormatter(self, fmt): *************** *** 592,606 **** pass ! def handleError(self): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is ! encountered during an emit() call. By default it does nothing, ! because by default raiseExceptions is false, which means that exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. """ if raiseExceptions: --- 612,626 ---- pass ! def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is ! encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. + The record which was being processed is passed in to this method. """ if raiseExceptions: *************** *** 646,653 **** try: msg = self.format(record) ! self.stream.write("%s\n" % msg) self.flush() except: ! self.handleError() class FileHandler(StreamHandler): --- 666,679 ---- try: msg = self.format(record) ! if not hasattr(types, "UnicodeType"): #if no unicode support... ! self.stream.write("%s\n" % msg) ! else: ! try: ! self.stream.write("%s\n" % msg) ! except UnicodeError: ! self.stream.write("%s\n" % msg.encode("UTF-8")) self.flush() except: ! self.handleError(record) class FileHandler(StreamHandler): *************** *** 862,878 **** apply(self._log, (INFO, msg, args), kwargs) ! def warn(self, msg, *args, **kwargs): """ ! Log 'msg % args' with severity 'WARN'. To pass exception information, use the keyword argument exc_info with a true value, e.g. ! logger.warn("Houston, we have a %s", "bit of a problem", exc_info=1) """ ! if self.manager.disable >= WARN: return ! if self.isEnabledFor(WARN): ! apply(self._log, (WARN, msg, args), kwargs) def error(self, msg, *args, **kwargs): --- 888,906 ---- apply(self._log, (INFO, msg, args), kwargs) ! def warning(self, msg, *args, **kwargs): """ ! Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. ! logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) """ ! if self.manager.disable >= WARNING: return ! if self.isEnabledFor(WARNING): ! apply(self._log, (WARNING, msg, args), kwargs) ! ! warn = warning def error(self, msg, *args, **kwargs): *************** *** 983,987 **** """ if hdlr in self.handlers: ! hdlr.close() self.handlers.remove(hdlr) --- 1011,1015 ---- """ if hdlr in self.handlers: ! #hdlr.close() self.handlers.remove(hdlr) *************** *** 1048,1052 **** _loggerClass = Logger ! root = RootLogger(WARN) Logger.root = root Logger.manager = Manager(Logger.root) --- 1076,1080 ---- _loggerClass = Logger ! root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) *************** *** 1120,1130 **** apply(error, (msg,)+args, {'exc_info': 1}) ! def warn(msg, *args, **kwargs): """ ! Log a message with severity 'WARN' on the root logger. """ if len(root.handlers) == 0: basicConfig() ! apply(root.warn, (msg,)+args, kwargs) def info(msg, *args, **kwargs): --- 1148,1160 ---- apply(error, (msg,)+args, {'exc_info': 1}) ! def warning(msg, *args, **kwargs): """ ! Log a message with severity 'WARNING' on the root logger. """ if len(root.handlers) == 0: basicConfig() ! apply(root.warning, (msg,)+args, kwargs) ! ! warn = warning def info(msg, *args, **kwargs): Index: handlers.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/handlers.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** handlers.py 26 Jan 2003 16:15:24 -0000 1.4 --- handlers.py 18 Feb 2003 14:20:07 -0000 1.5 *************** *** 101,105 **** if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) ! #print msg if self.stream.tell() + len(msg) >= self.maxBytes: self.doRollover() --- 101,105 ---- if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) ! self.stream.seek(0, 2) #due to non-posix-compliant Windows feature if self.stream.tell() + len(msg) >= self.maxBytes: self.doRollover() *************** *** 146,151 **** network is busy. """ ! v = sys.version_info ! if v[0] >= 2 and v[1] >= 2: self.sock.sendall(s) else: --- 146,151 ---- network is busy. """ ! v = logging._verinfo ! if v and (v[0] >= 2) and (v[1] >= 2): self.sock.sendall(s) else: *************** *** 168,172 **** return slen + s ! def handleError(self): """ Handle an error during logging. --- 168,172 ---- return slen + s ! def handleError(self, record): """ Handle an error during logging. *************** *** 180,184 **** self.sock = None #try to reconnect next time else: ! logging.Handler.handleError(self) def emit(self, record): --- 180,184 ---- self.sock = None #try to reconnect next time else: ! logging.Handler.handleError(self, record) def emit(self, record): *************** *** 197,201 **** self.send(s) except: ! self.handleError() def close(self): --- 197,201 ---- self.send(s) except: ! self.handleError(record) def close(self): *************** *** 356,360 **** self.socket.close() self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) ! self.socket.connect(address) self.unixsocket = 1 else: --- 356,360 ---- self.socket.close() self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) ! self.socket.connect(address) self.unixsocket = 1 else: *************** *** 412,416 **** self.socket.sendto(msg, self.address) except: ! self.handleError() class SMTPHandler(logging.Handler): --- 412,416 ---- self.socket.sendto(msg, self.address) except: ! self.handleError(record) class SMTPHandler(logging.Handler): *************** *** 435,438 **** --- 435,440 ---- self.mailport = None self.fromaddr = fromaddr + if type(toaddrs) == types.StringType: + toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject *************** *** 468,472 **** smtp.quit() except: ! self.handleError() class NTEventLogHandler(logging.Handler): --- 470,474 ---- smtp.quit() except: ! self.handleError(record) class NTEventLogHandler(logging.Handler): *************** *** 497,501 **** logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, ! logging.WARN : win32evtlog.EVENTLOG_WARNING_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, --- 499,503 ---- logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, ! logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, *************** *** 532,536 **** a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, ! WARN, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute. --- 534,538 ---- a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, ! WARNING, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute. *************** *** 553,557 **** self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except: ! self.handleError() def close(self): --- 555,559 ---- self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except: ! self.handleError(record) def close(self): *************** *** 611,615 **** h.getreply() #can't do anything with the result except: ! self.handleError() class BufferingHandler(logging.Handler): --- 613,617 ---- h.getreply() #can't do anything with the result except: ! self.handleError(record) class BufferingHandler(logging.Handler): From nnorwitz@users.sourceforge.net Tue Feb 18 14:20:36 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 06:20:36 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_logging.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12493/Lib/test Modified Files: test_logging.py Log Message: SF patch #687683, Patches to logging (updates from Vinay) Mostly rename WARN -> WARNING Other misc tweaks Update tests (not in original patch) Index: test_logging.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_logging.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_logging.py 21 Jan 2003 21:05:20 -0000 1.4 --- test_logging.py 18 Feb 2003 14:20:02 -0000 1.5 *************** *** 343,348 **** logger = logging.getLogger("") sh = logger.handlers[0] logger.removeHandler(sh) ! mh = logging.handlers.MemoryHandler(10,logging.WARN, sh) logger.setLevel(logging.DEBUG) logger.addHandler(mh) --- 343,349 ---- logger = logging.getLogger("") sh = logger.handlers[0] + sh.close() logger.removeHandler(sh) ! mh = logging.handlers.MemoryHandler(10,logging.WARNING, sh) logger.setLevel(logging.DEBUG) logger.addHandler(mh) *************** *** 351,355 **** message("-- logging at INFO, nothing should be seen yet --") logger.info("Info message") ! message("-- logging at WARN, 3 messages should be seen --") logger.warn("Warn message") for i in xrange(102): --- 352,356 ---- message("-- logging at INFO, nothing should be seen yet --") logger.info("Info message") ! message("-- logging at WARNING, 3 messages should be seen --") logger.warn("Warn message") for i in xrange(102): *************** *** 437,440 **** --- 438,442 ---- rootLogger.addHandler(hdlr) test0() + hdlr.close() rootLogger.removeHandler(hdlr) From nnorwitz@users.sourceforge.net Tue Feb 18 14:20:39 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 06:20:39 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_logging,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv12493/Lib/test/output Modified Files: test_logging Log Message: SF patch #687683, Patches to logging (updates from Vinay) Mostly rename WARN -> WARNING Other misc tweaks Update tests (not in original patch) Index: test_logging =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/output/test_logging,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_logging 21 Jan 2003 21:05:22 -0000 1.2 --- test_logging 18 Feb 2003 14:20:04 -0000 1.3 *************** *** 5,13 **** CRITICAL:INF:Message 2 ERROR:INF:Message 3 ! WARN:INF:Message 4 INFO:INF:Message 5 CRITICAL:INF.UNDEF:Message 6 ERROR:INF.UNDEF:Message 7 ! WARN:INF.UNDEF:Message 8 INFO:INF.UNDEF:Message 9 CRITICAL:INF.ERR:Message 10 --- 5,13 ---- CRITICAL:INF:Message 2 ERROR:INF:Message 3 ! WARNING:INF:Message 4 INFO:INF:Message 5 CRITICAL:INF.UNDEF:Message 6 ERROR:INF.UNDEF:Message 7 ! WARNING:INF.UNDEF:Message 8 INFO:INF.UNDEF:Message 9 CRITICAL:INF.ERR:Message 10 *************** *** 17,26 **** CRITICAL:DEB:Message 14 ERROR:DEB:Message 15 ! WARN:DEB:Message 16 INFO:DEB:Message 17 DEBUG:DEB:Message 18 CRITICAL:UNDEF:Message 19 ERROR:UNDEF:Message 20 ! WARN:UNDEF:Message 21 INFO:UNDEF:Message 22 CRITICAL:INF.BADPARENT.UNDEF:Message 23 --- 17,26 ---- CRITICAL:DEB:Message 14 ERROR:DEB:Message 15 ! WARNING:DEB:Message 16 INFO:DEB:Message 17 DEBUG:DEB:Message 18 CRITICAL:UNDEF:Message 19 ERROR:UNDEF:Message 20 ! WARNING:UNDEF:Message 21 INFO:UNDEF:Message 22 CRITICAL:INF.BADPARENT.UNDEF:Message 23 *************** *** 260,267 **** -- logging at DEBUG, nothing should be seen yet -- -- logging at INFO, nothing should be seen yet -- ! -- logging at WARN, 3 messages should be seen -- DEBUG:root:Debug message INFO:root:Info message ! WARN:root:Warn message -- logging 0 at INFO, messages should be seen every 10 events -- -- logging 1 at INFO, messages should be seen every 10 events -- --- 260,267 ---- -- logging at DEBUG, nothing should be seen yet -- -- logging at INFO, nothing should be seen yet -- ! -- logging at WARNING, 3 messages should be seen -- DEBUG:root:Debug message INFO:root:Info message ! WARNING:root:Warn message -- logging 0 at INFO, messages should be seen every 10 events -- -- logging 1 at INFO, messages should be seen every 10 events -- *************** *** 491,499 **** INF -> CRITICAL: Message 2 (via logrecv.tcp.INF) INF -> ERROR: Message 3 (via logrecv.tcp.INF) ! INF -> WARN: Message 4 (via logrecv.tcp.INF) INF -> INFO: Message 5 (via logrecv.tcp.INF) INF.UNDEF -> CRITICAL: Message 6 (via logrecv.tcp.INF.UNDEF) INF.UNDEF -> ERROR: Message 7 (via logrecv.tcp.INF.UNDEF) ! INF.UNDEF -> WARN: Message 8 (via logrecv.tcp.INF.UNDEF) INF.UNDEF -> INFO: Message 9 (via logrecv.tcp.INF.UNDEF) INF.ERR -> CRITICAL: Message 10 (via logrecv.tcp.INF.ERR) --- 491,499 ---- INF -> CRITICAL: Message 2 (via logrecv.tcp.INF) INF -> ERROR: Message 3 (via logrecv.tcp.INF) ! INF -> WARNING: Message 4 (via logrecv.tcp.INF) INF -> INFO: Message 5 (via logrecv.tcp.INF) INF.UNDEF -> CRITICAL: Message 6 (via logrecv.tcp.INF.UNDEF) INF.UNDEF -> ERROR: Message 7 (via logrecv.tcp.INF.UNDEF) ! INF.UNDEF -> WARNING: Message 8 (via logrecv.tcp.INF.UNDEF) INF.UNDEF -> INFO: Message 9 (via logrecv.tcp.INF.UNDEF) INF.ERR -> CRITICAL: Message 10 (via logrecv.tcp.INF.ERR) *************** *** 503,512 **** DEB -> CRITICAL: Message 14 (via logrecv.tcp.DEB) DEB -> ERROR: Message 15 (via logrecv.tcp.DEB) ! DEB -> WARN: Message 16 (via logrecv.tcp.DEB) DEB -> INFO: Message 17 (via logrecv.tcp.DEB) DEB -> DEBUG: Message 18 (via logrecv.tcp.DEB) UNDEF -> CRITICAL: Message 19 (via logrecv.tcp.UNDEF) UNDEF -> ERROR: Message 20 (via logrecv.tcp.UNDEF) ! UNDEF -> WARN: Message 21 (via logrecv.tcp.UNDEF) UNDEF -> INFO: Message 22 (via logrecv.tcp.UNDEF) INF.BADPARENT.UNDEF -> CRITICAL: Message 23 (via logrecv.tcp.INF.BADPARENT.UNDEF) --- 503,512 ---- DEB -> CRITICAL: Message 14 (via logrecv.tcp.DEB) DEB -> ERROR: Message 15 (via logrecv.tcp.DEB) ! DEB -> WARNING: Message 16 (via logrecv.tcp.DEB) DEB -> INFO: Message 17 (via logrecv.tcp.DEB) DEB -> DEBUG: Message 18 (via logrecv.tcp.DEB) UNDEF -> CRITICAL: Message 19 (via logrecv.tcp.UNDEF) UNDEF -> ERROR: Message 20 (via logrecv.tcp.UNDEF) ! UNDEF -> WARNING: Message 21 (via logrecv.tcp.UNDEF) UNDEF -> INFO: Message 22 (via logrecv.tcp.UNDEF) INF.BADPARENT.UNDEF -> CRITICAL: Message 23 (via logrecv.tcp.INF.BADPARENT.UNDEF) From nnorwitz@users.sourceforge.net Tue Feb 18 14:20:39 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 06:20:39 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib liblogging.tex,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv12493/Doc/lib Modified Files: liblogging.tex Log Message: SF patch #687683, Patches to logging (updates from Vinay) Mostly rename WARN -> WARNING Other misc tweaks Update tests (not in original patch) Index: liblogging.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/liblogging.tex,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** liblogging.tex 28 Jan 2003 22:09:16 -0000 1.7 --- liblogging.tex 18 Feb 2003 14:20:05 -0000 1.8 *************** *** 251,256 **** Sets the threshold for this logger to \var{lvl}. Logging messages which are less severe than \var{lvl} will be ignored. When a logger is ! created, the level is set to \constant{ALL} (which causes all messages ! to be processed). \end{methoddesc} --- 251,257 ---- Sets the threshold for this logger to \var{lvl}. Logging messages which are less severe than \var{lvl} will be ignored. When a logger is ! created, the level is set to \constant{NOTSET} (which causes all messages ! to be processed in the root logger, or delegation to the parent in non-root ! loggers). \end{methoddesc} *************** *** 264,270 **** \begin{methoddesc}{getEffectiveLevel}{} Indicates the effective level for this logger. If a value other than ! \constant{ALL} has been set using \method{setLevel()}, it is returned. Otherwise, the hierarchy is traversed towards the root until a value ! other than \constant{ALL} is found, and that value is returned. \end{methoddesc} --- 265,271 ---- \begin{methoddesc}{getEffectiveLevel}{} Indicates the effective level for this logger. If a value other than ! \constant{NOTSET} has been set using \method{setLevel()}, it is returned. Otherwise, the hierarchy is traversed towards the root until a value ! other than \constant{NOTSET} is found,and that value is returned. \end{methoddesc} *************** *** 356,360 **** method in subclasses needs to call \method{Handler.__init__()}. ! \begin{methoddesc}{__init__}{level=\constant{ALL}} Initializes the \class{Handler} instance by setting its level, setting the list of filters to the empty list and creating a lock (using --- 357,361 ---- method in subclasses needs to call \method{Handler.__init__()}. ! \begin{methoddesc}{__init__}{level=\constant{NOTSET}} Initializes the \class{Handler} instance by setting its level, setting the list of filters to the empty list and creating a lock (using *************** *** 378,382 **** Sets the threshold for this handler to \var{lvl}. Logging messages which are less severe than \var{lvl} will be ignored. When a handler is created, the ! level is set to \constant{ALL} (which causes all messages to be processed). \end{methoddesc} --- 379,383 ---- Sets the threshold for this handler to \var{lvl}. Logging messages which are less severe than \var{lvl} will be ignored. When a handler is created, the ! level is set to \constant{NOTSET} (which causes all messages to be processed). \end{methoddesc} *************** *** 488,492 **** \begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes, ! backupCount}} Returns a new instance of the \class{RotatingFileHandler} class. The specified file is opened and used as the stream for logging. If --- 489,493 ---- \begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes, ! backupCount}} Returns a new instance of the \class{RotatingFileHandler} class. The specified file is opened and used as the stream for logging. If *************** *** 737,741 **** \begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel ! \optional{, target}}} Returns a new instance of the \class{MemoryHandler} class. The instance is initialized with a buffer size of \var{capacity}. If --- 738,742 ---- \begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel ! \optional{, target}}} Returns a new instance of the \class{MemoryHandler} class. The instance is initialized with a buffer size of \var{capacity}. If *************** *** 814,821 **** (typically at application startup time) \%(thread)d Thread ID (if available) \%(message)s The result of msg \% args, computed just as the record is emitted - \begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}} Returns a new instance of the \class{Formatter} class. The --- 815,822 ---- (typically at application startup time) \%(thread)d Thread ID (if available) + \%(process)d Process ID (if available) \%(message)s The result of msg \% args, computed just as the record is emitted \begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}} Returns a new instance of the \class{Formatter} class. The *************** *** 890,894 **** \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, ! exc_info} Returns an instance of \class{LogRecord} initialized with interesting information. The \var{name} is the logger name; \var{lvl} is the --- 891,895 ---- \begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, ! exc_info} Returns an instance of \class{LogRecord} initialized with interesting information. The \var{name} is the logger name; \var{lvl} is the From jhylton@users.sourceforge.net Tue Feb 18 15:06:22 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Tue, 18 Feb 2003 07:06:22 -0800 Subject: [Python-checkins] python/dist/src/Lib trace.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv28052 Added Files: trace.py Log Message: Copy the trace module here from Tools/scripts. There are some problems with this module, but the tool works for simple tasks and no one else has volunteered a better code coverage tool. Should cleanup and document before the beta release. --- NEW FILE: trace.py --- #!/usr/bin/env python # portions copyright 2001, Autonomous Zones Industries, Inc., all rights... # err... reserved and offered to the public under the terms of the # Python 2.2 license. # Author: Zooko O'Whielacronx # http://zooko.com/ # mailto:zooko@zooko.com # # Copyright 2000, Mojam Media, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1999, Bioreason, Inc., all rights reserved. # Author: Andrew Dalke # # Copyright 1995-1997, Automatrix, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. # # # Permission to use, copy, modify, and distribute this Python software and # its associated documentation for any purpose without fee is hereby # granted, provided that the above copyright notice appears in all copies, # and that both that copyright notice and this permission notice appear in # supporting documentation, and that the name of neither Automatrix, # Bioreason or Mojam Media be used in advertising or publicity pertaining to # distribution of the software without specific, written prior permission. # """program/module to trace Python program or function execution Sample use, command line: trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs trace.py -t --ignore-dir '$prefix' spam.py eggs Sample use, programmatically # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) # run the new command using the given trace trace.run(coverage.globaltrace, 'main()') # make a report, telling it where you want output r = trace.results() r.write_results(show_missing=1) """ import sys, os, tempfile, types, copy, operator, inspect, exceptions, marshal try: import cPickle pickle = cPickle except ImportError: import pickle # DEBUG_MODE=1 # make this true to get printouts which help you understand what's going on def usage(outfile): outfile.write("""Usage: %s [OPTIONS] [ARGS] Meta-options: --help Display this help then exit. --version Output version information then exit. Otherwise, exactly one of the following three options must be given: -t, --trace Print each line to sys.stdout before it is executed. -c, --count Count the number of times each line is executed and write the counts to .cover for each module executed, in the module's directory. See also `--coverdir', `--file', `--no-report' below. -r, --report Generate a report from a counts file; do not execute any code. `--file' must specify the results file to read, which must have been created in a previous run with `--count --file=FILE'. Modifiers: -f, --file= File to accumulate counts over several runs. -R, --no-report Do not generate the coverage report files. Useful if you want to accumulate over several runs. -C, --coverdir= Directory where the report files. The coverage report for . is written to file //.cover. -m, --missing Annotate executable lines that were not executed with '>>>>>> '. -s, --summary Write a brief summary on stdout for each file. (Can only be used with --count or --report.) Filters, may be repeated multiple times: --ignore-module= Ignore the given module and its submodules (if it is a package). --ignore-dir= Ignore files in the given directory (multiple directories can be joined by os.pathsep). """ % sys.argv[0]) class Ignore: def __init__(self, modules = None, dirs = None): self._mods = modules or [] self._dirs = dirs or [] self._dirs = map(os.path.normpath, self._dirs) self._ignore = { '': 1 } def names(self, filename, modulename): if self._ignore.has_key(modulename): return self._ignore[modulename] # haven't seen this one before, so see if the module name is # on the ignore list. Need to take some care since ignoring # "cmp" musn't mean ignoring "cmpcache" but ignoring # "Spam" must also mean ignoring "Spam.Eggs". for mod in self._mods: if mod == modulename: # Identical names, so ignore self._ignore[modulename] = 1 return 1 # check if the module is a proper submodule of something on # the ignore list n = len(mod) # (will not overflow since if the first n characters are the # same and the name has not already occured, then the size # of "name" is greater than that of "mod") if mod == modulename[:n] and modulename[n] == '.': self._ignore[modulename] = 1 return 1 # Now check that __file__ isn't in one of the directories if filename is None: # must be a built-in, so we must ignore self._ignore[modulename] = 1 return 1 # Ignore a file when it contains one of the ignorable paths for d in self._dirs: # The '+ os.sep' is to ensure that d is a parent directory, # as compared to cases like: # d = "/usr/local" # filename = "/usr/local.py" # or # d = "/usr/local.py" # filename = "/usr/local.py" if filename.startswith(d + os.sep): self._ignore[modulename] = 1 return 1 # Tried the different ways, so we don't ignore this module self._ignore[modulename] = 0 return 0 class CoverageResults: def __init__(self, counts=None, calledfuncs=None, infile=None, outfile=None): self.counts = counts if self.counts is None: self.counts = {} self.counter = self.counts.copy() # map (filename, lineno) to count self.calledfuncs = calledfuncs if self.calledfuncs is None: self.calledfuncs = {} self.calledfuncs = self.calledfuncs.copy() self.infile = infile self.outfile = outfile if self.infile: # try and merge existing counts file try: thingie = pickle.load(open(self.infile, 'r')) if type(thingie) is types.DictType: # backwards compatibility for old trace.py after # Zooko touched it but before calledfuncs --Zooko # 2001-10-24 self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: counts, calledfuncs = thingie self.update(self.__class__(counts, calledfuncs)) except (IOError, EOFError): pass except pickle.UnpicklingError: # backwards compatibility for old trace.py before # Zooko touched it --Zooko 2001-10-24 self.update(self.__class__(marshal.load(open(self.infile)))) def update(self, other): """Merge in the data from another CoverageResults""" counts = self.counts calledfuncs = self.calledfuncs other_counts = other.counts other_calledfuncs = other.calledfuncs for key in other_counts.keys(): if key != 'calledfuncs': # backwards compatibility for abortive attempt to # stuff calledfuncs into self.counts, by Zooko # --Zooko 2001-10-24 counts[key] = counts.get(key, 0) + other_counts[key] for key in other_calledfuncs.keys(): calledfuncs[key] = 1 def write_results(self, show_missing = 1, summary = 0, coverdir = None): """ @param coverdir """ for filename, modulename, funcname in self.calledfuncs.keys(): print ("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname)) import re # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for thingie in self.counts.keys(): if thingie != "calledfuncs": # backwards compatibility for abortive attempt to # stuff calledfuncs into self.counts, by Zooko --Zooko # 2001-10-24 filename, lineno = thingie lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] # there are many places where this is insufficient, like a blank # line embedded in a multiline string. blank = re.compile(r'^\s*(#.*)?$') # accumulate summary info, if needed sums = {} # generate file paths for the coverage files we are going to write... fnlist = [] tfdir = tempfile.gettempdir() for key in per_file.keys(): filename = key # skip some "files" we don't care about... if filename == "": continue # are these caused by code compiled using exec or something? if filename.startswith(tfdir): continue modulename = inspect.getmodulename(filename) if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if coverdir: thiscoverdir = coverdir else: thiscoverdir = os.path.dirname(os.path.abspath(filename)) # the code from here to "<<<" is the contents of the `fileutil.make_dirs()' function in the Mojo Nation project. --Zooko 2001-10-14 # http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/mojonation/evil/common/fileutil.py?rev=HEAD&content-type=text/vnd.viewcvs-markup tx = None try: os.makedirs(thiscoverdir) except OSError, x: tx = x if not os.path.isdir(thiscoverdir): if tx: raise tx raise exceptions.IOError, "unknown error prevented creation of directory: %s" % thiscoverdir # careful not to construct an IOError with a 2-tuple, as that has a special meaning... # <<< # build list file name by appending a ".cover" to the module name # and sticking it into the specified directory if "." in modulename: # A module in a package finalname = modulename.split(".")[-1] listfilename = os.path.join(thiscoverdir, finalname + ".cover") else: listfilename = os.path.join(thiscoverdir, modulename + ".cover") # Get the original lines from the .py file try: lines = open(filename, 'r').readlines() except IOError, err: sys.stderr.write("trace: Could not open %s for reading because: %s - skipping\n" % (`filename`, err)) continue try: outfile = open(listfilename, 'w') except IOError, err: sys.stderr.write( '%s: Could not open %s for writing because: %s" \ "- skipping\n' % ("trace", `listfilename`, err)) continue # If desired, get a list of the line numbers which represent # executable content (returned as a dict for better lookup speed) if show_missing: executable_linenos = find_executable_linenos(filename) else: executable_linenos = {} n_lines = 0 n_hits = 0 lines_hit = per_file[key] for i in range(len(lines)): line = lines[i] # do the blank/comment match to try to mark more lines # (help the reader find stuff that hasn't been covered) if lines_hit.has_key(i+1): # count precedes the lines that we captured outfile.write('%5d: ' % lines_hit[i+1]) n_hits = n_hits + 1 n_lines = n_lines + 1 elif blank.match(line): # blank lines and comments are preceded by dots outfile.write(' . ') else: # lines preceded by no marks weren't hit # Highlight them if so indicated, unless the line contains # '#pragma: NO COVER' (it is possible to embed this into # the text as a non-comment; no easy fix) if executable_linenos.has_key(i+1) and \ lines[i].find(' '.join(['#pragma', 'NO COVER'])) == -1: outfile.write('>>>>>> ') else: outfile.write(' '*7) n_lines = n_lines + 1 outfile.write(lines[i].expandtabs(8)) outfile.close() if summary and n_lines: percent = int(100 * n_hits / n_lines) sums[modulename] = n_lines, percent, modulename, filename if summary and sums: mods = sums.keys() mods.sort() print "lines cov% module (path)" for m in mods: n_lines, percent, modulename, filename = sums[m] print "%5d %3d%% %s (%s)" % sums[m] if self.outfile: # try and store counts and module info into self.outfile try: pickle.dump((self.counts, self.calledfuncs), open(self.outfile, 'w'), 1) except IOError, err: sys.stderr.write("cannot save counts files because %s" % err) def _find_LINENO_from_code(code): """return the numbers of the lines containing the source code that was compiled into code""" linenos = {} line_increments = [ord(c) for c in code.co_lnotab[1::2]] table_length = len(line_increments) lineno = code.co_firstlineno for li in line_increments: linenos[lineno] = 1 lineno += li linenos[lineno] = 1 return linenos def _find_LINENO(code): """return all of the lineno information from a code object""" import types # get all of the lineno information from the code of this scope level linenos = _find_LINENO_from_code(code) # and check the constants for references to other code objects for c in code.co_consts: if type(c) == types.CodeType: # find another code object, so recurse into it linenos.update(_find_LINENO(c)) return linenos def find_executable_linenos(filename): """return a dict of the line numbers from executable statements in a file """ import parser assert filename.endswith('.py') prog = open(filename).read() ast = parser.suite(prog) code = parser.compileast(ast, filename) return _find_LINENO(code) ### XXX because os.path.commonprefix seems broken by my way of thinking... def commonprefix(dirs): "Given a list of pathnames, returns the longest common leading component" if not dirs: return '' n = copy.copy(dirs) for i in range(len(n)): n[i] = n[i].split(os.sep) prefix = n[0] for item in n: for i in range(len(prefix)): if prefix[:i+1] <> item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return os.sep.join(prefix) class Trace: def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None): """ @param count true iff it should count number of times each line is executed @param trace true iff it should print out each line that is being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results """ self.infile = infile self.outfile = outfile self.ignore = Ignore(ignoremods, ignoredirs) self.counts = {} # keys are (filename, linenumber) self.blabbed = {} # for debugging self.pathtobasename = {} # for memoizing os.path.basename self.donothing = 0 self.trace = trace self._calledfuncs = {} if countfuncs: self.globaltrace = self.globaltrace_countfuncs elif trace and count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace_and_count elif trace: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace elif count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_count else: # Ahem -- do nothing? Okay. self.donothing = 1 def run(self, cmd): import __main__ dict = __main__.__dict__ if not self.donothing: sys.settrace(self.globaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None) def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(self.globaltrace) try: exec cmd in globals, locals finally: if not self.donothing: sys.settrace(None) def runfunc(self, func, *args, **kw): result = None if not self.donothing: sys.settrace(self.globaltrace) try: result = apply(func, args, kw) finally: if not self.donothing: sys.settrace(None) return result def globaltrace_countfuncs(self, frame, why, arg): """ Handles `call' events (why == 'call') and adds the (filename, modulename, funcname,) to the self._calledfuncs dict. """ if why == 'call': filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 0) if filename: modulename = inspect.getmodulename(filename) else: modulename = None self._calledfuncs[(filename, modulename, funcname,)] = 1 def globaltrace_lt(self, frame, why, arg): """ Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'. """ if why == 'call': filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 0) if filename: modulename = inspect.getmodulename(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print (" --- modulename: %s, funcname: %s" % (modulename, funcname)) return self.localtrace else: # XXX why no filename? return None def localtrace_trace_and_count(self, frame, why, arg): if why == 'line': # record the file name and line number of every trace # XXX I wish inspect offered me an optimized # `getfilename(frame)' to use in place of the presumably # heavier `getframeinfo()'. --Zooko 2001-10-14 filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. # --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? # --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: print "%s(%d): %s" % (bname, lineno, context[lineindex]), except IndexError: # Uh.. sometimes getframeinfo gives me a context of # length 1 and a lineindex of -2. Oh well. pass return self.localtrace def localtrace_trace(self, frame, why, arg): if why == 'line': # XXX shouldn't do the count increment when arg is # exception? But be careful to return self.localtrace # when arg is exception! ? --Zooko 2001-10-14 # record the file name and line number of every trace XXX # I wish inspect offered me an optimized # `getfilename(frame)' to use in place of the presumably # heavier `getframeinfo()'. --Zooko 2001-10-14 filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame) # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. # --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? # --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) if context is not None: try: print "%s(%d): %s" % (bname, lineno, context[lineindex]), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. pass else: print "%s(???): ???" % bname return self.localtrace def localtrace_count(self, frame, why, arg): if why == 'line': filename = frame.f_code.co_filename lineno = frame.f_lineno key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 return self.localtrace def results(self): return CoverageResults(self.counts, infile=self.infile, outfile=self.outfile, calledfuncs=self._calledfuncs) def _err_exit(msg): sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.exit(1) def main(argv=None): import getopt if argv is None: argv = sys.argv try: opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:l", ["help", "version", "trace", "count", "report", "no-report", "summary", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs",]) except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) trace = 0 count = 0 report = 0 no_report = 0 counts_file = None missing = 0 ignore_modules = [] ignore_dirs = [] coverdir = None summary = 0 listfuncs = False for opt, val in opts: if opt == "--help": usage(sys.stdout) sys.exit(0) if opt == "--version": sys.stdout.write("trace 2.0\n") sys.exit(0) if opt == "-l" or opt == "--listfuncs": listfuncs = True continue if opt == "-t" or opt == "--trace": trace = 1 continue if opt == "-c" or opt == "--count": count = 1 continue if opt == "-r" or opt == "--report": report = 1 continue if opt == "-R" or opt == "--no-report": no_report = 1 continue if opt == "-f" or opt == "--file": counts_file = val continue if opt == "-m" or opt == "--missing": missing = 1 continue if opt == "-C" or opt == "--coverdir": coverdir = val continue if opt == "-s" or opt == "--summary": summary = 1 continue if opt == "--ignore-module": ignore_modules.append(val) continue if opt == "--ignore-dir": for s in val.split(os.pathsep): s = os.path.expandvars(s) # should I also call expanduser? (after all, could use $HOME) s = s.replace("$prefix", os.path.join(sys.prefix, "lib", "python" + sys.version[:3])) s = s.replace("$exec_prefix", os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3])) s = os.path.normpath(s) ignore_dirs.append(s) continue assert 0, "Should never get here" if listfuncs and (count or trace): _err_exit("cannot specify both --listfuncs and (--trace or --count)") if not count and not trace and not report and not listfuncs: _err_exit("must specify one of --trace, --count, --report or --listfuncs") if report and no_report: _err_exit("cannot specify both --report and --no-report") if report and not counts_file: _err_exit("--report requires a --file") if no_report and len(prog_argv) == 0: _err_exit("missing name of file to run") # everything is ready if report: results = CoverageResults(infile=counts_file, outfile=counts_file) results.write_results(missing, summary=summary, coverdir=coverdir) else: sys.argv = prog_argv progname = prog_argv[0] sys.path[0] = os.path.split(progname)[0] t = Trace(count, trace, countfuncs=listfuncs, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(' + `progname` + ')') except IOError, err: _err_exit("Cannot run file %s because: %s" % (`sys.argv[0]`, err)) except SystemExit: pass results = t.results() if not no_report: results.write_results(missing, summary=summary, coverdir=coverdir) if __name__=='__main__': main() From nnorwitz@users.sourceforge.net Tue Feb 18 15:22:14 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 07:22:14 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_compile.py,1.16,1.17 test_sys.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3927/Lib/test Modified Files: test_compile.py test_sys.py Log Message: Fix SF bug #688424, 64-bit test problems Index: test_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_compile.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_compile.py 13 Feb 2003 22:07:55 -0000 1.16 --- test_compile.py 18 Feb 2003 15:22:09 -0000 1.17 *************** *** 146,153 **** import warnings warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) # XXX Of course the following test will have to be changed in Python 2.4 # This test is in a so the filterwarnings() can affect it exec """ ! expect_same("0xffffffff", -1) ! expect_same("-0xffffffff", 1) """ --- 146,158 ---- import warnings warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning) + warnings.filterwarnings("ignore", "hex.* of negative int", FutureWarning) # XXX Of course the following test will have to be changed in Python 2.4 # This test is in a so the filterwarnings() can affect it + import sys + all_one_bits = '0xffffffff' + if sys.maxint != 2147483647: + all_one_bits = '0xffffffffffffffff' exec """ ! expect_same(all_one_bits, -1) ! expect_same("-" + all_one_bits, 1) """ Index: test_sys.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sys.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_sys.py 3 Feb 2003 23:05:27 -0000 1.2 --- test_sys.py 18 Feb 2003 15:22:10 -0000 1.3 *************** *** 174,178 **** def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) ! self.assertRaises(ValueError, sys._getframe, sys.maxint) self.assert_( SysModuleTest.test_getframe.im_func.func_code \ --- 174,178 ---- def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) ! self.assertRaises(ValueError, sys._getframe, 2000000000) self.assert_( SysModuleTest.test_getframe.im_func.func_code \ From nnorwitz@users.sourceforge.net Tue Feb 18 15:45:47 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Tue, 18 Feb 2003 07:45:47 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_hexoct.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv16399/Lib/test Modified Files: test_hexoct.py Log Message: Fix SF bug #688424, 64-bit test problems Index: test_hexoct.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_hexoct.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_hexoct.py 12 Feb 2003 23:49:57 -0000 1.2 --- test_hexoct.py 18 Feb 2003 15:45:44 -0000 1.3 *************** *** 6,9 **** --- 6,12 ---- """ + import sys + platform_long_is_32_bits = sys.maxint == 2147483647 + import unittest from test import test_support *************** *** 19,45 **** self.assertEqual(0x0, 0) self.assertEqual(0x10, 16) ! self.assertEqual(0x7fffffff, 2147483647) # Ditto with a minus sign and parentheses self.assertEqual(-(0x0), 0) self.assertEqual(-(0x10), -16) ! self.assertEqual(-(0x7fffffff), -2147483647) # Ditto with a minus sign and NO parentheses self.assertEqual(-0x0, 0) self.assertEqual(-0x10, -16) ! self.assertEqual(-0x7fffffff, -2147483647) def test_hex_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: ! # Positive-looking constants with negavive values ! self.assertEqual(0x80000000, -2147483648L) ! self.assertEqual(0xffffffff, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(0x80000000), 2147483648L) ! self.assertEqual(-(0xffffffff), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-0x80000000, 2147483648L) ! self.assertEqual(-0xffffffff, 1) \n""" --- 22,69 ---- self.assertEqual(0x0, 0) self.assertEqual(0x10, 16) ! if platform_long_is_32_bits: ! self.assertEqual(0x7fffffff, 2147483647) ! else: ! self.assertEqual(0x7fffffffffffffff, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(0x0), 0) self.assertEqual(-(0x10), -16) ! if platform_long_is_32_bits: ! self.assertEqual(-(0x7fffffff), -2147483647) ! else: ! self.assertEqual(-(0x7fffffffffffffff), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-0x0, 0) self.assertEqual(-0x10, -16) ! if platform_long_is_32_bits: ! self.assertEqual(-0x7fffffff, -2147483647) ! else: ! self.assertEqual(-0x7fffffffffffffff, -9223372036854775807) def test_hex_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: ! if platform_long_is_32_bits: ! # Positive-looking constants with negavive values ! self.assertEqual(0x80000000, -2147483648L) ! self.assertEqual(0xffffffff, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(0x80000000), 2147483648L) ! self.assertEqual(-(0xffffffff), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-0x80000000, 2147483648L) ! self.assertEqual(-0xffffffff, 1) ! else: ! # Positive-looking constants with negavive values ! self.assertEqual(0x8000000000000000, -9223372036854775808L) ! self.assertEqual(0xffffffffffffffff, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(0x8000000000000000), 9223372036854775808L) ! self.assertEqual(-(0xffffffffffffffff), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-0x8000000000000000, 9223372036854775808L) ! self.assertEqual(-0xffffffffffffffff, 1) \n""" *************** *** 48,74 **** self.assertEqual(00, 0) self.assertEqual(020, 16) ! self.assertEqual(017777777777, 2147483647) # Ditto with a minus sign and parentheses self.assertEqual(-(00), 0) self.assertEqual(-(020), -16) ! self.assertEqual(-(017777777777), -2147483647) # Ditto with a minus sign and NO parentheses self.assertEqual(-00, 0) self.assertEqual(-020, -16) ! self.assertEqual(-017777777777, -2147483647) def test_oct_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: ! # Positive-looking constants with negavive values ! self.assertEqual(020000000000, -2147483648L) ! self.assertEqual(037777777777, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(020000000000), 2147483648L) ! self.assertEqual(-(037777777777), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-020000000000, 2147483648L) ! self.assertEqual(-037777777777, 1) \n""" --- 72,119 ---- self.assertEqual(00, 0) self.assertEqual(020, 16) ! if platform_long_is_32_bits: ! self.assertEqual(017777777777, 2147483647) ! else: ! self.assertEqual(0777777777777777777777, 9223372036854775807) # Ditto with a minus sign and parentheses self.assertEqual(-(00), 0) self.assertEqual(-(020), -16) ! if platform_long_is_32_bits: ! self.assertEqual(-(017777777777), -2147483647) ! else: ! self.assertEqual(-(0777777777777777777777), -9223372036854775807) # Ditto with a minus sign and NO parentheses self.assertEqual(-00, 0) self.assertEqual(-020, -16) ! if platform_long_is_32_bits: ! self.assertEqual(-017777777777, -2147483647) ! else: ! self.assertEqual(-0777777777777777777777, -9223372036854775807) def test_oct_unsigned(self): # This test is in a so we can ignore the warnings exec """if 1: ! if platform_long_is_32_bits: ! # Positive-looking constants with negavive values ! self.assertEqual(020000000000, -2147483648L) ! self.assertEqual(037777777777, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(020000000000), 2147483648L) ! self.assertEqual(-(037777777777), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-020000000000, 2147483648L) ! self.assertEqual(-037777777777, 1) ! else: ! # Positive-looking constants with negavive values ! self.assertEqual(01000000000000000000000, -9223372036854775808L) ! self.assertEqual(01777777777777777777777, -1) ! # Ditto with a minus sign and parentheses ! self.assertEqual(-(01000000000000000000000), 9223372036854775808L) ! self.assertEqual(-(01777777777777777777777), 1) ! # Ditto with a minus sign and NO parentheses ! # This failed in Python 2.2 through 2.2.2 and in 2.3a1 ! self.assertEqual(-01000000000000000000000, 9223372036854775808L) ! self.assertEqual(-01777777777777777777777, 1) \n""" From gvanrossum@users.sourceforge.net Tue Feb 18 16:11:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 08:11:15 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29960 Modified Files: _iconv_codec.c Log Message: Fold some long lines. Change fatal errors during module initialization into RuntimeErrors. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** _iconv_codec.c 10 Feb 2003 20:48:35 -0000 1.10 --- _iconv_codec.c 18 Feb 2003 16:11:11 -0000 1.11 *************** *** 145,149 **** while (inplen > 0) { ! if (iconv(self->enchdl, (char**)&inp, &inplen, &out, &outlen) == (size_t)-1) { char reason[128]; int errpos; --- 145,151 ---- while (inplen > 0) { ! if (iconv(self->enchdl, (char**)&inp, &inplen, &out, &outlen) ! == (size_t)-1) ! { char reason[128]; int errpos; *************** *** 248,253 **** newpos = inputlen + newpos; if (newpos < 0 || newpos > inputlen) { ! PyErr_Format(PyExc_IndexError, "position %ld from error handler" ! " out of bounds", newpos); goto errorexit; } --- 250,256 ---- newpos = inputlen + newpos; if (newpos < 0 || newpos > inputlen) { ! PyErr_Format(PyExc_IndexError, ! "position %ld from error handler out of bounds", ! newpos); goto errorexit; } *************** *** 477,482 **** newpos = inplen_total + newpos; if (newpos < 0 || newpos > inplen_total) { ! PyErr_Format(PyExc_IndexError, "position %ld from error handler" ! " out of bounds", newpos); goto errorexit; } --- 480,486 ---- newpos = inplen_total + newpos; if (newpos < 0 || newpos > inplen_total) { ! PyErr_Format(PyExc_IndexError, ! "position %ld from error handler out of bounds", ! newpos); goto errorexit; } *************** *** 497,501 **** finalsize = (int)(out - out_top); if (finalsize != outlen_total) { ! if (PyUnicode_Resize(&outputobj, finalsize / Py_UNICODE_SIZE) == -1) goto errorexit; } --- 501,506 ---- finalsize = (int)(out - out_top); if (finalsize != outlen_total) { ! if (PyUnicode_Resize(&outputobj, finalsize / Py_UNICODE_SIZE) ! == -1) goto errorexit; } *************** *** 669,680 **** iconv_t hdl = iconv_open(UNICODE_ENCODING, "ASCII"); ! if (hdl == (iconv_t)-1) ! Py_FatalError("can't initialize the _iconv_codec module: iconv_open() failed"); res = iconv(hdl, &inptr, &insize, &outptr, &outsize); ! if (res == (size_t)-1) ! Py_FatalError("can't initialize the _iconv_codec module: iconv() failed"); ! /* Check whether conv() returned native endianess or not for the chosen encoding */ if (out == 0x1) byteswap = 0; --- 674,692 ---- iconv_t hdl = iconv_open(UNICODE_ENCODING, "ASCII"); ! if (hdl == (iconv_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, ! "can't initialize the _iconv_codec module: iconv_open() failed"); ! return; ! } res = iconv(hdl, &inptr, &insize, &outptr, &outsize); ! if (res == (size_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, ! "can't initialize the _iconv_codec module: iconv() failed"); ! return; ! } ! /* Check whether conv() returned native endianess or not for the chosen ! encoding */ if (out == 0x1) byteswap = 0; *************** *** 685,690 **** #endif byteswap = 1; ! else ! Py_FatalError("can't initialize the _iconv_codec module: mixed endianess"); iconv_close(hdl); --- 697,706 ---- #endif byteswap = 1; ! else { ! iconv_close(hdl); ! PyErr_SetString(PyExc_RuntimeError, ! "can't initialize the _iconv_codec module: mixed endianess"); ! return; ! } iconv_close(hdl); *************** *** 698,702 **** if (PyErr_Occurred()) ! Py_FatalError("can't initialize the _iconv_codec module"); } --- 714,719 ---- if (PyErr_Occurred()) ! PyErr_SetString(PyExc_RuntimeError, ! "can't initialize the _iconv_codec module"); } From gvanrossum@users.sourceforge.net Tue Feb 18 16:33:53 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 08:33:53 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.117,2.118 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv11887 Modified Files: abstract.c Log Message: Make PyNumber_Check() a bit more careful, since all sorts of things now have tp_as_number. Check for nb_int or nb_float. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.117 retrieving revision 2.118 diff -C2 -d -r2.117 -r2.118 *** abstract.c 12 Feb 2003 03:36:05 -0000 2.117 --- abstract.c 18 Feb 2003 16:33:49 -0000 2.118 *************** *** 309,313 **** PyNumber_Check(PyObject *o) { ! return o && o->ob_type->tp_as_number; } --- 309,315 ---- PyNumber_Check(PyObject *o) { ! return o && o->ob_type->tp_as_number && ! (o->ob_type->tp_as_number->nb_int || ! o->ob_type->tp_as_number->nb_float); } From gvanrossum@users.sourceforge.net Tue Feb 18 16:36:34 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 08:36:34 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.663,1.664 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv13369 Modified Files: NEWS Log Message: Make PyNumber_Check() a bit more careful, since all sorts of things now have tp_as_number. Check for nb_int or nb_float. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.663 retrieving revision 1.664 diff -C2 -d -r1.663 -r1.664 *** NEWS 17 Feb 2003 12:26:23 -0000 1.663 --- NEWS 18 Feb 2003 16:36:28 -0000 1.664 *************** *** 90,93 **** --- 90,97 ---- ----------------- + - operator.isNumberType() now checks that the object has a nb_int or + nb_float slot, rather than simply checking whether it has a non-NULL + tp_as_number pointer. + - The imp module now has ways to acquire and release the "import lock": imp.acquire_lock() and imp.release_lock(). Note: this is a *************** *** 318,321 **** --- 322,329 ---- C API ----- + + - PyNumber_Check() now checks that the object has a nb_int or nb_float + slot, rather than simply checking whether it has a non-NULL + tp_as_number pointer. - A C type that inherits from a base type that defines tp_as_buffer From gvanrossum@users.sourceforge.net Tue Feb 18 16:40:16 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 08:40:16 -0800 Subject: [Python-checkins] python/dist/src/Objects object.c,2.197,2.198 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv15420 Modified Files: object.c Log Message: default_3way_compare(): use PyNumber_Check(), rather than testing for tp_as_number directly. Index: object.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v retrieving revision 2.197 retrieving revision 2.198 diff -C2 -d -r2.197 -r2.198 *** object.c 5 Feb 2003 19:35:19 -0000 2.197 --- object.c 18 Feb 2003 16:40:09 -0000 2.198 *************** *** 634,643 **** return 1; ! /* different type: compare type names */ ! if (v->ob_type->tp_as_number) vname = ""; else vname = v->ob_type->tp_name; ! if (w->ob_type->tp_as_number) wname = ""; else --- 634,643 ---- return 1; ! /* different type: compare type names; numbers are smaller */ ! if (PyNumber_Check(v)) vname = ""; else vname = v->ob_type->tp_name; ! if (PyNumber_Check(w)) wname = ""; else From tim_one@users.sourceforge.net Tue Feb 18 16:54:47 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 08:54:47 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descrtut.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23693/Lib/test Modified Files: test_descrtut.py Log Message: One doctest displaying a dict didn't sort it first. *Maybe* this fixes the AIX problem with this test. Index: test_descrtut.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descrtut.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** test_descrtut.py 23 Jul 2002 19:03:48 -0000 1.14 --- test_descrtut.py 18 Feb 2003 16:54:41 -0000 1.15 *************** *** 107,112 **** >>> 'default' in d and 'x1' in d and 'x2' in d True ! >>> print a.__dict__ ! {'default': -1000, 'x2': 200, 'x1': 100} >>> """ --- 107,112 ---- >>> 'default' in d and 'x1' in d and 'x2' in d True ! >>> print sortdict(a.__dict__) ! {'default': -1000, 'x1': 100, 'x2': 200} >>> """ From jhylton@users.sourceforge.net Tue Feb 18 17:02:19 2003 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Tue, 18 Feb 2003 09:02:19 -0800 Subject: [Python-checkins] python/dist/src/Objects funcobject.c,2.58,2.59 methodobject.c,2.45,2.46 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv29654 Modified Files: funcobject.c methodobject.c Log Message: Make __module__ settable on functions and methods. Index: funcobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/funcobject.c,v retrieving revision 2.58 retrieving revision 2.59 diff -C2 -d -r2.58 -r2.59 *** funcobject.c 31 Jan 2003 18:33:17 -0000 2.58 --- funcobject.c 18 Feb 2003 17:02:14 -0000 2.59 *************** *** 160,164 **** {"func_name", T_OBJECT, OFF(func_name), READONLY}, {"__name__", T_OBJECT, OFF(func_name), READONLY}, ! {"__module__", T_OBJECT, OFF(func_module), READONLY}, {NULL} /* Sentinel */ }; --- 160,164 ---- {"func_name", T_OBJECT, OFF(func_name), READONLY}, {"__name__", T_OBJECT, OFF(func_name), READONLY}, ! {"__module__", T_OBJECT, OFF(func_module)}, {NULL} /* Sentinel */ }; Index: methodobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/methodobject.c,v retrieving revision 2.45 retrieving revision 2.46 diff -C2 -d -r2.45 -r2.46 *** methodobject.c 31 Jan 2003 18:33:17 -0000 2.45 --- methodobject.c 18 Feb 2003 17:02:15 -0000 2.46 *************** *** 190,194 **** static PyMemberDef meth_members[] = { ! {"__module__", T_OBJECT, OFF(m_module), READONLY}, {NULL} }; --- 190,194 ---- static PyMemberDef meth_members[] = { ! {"__module__", T_OBJECT, OFF(m_module)}, {NULL} }; From gvanrossum@users.sourceforge.net Tue Feb 18 17:18:41 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 09:18:41 -0800 Subject: [Python-checkins] python/dist/src/Objects methodobject.c,2.46,2.47 funcobject.c,2.59,2.60 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv6882 Modified Files: methodobject.c funcobject.c Log Message: Make __method__ writable except in restricted mode (like for classic classes). Index: methodobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/methodobject.c,v retrieving revision 2.46 retrieving revision 2.47 diff -C2 -d -r2.46 -r2.47 *** methodobject.c 18 Feb 2003 17:02:15 -0000 2.46 --- methodobject.c 18 Feb 2003 17:18:34 -0000 2.47 *************** *** 190,194 **** static PyMemberDef meth_members[] = { ! {"__module__", T_OBJECT, OFF(m_module)}, {NULL} }; --- 190,194 ---- static PyMemberDef meth_members[] = { ! {"__module__", T_OBJECT, OFF(m_module), WRITE_RESTRICTED}, {NULL} }; Index: funcobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/funcobject.c,v retrieving revision 2.59 retrieving revision 2.60 diff -C2 -d -r2.59 -r2.60 *** funcobject.c 18 Feb 2003 17:02:14 -0000 2.59 --- funcobject.c 18 Feb 2003 17:18:35 -0000 2.60 *************** *** 160,164 **** {"func_name", T_OBJECT, OFF(func_name), READONLY}, {"__name__", T_OBJECT, OFF(func_name), READONLY}, ! {"__module__", T_OBJECT, OFF(func_module)}, {NULL} /* Sentinel */ }; --- 160,164 ---- {"func_name", T_OBJECT, OFF(func_name), READONLY}, {"__name__", T_OBJECT, OFF(func_name), READONLY}, ! {"__module__", T_OBJECT, OFF(func_module), WRITE_RESTRICTED}, {NULL} /* Sentinel */ }; From gvanrossum@users.sourceforge.net Tue Feb 18 19:22:28 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 11:22:28 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.210,2.211 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv15914 Modified Files: typeobject.c Log Message: The recent changes to super(), in particular supercheck(), broke when using super() for an instance in a metaclass situation. Because the class was a metaclass, the instance was a class, and hence the PyType_Check() branch was taken. But this branch didn't apply. Make it so that if this branch doesn't apply, the other branch is still tried. All tests pass. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.210 retrieving revision 2.211 diff -C2 -d -r2.210 -r2.211 *** typeobject.c 13 Feb 2003 16:24:34 -0000 2.210 --- typeobject.c 18 Feb 2003 19:22:22 -0000 2.211 *************** *** 5171,5184 **** */ ! if (PyType_Check(obj)) { ! /* It's a new-style class */ ! if (PyType_IsSubtype((PyTypeObject *)obj, type)) { ! Py_INCREF(obj); ! return (PyTypeObject *)obj; ! } ! else ! goto fail; } ! else if (PyType_IsSubtype(obj->ob_type, type)) { Py_INCREF(obj->ob_type); return obj->ob_type; --- 5171,5182 ---- */ ! /* Check for first bullet above (special case) */ ! if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { ! Py_INCREF(obj); ! return (PyTypeObject *)obj; } ! ! /* Normal case */ ! if (PyType_IsSubtype(obj->ob_type, type)) { Py_INCREF(obj->ob_type); return obj->ob_type; From tim_one@users.sourceforge.net Tue Feb 18 19:32:55 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 11:32:55 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.211,2.212 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv20183/python/Objects Modified Files: typeobject.c Log Message: Removed unreferenced label. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.211 retrieving revision 2.212 diff -C2 -d -r2.211 -r2.212 *** typeobject.c 18 Feb 2003 19:22:22 -0000 2.211 --- typeobject.c 18 Feb 2003 19:32:50 -0000 2.212 *************** *** 5211,5216 **** } ! fail: ! PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); --- 5211,5215 ---- } ! PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); From tim_one@users.sourceforge.net Tue Feb 18 20:50:48 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 12:50:48 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.138,2.139 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv29179/python/Modules Modified Files: cPickle.c Log Message: save_global(): Trying to resolve module.name can fail for two reasons: importing module can fail, or the attribute lookup module.name can fail. We were giving the same error msg for both cases, making it needlessly hard to guess what went wrong. These cases give different error msgs now. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.138 retrieving revision 2.139 diff -C2 -d -r2.138 -r2.139 *** cPickle.c 15 Feb 2003 15:07:17 -0000 2.138 --- cPickle.c 18 Feb 2003 20:50:45 -0000 2.139 *************** *** 2022,2027 **** if (mod == NULL) { cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: it's not found as %s.%s", ! "OSS", args, module, global_name); goto finally; } --- 2022,2028 ---- if (mod == NULL) { cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: import of module %s " ! "failed", ! "OS", args, module); goto finally; } *************** *** 2029,2033 **** if (klass == NULL) { cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: it's not found as %s.%s", "OSS", args, module, global_name); goto finally; --- 2030,2035 ---- if (klass == NULL) { cPickle_ErrFormat(PicklingError, ! "Can't pickle %s: attribute lookup %s.%s " ! "failed", "OSS", args, module, global_name); goto finally; From akuchling@users.sourceforge.net Tue Feb 18 21:28:24 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Tue, 18 Feb 2003 13:28:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command register.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv20300 Modified Files: register.py Log Message: Use python.org as the repository Index: register.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/register.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** register.py 3 Jan 2003 15:29:28 -0000 1.1 --- register.py 18 Feb 2003 21:28:20 -0000 1.2 *************** *** 18,23 **** description = "register the distribution with the repository" ! # XXX must update this to python.org before 2.3final! ! DEFAULT_REPOSITORY = 'http://www.amk.ca/cgi-bin/pypi.cgi' user_options = [ --- 18,22 ---- description = "register the distribution with the repository" ! DEFAULT_REPOSITORY = 'http://www.python.org/pypi' user_options = [ From tim_one@users.sourceforge.net Tue Feb 18 21:59:28 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 13:59:28 -0800 Subject: [Python-checkins] python/dist/src/PC python_nt.rc,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/PC In directory sc8-pr-cvs1:/tmp/cvs-serv5715/PC Modified Files: python_nt.rc Log Message: Bump version # to 2.3a2. Index: python_nt.rc =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/python_nt.rc,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** python_nt.rc 2 Jan 2003 17:09:19 -0000 1.20 --- python_nt.rc 18 Feb 2003 21:58:48 -0000 1.21 *************** *** 34,45 **** * following comment and #define are output from PCbuild\field3.py: * ! * For 2.3a0, * PY_MICRO_VERSION = 0 * PY_RELEASE_LEVEL = 'alpha' = 0xa ! * PY_RELEASE_SERIAL = 1 * ! * and 0*1000 + 10*10 + 1 = 101 */ ! #define FIELD3 101 /* e.g., 2.1a2 --- 34,45 ---- * following comment and #define are output from PCbuild\field3.py: * ! * For 2.3a2, * PY_MICRO_VERSION = 0 * PY_RELEASE_LEVEL = 'alpha' = 0xa ! * PY_RELEASE_SERIAL = 2 * ! * and 0*1000 + 10*10 + 2 = 102 */ ! #define FIELD3 102 /* e.g., 2.1a2 From tim_one@users.sourceforge.net Tue Feb 18 21:59:26 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 13:59:26 -0800 Subject: [Python-checkins] python/dist/src/Include patchlevel.h,2.63,2.64 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv5715/Include Modified Files: patchlevel.h Log Message: Bump version # to 2.3a2. Index: patchlevel.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/patchlevel.h,v retrieving revision 2.63 retrieving revision 2.64 diff -C2 -d -r2.63 -r2.64 *** patchlevel.h 31 Dec 2002 01:50:07 -0000 2.63 --- patchlevel.h 18 Feb 2003 21:58:43 -0000 2.64 *************** *** 24,31 **** #define PY_MICRO_VERSION 0 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA ! #define PY_RELEASE_SERIAL 1 /* Version as a string */ ! #define PY_VERSION "2.3a1" /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. --- 24,31 ---- #define PY_MICRO_VERSION 0 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_ALPHA ! #define PY_RELEASE_SERIAL 2 /* Version as a string */ ! #define PY_VERSION "2.3a2" /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. From tim_one@users.sourceforge.net Tue Feb 18 21:59:37 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 13:59:37 -0800 Subject: [Python-checkins] python/dist/src/PCbuild BUILDno.txt,1.41,1.42 python20.wse,1.116,1.117 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv5715/PCbuild Modified Files: BUILDno.txt python20.wse Log Message: Bump version # to 2.3a2. Index: BUILDno.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/BUILDno.txt,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** BUILDno.txt 31 Dec 2002 02:09:08 -0000 1.41 --- BUILDno.txt 18 Feb 2003 21:58:50 -0000 1.42 *************** *** 34,37 **** --- 34,39 ---- Windows Python BUILD numbers ---------------------------- + 39 2.3a2 + 19-Feb-2002 38 2.3a1 31-Dec-2002 Index: python20.wse =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/python20.wse,v retrieving revision 1.116 retrieving revision 1.117 diff -C2 -d -r1.116 -r1.117 *** python20.wse 17 Jan 2003 21:50:32 -0000 1.116 --- python20.wse 18 Feb 2003 21:58:53 -0000 1.117 *************** *** 2,6 **** item: Global Version=8.14 ! Title=Python 2.3 alpha 1 Flags=00010100 Languages=65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 --- 2,6 ---- item: Global Version=8.14 ! Title=Python 2.3 alpha 2 Flags=00010100 Languages=65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 *************** *** 19,25 **** Patch Threshold=85 Patch Memory=4000 ! EXE Filename=Python-2.3a1.exe Dialogs Version=8 ! Version File=2.3a1 Version Description=Python Programming Language Version Copyright=©2001-2003 Python Software Foundation --- 19,25 ---- Patch Threshold=85 Patch Memory=4000 ! EXE Filename=Python-2.3a2.exe Dialogs Version=8 ! Version File=2.3a2 Version Description=Python Programming Language Version Copyright=©2001-2003 Python Software Foundation *************** *** 67,71 **** item: Set Variable Variable=PYVER_STRING ! Value=2.3a1 end item: Remark --- 67,71 ---- item: Set Variable Variable=PYVER_STRING ! Value=2.3a2 end item: Remark From tim_one@users.sourceforge.net Tue Feb 18 22:00:10 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:00:10 -0800 Subject: [Python-checkins] python/dist/src/PCbuild pythoncore.dsp,1.42,1.43 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv6933/PCbuild Modified Files: pythoncore.dsp Log Message: Bump Windows build number for 2.3a2. Index: pythoncore.dsp =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/pythoncore.dsp,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** pythoncore.dsp 1 Feb 2003 00:10:11 -0000 1.42 --- pythoncore.dsp 18 Feb 2003 22:00:05 -0000 1.43 *************** *** 259,263 **** SOURCE=..\Modules\getbuildinfo.c ! # ADD CPP /D BUILD=38 # End Source File # Begin Source File --- 259,263 ---- SOURCE=..\Modules\getbuildinfo.c ! # ADD CPP /D BUILD=39 # End Source File # Begin Source File From gvanrossum@users.sourceforge.net Tue Feb 18 22:05:43 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:05:43 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.212,2.213 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv10437/Objects Modified Files: typeobject.c Log Message: Introducing __reduce_ex__, which is called with a protocol number argument if it exists in preference over __reduce__. Now Tim can go implement this in cPickle.c. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.212 retrieving revision 2.213 diff -C2 -d -r2.212 -r2.213 *** typeobject.c 18 Feb 2003 19:32:50 -0000 2.212 --- typeobject.c 18 Feb 2003 22:05:09 -0000 2.213 *************** *** 2442,2450 **** static PyObject * ! object_reduce(PyObject *self, PyObject *args) { ! /* Call copy_reg._reduce(self) */ static PyObject *copy_reg_str; PyObject *copy_reg, *res; if (!copy_reg_str) { --- 2442,2454 ---- static PyObject * ! object_reduce_ex(PyObject *self, PyObject *args) { ! /* Call copy_reg._reduce_ex(self, proto) */ static PyObject *copy_reg_str; PyObject *copy_reg, *res; + int proto = 0; + + if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) + return NULL; if (!copy_reg_str) { *************** *** 2456,2460 **** if (!copy_reg) return NULL; ! res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self); Py_DECREF(copy_reg); return res; --- 2460,2464 ---- if (!copy_reg) return NULL; ! res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto); Py_DECREF(copy_reg); return res; *************** *** 2462,2466 **** static PyMethodDef object_methods[] = { ! {"__reduce__", object_reduce, METH_NOARGS, PyDoc_STR("helper for pickle")}, {0} --- 2466,2472 ---- static PyMethodDef object_methods[] = { ! {"__reduce_ex__", object_reduce_ex, METH_VARARGS, ! PyDoc_STR("helper for pickle")}, ! {"__reduce__", object_reduce_ex, METH_VARARGS, PyDoc_STR("helper for pickle")}, {0} From gvanrossum@users.sourceforge.net Tue Feb 18 22:05:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:05:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descrtut.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv10437/Lib/test Modified Files: test_descrtut.py Log Message: Introducing __reduce_ex__, which is called with a protocol number argument if it exists in preference over __reduce__. Now Tim can go implement this in cPickle.c. Index: test_descrtut.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descrtut.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_descrtut.py 18 Feb 2003 16:54:41 -0000 1.15 --- test_descrtut.py 18 Feb 2003 22:05:12 -0000 1.16 *************** *** 211,214 **** --- 211,215 ---- '__new__', '__reduce__', + '__reduce_ex__', '__repr__', '__rmul__', From gvanrossum@users.sourceforge.net Tue Feb 18 22:05:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:05:15 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.20,1.21 pickle.py,1.153,1.154 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv10437/Lib Modified Files: copy_reg.py pickle.py Log Message: Introducing __reduce_ex__, which is called with a protocol number argument if it exists in preference over __reduce__. Now Tim can go implement this in cPickle.c. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** copy_reg.py 13 Feb 2003 16:25:37 -0000 1.20 --- copy_reg.py 18 Feb 2003 22:05:11 -0000 1.21 *************** *** 110,113 **** --- 110,124 ---- return __newobj__, (cls,) + args, state, listitems, dictitems + # Extended reduce: + + def _reduce_ex(obj, proto=0): + obj_reduce = getattr(obj, "__reduce__", None) + if obj_reduce and obj.__class__.__reduce__ is not object.__reduce__: + return obj_reduce() + elif proto < 2: + return _reduce(obj) + else: + return _better_reduce(obj) + def _slotnames(cls): """Return a list of slot names for a given class. Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.153 retrieving revision 1.154 diff -C2 -d -r1.153 -r1.154 *** pickle.py 15 Feb 2003 03:01:08 -0000 1.153 --- pickle.py 18 Feb 2003 22:05:11 -0000 1.154 *************** *** 305,323 **** # Check copy_reg.dispatch_table reduce = dispatch_table.get(t) ! if not reduce: ! # Check for a __reduce__ method. ! # Subtle: get the unbound method from the class, so that ! # protocol 2 can override the default __reduce__ that all ! # classes inherit from object. This has the added ! # advantage that the call always has the form reduce(obj) ! reduce = getattr(t, "__reduce__", None) ! if self.proto >= 2: ! # Protocol 2 can do better than the default __reduce__ ! if reduce is object.__reduce__: ! reduce = _better_reduce ! if not reduce: ! raise PicklingError("Can't pickle %r object: %r" % ! (t.__name__, obj)) ! rv = reduce(obj) # Check for string returned by reduce(), meaning "save as global" --- 305,322 ---- # Check copy_reg.dispatch_table reduce = dispatch_table.get(t) ! if reduce: ! rv = reduce(obj) ! else: ! # Check for a __reduce_ex__ method, fall back to __reduce__ ! reduce = getattr(obj, "__reduce_ex__", None) ! if reduce: ! rv = reduce(self.proto) ! else: ! reduce = getattr(obj, "__reduce__", None) ! if reduce: ! rv = reduce() ! else: ! raise PicklingError("Can't pickle %r object: %r" % ! (t.__name__, obj)) # Check for string returned by reduce(), meaning "save as global" From fdrake@users.sourceforge.net Tue Feb 18 22:12:01 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:12:01 -0800 Subject: [Python-checkins] python/dist/src/Doc/texinputs boilerplate.tex,1.76,1.77 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/texinputs In directory sc8-pr-cvs1:/tmp/cvs-serv15337/texinputs Modified Files: boilerplate.tex Log Message: Bump version number. Index: boilerplate.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/texinputs/boilerplate.tex,v retrieving revision 1.76 retrieving revision 1.77 diff -C2 -d -r1.76 -r1.77 *** boilerplate.tex 1 Jan 2003 04:50:32 -0000 1.76 --- boilerplate.tex 18 Feb 2003 22:11:58 -0000 1.77 *************** *** 8,11 **** \date{\today} % XXX update before release! \release{2.3} % software release, not documentation ! \setreleaseinfo{a1+} % empty for final release \setshortversion{2.3} % major.minor only for software --- 8,11 ---- \date{\today} % XXX update before release! \release{2.3} % software release, not documentation ! \setreleaseinfo{a2} % empty for final release \setshortversion{2.3} % major.minor only for software From fdrake@users.sourceforge.net Tue Feb 18 22:12:01 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:12:01 -0800 Subject: [Python-checkins] python/dist/src/Doc Makefile,1.250,1.251 Message-ID: Update of /cvsroot/python/python/dist/src/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv15337 Modified Files: Makefile Log Message: Bump version number. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/Makefile,v retrieving revision 1.250 retrieving revision 1.251 diff -C2 -d -r1.250 -r1.251 *** Makefile 31 Dec 2002 20:26:25 -0000 1.250 --- Makefile 18 Feb 2003 22:11:57 -0000 1.251 *************** *** 67,71 **** # This is the *documentation* release, and is used to construct the file # names of the downloadable tarballs. ! RELEASE=2.3a1+ PYTHON= python --- 67,71 ---- # This is the *documentation* release, and is used to construct the file # names of the downloadable tarballs. ! RELEASE=2.3a2 PYTHON= python From tim_one@users.sourceforge.net Tue Feb 18 22:17:44 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:17:44 -0800 Subject: [Python-checkins] python/dist/src/PCbuild BUILDno.txt,1.42,1.43 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv18286/python/PCbuild Modified Files: BUILDno.txt Log Message: I entered the wrong year for 2.3a2. Index: BUILDno.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/BUILDno.txt,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** BUILDno.txt 18 Feb 2003 21:58:50 -0000 1.42 --- BUILDno.txt 18 Feb 2003 22:17:40 -0000 1.43 *************** *** 35,39 **** ---------------------------- 39 2.3a2 ! 19-Feb-2002 38 2.3a1 31-Dec-2002 --- 35,39 ---- ---------------------------- 39 2.3a2 ! 19-Feb-2003 38 2.3a1 31-Dec-2002 From gvanrossum@users.sourceforge.net Tue Feb 18 22:41:28 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:41:28 -0800 Subject: [Python-checkins] python/dist/src/Lib/test pickletester.py,1.52,1.53 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv798 Modified Files: pickletester.py Log Message: Three test cases for __reduce_ex__. This fails for cPickle, until Tim checks in his changes to support this in cPickle.c. Index: pickletester.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/pickletester.py,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** pickletester.py 15 Feb 2003 03:01:09 -0000 1.52 --- pickletester.py 18 Feb 2003 22:41:24 -0000 1.53 *************** *** 740,743 **** --- 740,795 ---- self.assertEqual(x.bar, y.bar) + def test_reduce_overrides_default_reduce_ex(self): + for proto in 0, 1, 2: + x = REX_one() + self.assertEqual(x._reduce_called, 0) + s = self.dumps(x, proto) + self.assertEqual(x._reduce_called, 1) + y = self.loads(s) + self.assertEqual(y._reduce_called, 0) + + def test_reduce_ex_called(self): + for proto in 0, 1, 2: + x = REX_two() + self.assertEqual(x._proto, None) + s = self.dumps(x, proto) + self.assertEqual(x._proto, proto) + y = self.loads(s) + self.assertEqual(y._proto, None) + + def test_reduce_ex_overrides_reduce(self): + for proto in 0, 1, 2: + x = REX_three() + self.assertEqual(x._proto, None) + s = self.dumps(x, proto) + self.assertEqual(x._proto, proto) + y = self.loads(s) + self.assertEqual(y._proto, None) + + # Test classes for reduce_ex + + class REX_one(object): + _reduce_called = 0 + def __reduce__(self): + self._reduce_called = 1 + return REX_one, () + # No __reduce_ex__ here, but inheriting it from object + + class REX_two(object): + _proto = None + def __reduce_ex__(self, proto): + self._proto = proto + return REX_two, () + # No __reduce__ here, but inheriting it from object + + class REX_three(object): + _proto = None + def __reduce_ex__(self, proto): + self._proto = proto + return REX_two, () + def __reduce__(self): + raise TestFailed, "This __reduce__ shouldn't be called" + + # Test classes for newobj class MyInt(int): From gvanrossum@users.sourceforge.net Tue Feb 18 22:49:13 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 14:49:13 -0800 Subject: [Python-checkins] python/dist/src/Lib pickle.py,1.154,1.155 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv6257 Modified Files: pickle.py Log Message: Remove unused _better_reduce (which will disappear soon) and _reconstructor (whose import here is a mystery to me). Index: pickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pickle.py,v retrieving revision 1.154 retrieving revision 1.155 diff -C2 -d -r1.154 -r1.155 *** pickle.py 18 Feb 2003 22:05:11 -0000 1.154 --- pickle.py 18 Feb 2003 22:49:10 -0000 1.155 *************** *** 28,32 **** from types import * ! from copy_reg import dispatch_table, _reconstructor, _better_reduce from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal --- 28,32 ---- from types import * ! from copy_reg import dispatch_table from copy_reg import _extension_registry, _inverted_registry, _extension_cache import marshal From jackjansen@users.sourceforge.net Tue Feb 18 23:28:08 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 15:28:08 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac argvemulator.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv30644 Modified Files: argvemulator.py Log Message: Argvemulator still used the old Alias API. Fixed. Index: argvemulator.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/argvemulator.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** argvemulator.py 30 Dec 2002 22:04:20 -0000 1.1 --- argvemulator.py 18 Feb 2003 23:28:05 -0000 1.2 *************** *** 102,107 **** def open_file(self, _object=None, **args): for alias in _object: ! fss = alias.Resolve()[0] ! pathname = fss.as_pathname() sys.argv.append(pathname) self._quit() --- 102,107 ---- def open_file(self, _object=None, **args): for alias in _object: ! fsr = alias.FSResolveAlias(None)[0] ! pathname = fsr.as_pathname() sys.argv.append(pathname) self._quit() From jackjansen@users.sourceforge.net Tue Feb 18 23:29:50 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 15:29:50 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv31090 Modified Files: bundlebuilder.py Log Message: Added an argv_emulation option (command line option: --argv or -a) which creates the sys.argv emulation wrapper for droplets. Also updates the plist, if needed, and the includedModules (but this last is untested). Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** bundlebuilder.py 18 Feb 2003 11:24:31 -0000 1.9 --- bundlebuilder.py 18 Feb 2003 23:29:46 -0000 1.10 *************** *** 267,270 **** --- 267,276 ---- """ + ARGVEMULATOR="""\ + import argvemulator, os + + argvemulator.ArgvCollector().mainloop() + execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s")) + """ class AppBuilder(BundleBuilder): *************** *** 294,297 **** --- 300,307 ---- # If True, build standalone app. standalone = 0 + + # If True, add a real main program that emulates sys.argv before calling + # mainprogram + argv_emulation = 0 # The following attributes are only used when building a standalone app. *************** *** 369,372 **** --- 379,403 ---- mainprogram = os.path.basename(self.mainprogram) self.files.append((self.mainprogram, pathjoin(resdir, mainprogram))) + if self.argv_emulation: + # Change the main program, and create the helper main program (which + # does argv collection and then calls the real main). + # Also update the included modules (if we're creating a standalone + # program) and the plist + realmainprogram = mainprogram + mainprogram = '__argvemulator_' + mainprogram + resdirpath = pathjoin(self.bundlepath, resdir) + mainprogrampath = pathjoin(resdirpath, mainprogram) + makedirs(resdirpath) + open(mainprogrampath, "w").write(ARGVEMULATOR % locals()) + if self.standalone: + self.includeModules.append("argvemulator") + self.includeModules.append("os") + if not self.plist.has_key("CFBundleDocumentTypes"): + self.plist["CFBundleDocumentTypes"] = [ + { "CFBundleTypeOSTypes" : [ + "****", + "fold", + "disk"], + "CFBundleTypeRole": "Viewer"}] # Write bootstrap script executable = os.path.basename(self.executable) *************** *** 620,623 **** --- 651,655 ---- -e, --executable=FILE the executable to be used -m, --mainprogram=FILE the Python main program + -a, --argv add a wrapper main program to create sys.argv -p, --plist=FILE .plist file (default: generate one) --nib=NAME main nib name *************** *** 648,655 **** builder = AppBuilder(verbosity=1) ! shortopts = "b:n:r:e:m:c:p:lx:i:hvq" longopts = ("builddir=", "name=", "resource=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", ! "link-exec", "help", "verbose", "quiet", "standalone", "exclude=", "include=", "package=", "strip", "iconfile=") --- 680,687 ---- builder = AppBuilder(verbosity=1) ! shortopts = "b:n:r:e:m:c:p:lx:i:hvqa" longopts = ("builddir=", "name=", "resource=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", ! "link-exec", "help", "verbose", "quiet", "argv", "standalone", "exclude=", "include=", "package=", "strip", "iconfile=") *************** *** 670,673 **** --- 702,707 ---- elif opt in ('-m', '--mainprogram'): builder.mainprogram = arg + elif opt in ('-a', '--argv'): + builder.argv_emulation = 1 elif opt in ('-c', '--creator'): builder.creator = arg From jackjansen@users.sourceforge.net Tue Feb 18 23:30:31 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 15:30:31 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac buildtools.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv32027 Modified Files: buildtools.py Log Message: Enable argv emulation if required. Fixed a bug for applets with their own plist files. Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** buildtools.py 12 Feb 2003 15:37:26 -0000 1.5 --- buildtools.py 18 Feb 2003 23:30:27 -0000 1.6 *************** *** 304,311 **** builder.resources.append(o) if plistname: ! import Plist ! builder.plist = Plist.fromFile(plistname) if icnsname: builder.iconfile = icnsname builder.setup() builder.build() --- 304,313 ---- builder.resources.append(o) if plistname: ! import plistlib ! builder.plist = plistlib.Plist.fromFile(plistname) if icnsname: builder.iconfile = icnsname + if not raw: + builder.argv_emulation = 1 builder.setup() builder.build() From jackjansen@users.sourceforge.net Tue Feb 18 23:32:55 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 15:32:55 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.664,1.665 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv909 Modified Files: NEWS Log Message: Added a note that MacOSX applets can no longer be run from a terminal window. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.664 retrieving revision 1.665 diff -C2 -d -r1.664 -r1.665 *** NEWS 18 Feb 2003 16:36:28 -0000 1.664 --- NEWS 18 Feb 2003 23:32:47 -0000 1.665 *************** *** 381,385 **** - Applets are now built with bundlebuilder in MacPython-OSX, which should make ! them more robust and also provides a path towards BuildApplication. --- 381,387 ---- - Applets are now built with bundlebuilder in MacPython-OSX, which should make ! them more robust and also provides a path towards BuildApplication. The ! downside of this change is that applets can no longer be run from the ! Terminal window, this will hopefully be fixed in the 2.3b1. From jackjansen@users.sourceforge.net Tue Feb 18 23:33:42 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 18 Feb 2003 15:33:42 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX Makefile,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv1262 Modified Files: Makefile Log Message: Undid half of the previous checkin: continue using BuildApplet for most applets. PackageManager is still built with bundlebuilder itself. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/Makefile,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** Makefile 12 Feb 2003 15:42:49 -0000 1.34 --- Makefile 18 Feb 2003 23:33:39 -0000 1.35 *************** *** 49,54 **** bundlebuilder=$(srcdir)/Lib/plat-mac/bundlebuilder.py ! installapps: install_PythonLauncher install_Python install_BuildApplet \ ! install_PackageManager install_IDE install_IDLE install_PythonLauncher: --- 49,54 ---- bundlebuilder=$(srcdir)/Lib/plat-mac/bundlebuilder.py ! installapps: install_PythonLauncher install_Python install_BuildApplet install_IDE \ ! install_IDLE install_PackageManager install_PythonLauncher: *************** *** 105,120 **** echo See Mac/OSX/README for details; \ else \ ! echo $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PythonIDE.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PythonIDE.icns \ ! --creator Pide build; \ ! $(INSTALLED_PYTHONW) $(bundlebuilder) \ ! --builddir $(PYTHONAPPSDIR)/ \ ! --resource $(srcdir)/Mac/Tools/IDE/PythonIDE.rsrc \ ! --mainprogram $(srcdir)/Mac/Tools/IDE/PythonIDE.py \ ! --iconfile $(srcdir)/Mac/Tools/IDE/PythonIDE.icns \ ! --creator Pide build; \ fi --- 105,114 ---- echo See Mac/OSX/README for details; \ else \ ! echo $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ ! --output $(PYTHONAPPSDIR)/PythonIDE.app --noargv \ ! $(srcdir)/Mac/Tools/IDE/PythonIDE.py ; \ ! $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ ! --output $(PYTHONAPPSDIR)/PythonIDE.app --noargv \ ! $(srcdir)/Mac/Tools/IDE/PythonIDE.py; \ fi From mhammond@users.sourceforge.net Wed Feb 19 00:33:36 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Tue, 18 Feb 2003 16:33:36 -0800 Subject: [Python-checkins] python/dist/src/Lib warnings.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv2094/Lib Modified Files: warnings.py Log Message: Fix bug 683658 - PyErr_Warn may cause import deadlock. Index: warnings.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/warnings.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** warnings.py 14 Oct 2002 21:06:02 -0000 1.18 --- warnings.py 19 Feb 2003 00:33:33 -0000 1.19 *************** *** 1,5 **** --- 1,9 ---- """Python part of the warnings subsystem.""" + # Note: function level imports should *not* be used + # in this module as it may cause import lock deadlock. + # See bug 683658. import sys, re, types + import linecache __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", *************** *** 115,119 **** def formatwarning(message, category, filename, lineno): """Function to format a warning the standard way.""" - import linecache s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) line = linecache.getline(filename, lineno).strip() --- 119,122 ---- From mhammond@users.sourceforge.net Wed Feb 19 00:33:35 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Tue, 18 Feb 2003 16:33:35 -0800 Subject: [Python-checkins] python/dist/src/Python errors.c,2.75,2.76 pythonrun.c,2.177,2.178 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv2094/Python Modified Files: errors.c pythonrun.c Log Message: Fix bug 683658 - PyErr_Warn may cause import deadlock. Index: errors.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/errors.c,v retrieving revision 2.75 retrieving revision 2.76 diff -C2 -d -r2.75 -r2.76 *** errors.c 11 Dec 2002 14:04:59 -0000 2.75 --- errors.c 19 Feb 2003 00:33:32 -0000 2.76 *************** *** 601,604 **** --- 601,605 ---- } + extern PyObject *PyModule_WarningsModule; /* Function to issue a warning message; may raise an exception. */ *************** *** 606,616 **** PyErr_Warn(PyObject *category, char *message) { ! PyObject *mod, *dict, *func = NULL; ! mod = PyImport_ImportModule("warnings"); ! if (mod != NULL) { ! dict = PyModule_GetDict(mod); func = PyDict_GetItemString(dict, "warn"); - Py_DECREF(mod); } if (func == NULL) { --- 607,615 ---- PyErr_Warn(PyObject *category, char *message) { ! PyObject *dict, *func = NULL; ! if (PyModule_WarningsModule != NULL) { ! dict = PyModule_GetDict(PyModule_WarningsModule); func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { Index: pythonrun.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/pythonrun.c,v retrieving revision 2.177 retrieving revision 2.178 diff -C2 -d -r2.177 -r2.178 *** pythonrun.c 13 Feb 2003 22:07:59 -0000 2.177 --- pythonrun.c 19 Feb 2003 00:33:33 -0000 2.178 *************** *** 61,64 **** --- 61,69 ---- int _Py_QnewFlag = 0; + /* Reference to 'warnings' module, to avoid importing it + on the fly when the import lock may be held. See 683658 + */ + PyObject *PyModule_WarningsModule = NULL; + static int initialized = 0; *************** *** 170,173 **** --- 175,180 ---- _PyImportHooks_Init(); + PyModule_WarningsModule = PyImport_ImportModule("warnings"); + initsigs(); /* Signal handling stuff, including initintr() */ *************** *** 225,228 **** --- 232,239 ---- /* Cleanup Codec registry */ _PyCodecRegistry_Fini(); + + /* drop module references we saved */ + Py_XDECREF(PyModule_WarningsModule); + PyModule_WarningsModule = NULL; /* Destroy all modules */ From guido@python.org Wed Feb 19 00:46:17 2003 From: guido@python.org (Guido van Rossum) Date: Tue, 18 Feb 2003 19:46:17 -0500 Subject: [Python-checkins] python/dist/src/Python errors.c,2.75,2.76 pythonrun.c,2.177,2.178 In-Reply-To: "Your message of Tue, 18 Feb 2003 16:33:35 PST." References: Message-ID: <200302190046.h1J0kHE32512@pcp02138704pcs.reston01.va.comcast.net> > Log Message: > Fix bug 683658 - PyErr_Warn may cause import deadlock. > > > Index: errors.c > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Python/errors.c,v > retrieving revision 2.75 > retrieving revision 2.76 > diff -C2 -d -r2.75 -r2.76 > *** errors.c 11 Dec 2002 14:04:59 -0000 2.75 > --- errors.c 19 Feb 2003 00:33:32 -0000 2.76 > *************** > *** 601,604 **** > --- 601,605 ---- > } > > + extern PyObject *PyModule_WarningsModule; [...] I'll let this go for now, but this should *not* be fixed this way: it breaks when multiple interpreters are used. This must be fixed before 2.3b1 is released. (And you never explained why you couldn't restructure your main program to avoid doing actions as a side effect of import, as I suggested.) --Guido van Rossum (home page: http://www.python.org/~guido/) From goodger@users.sourceforge.net Wed Feb 19 00:46:53 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Tue, 18 Feb 2003 16:46:53 -0800 Subject: [Python-checkins] python/nondist/peps pep-0309.txt,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv9196 Modified Files: pep-0309.txt Log Message: update from Peter Harris, with editorial tweaks Index: pep-0309.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0309.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pep-0309.txt 10 Feb 2003 14:51:45 -0000 1.1 --- pep-0309.txt 19 Feb 2003 00:46:51 -0000 1.2 *************** *** 1,4 **** PEP: 309 ! Title: Built-in Closure Type Version: $Revision$ Last-Modified: $Date$ --- 1,4 ---- PEP: 309 ! Title: Built-in Curry Type Version: $Revision$ Last-Modified: $Date$ *************** *** 9,13 **** Created: 08-Feb-2003 Python-Version: 2.4 ! Post-History: --- 9,13 ---- Created: 08-Feb-2003 Python-Version: 2.4 ! Post-History: 10-Feb-2003 *************** *** 15,22 **** ========= ! This proposal is for a built-in closure type for Python that allows a ! new callable to be constructed from another callable and a partial ! argument list (including positional and keyword arguments). A concise ! syntax shorthand for closures is suggested (tentatively). --- 15,27 ---- ========= ! This proposal is for a built-in closure or curry type for Python that ! allows a new callable to be constructed from another callable and a ! partial argument list (including positional and keyword arguments). A ! concise syntax shorthand for curried functions is suggested ! (tentatively). ! ! Note: after feedback on comp.lang.python, I am persuaded that the most ! accurate term for this is a 'curry', so the terminology has been ! amended since the first version of this PEP. *************** *** 24,33 **** =========== ! Closures are useful as functional 'sections' or as convenient anonymous functions for use as callbacks. In some functional languages, (e.g. Miranda) you can use an expression ! such as ``(+1)`` to mean the equivalent of Python's ``(lambda x: x + ! 1)``. In general, languages like that are strongly typed, so the compiler --- 29,38 ---- =========== ! Curried functions are useful as functional 'sections' or as convenient anonymous functions for use as callbacks. In some functional languages, (e.g. Miranda) you can use an expression ! such as ``(+1)`` to mean the equivalent of Python's ! ``(lambda x: x + 1)``. In general, languages like that are strongly typed, so the compiler *************** *** 35,40 **** thing when presented with a functor and less arguments than expected. ! Python has more flexible argument-passing, and so closures cannot be ! implicit in the same way. Instead of using them, a Python programmer will probably either define another named function or use a lambda. But lambda syntax is horrible, especially when you want to do --- 40,45 ---- thing when presented with a functor and less arguments than expected. ! Python has more flexible argument-passing, and so curries cannot be ! implicit in the same way. Instead of using them, a Python programmer will probably either define another named function or use a lambda. But lambda syntax is horrible, especially when you want to do *************** *** 47,53 **** ========== ! Here is one way to do closures in Python:: ! class closure(object): def __init__(self, fn, *args, **kw): --- 52,58 ---- ========== ! Here is one way to do a curry in Python:: ! class curry(object): def __init__(self, fn, *args, **kw): *************** *** 59,73 **** return self.fn(*(self.args + args), **d) ! Note that when the closure is called, positional arguments are appended to those provided to the constructor, and keyword arguments override and augment those provided to the constructor. ! So ``closure(operator.add,1)`` is a bit like ``(lambda x: 1+x)``, and ! ``closure(Tkinter.Label,fg='blue')`` is a callable like the Tkinter Label class, but with a blue foreground by default. ! I think a built-in type called ``closure``, that behaves the same way but maybe implemented more efficiently, would be very useful. Tentative Syntax Proposal --- 64,82 ---- return self.fn(*(self.args + args), **d) ! Note that when the curry is called, positional arguments are appended to those provided to the constructor, and keyword arguments override and augment those provided to the constructor. ! So ``curry(operator.add, 1)`` is a bit like ``(lambda x: 1 + x)``, and ! ``curry(Tkinter.Label, fg='blue')`` is a callable like the Tkinter Label class, but with a blue foreground by default. ! I think a built-in type called ``curry``, that behaves the same way but maybe implemented more efficiently, would be very useful. + Update: a recipe almost exactly like this has been in the Python + Cookbook for quite some time, at + http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549. + Tentative Syntax Proposal *************** *** 76,83 **** I know syntax proposals have the odds stacked against them, and introducing new punctuation characters is frowned upon, but I think ! closures are a sufficiently powerful abstraction to deserve it. ! I propose the syntax ``fn@(*args,**kw)``, meaning the same as ! ``closure(fn,*args,**kw)``. I have no idea what havoc this would wreak on the parser. --- 85,92 ---- I know syntax proposals have the odds stacked against them, and introducing new punctuation characters is frowned upon, but I think ! curries may be a sufficiently powerful abstraction to deserve it. ! I suggest the syntax ``fn@(*args, **kw)``, meaning the same as ! ``curry(fn, *args, **kw)``. I have no idea what havoc this would wreak on the parser. *************** *** 90,93 **** --- 99,105 ---- call it. + (The only other connection I can see with curry is that @ looks a bit + like a section through a mushroom pakora.) + Examples of Use *************** *** 100,106 **** button1 = Button(window, text="Action A", ! command=handler@('A','1')) button2 = Button(window, text="Action B", ! command=handler@('B','2',opt=1)) Convenience functions :: --- 112,118 ---- button1 = Button(window, text="Action A", ! command=handler@('A', '1')) button2 = Button(window, text="Action B", ! command=handler@('B', '2', opt=1)) Convenience functions :: *************** *** 109,112 **** --- 121,207 ---- + Feedback from comp.lang.python + =============================== + + Among the opinions voiced were the following (which I summarise): + + * Lambda is good enough. + + * The @ syntax is ugly (so far, unanimous). + + * It's really a curry rather than a closure. There is an almost + identical implementation of a curry class on ActiveState's Python + Cookbook. + + * A curry class would indeed be a useful addition to the standard + library. + + * It maybe isn't useful enough to be in the builtins. + + I agree that lambda is usually good enough, just not always. And I + want the possibility of useful introspection and subclassing. + + I disagree that @ is particularly ugly, but it may be that I'm just + weird. We have dictionary, list and tuple literals neatly + differentiated by special punctuation -- a way of directly expressing + curried function literals is not such a stretch. However, not one + single person has said they like it, so as far as I'm concerned it's a + dead parrot. + + I concur with calling the class curry rather than closure, so I have + amended this PEP accordingly. + + I think it's best as a builtin type rather than in a separate standard + library module, because it's simple and general enough. It may not be + an idiom that is very common in Python programming at the moment, but + I think that's because you have to code it yourself if you want it. + If added as a built-in feature, we would soon be wondering how we + managed without it. + + Carl Banks posted an implementation as a real functional closure:: + + def curry(fn, *cargs, **ckwargs): + def call_fn(*fargs, **fkwargs): + d = ckwargs.copy() + d.update(fkwargs) + return fn(*(cargs + fargs), **d) + return call_fn + + which he assures me is more efficient. All you lose with this + implementation is introspection and sub-classing. These are only + marginal benefits and not worth a performance hit, so this would also + do as a reference implementation of a built-in curry function rather + than a built-in curry class. + + I also coded the class in Pyrex:: + + cdef class curry: + cdef object fn, args, kw + def __init__(self, fn, *args, **kw): + self.fn=fn + self.args=args + self.kw = kw + + def __call__(self, *args, **kw): + if self.kw: # from Python Cookbook version + d = self.kw.copy() + d.update(kw) + else: + d=kw + return self.fn(*(self.args + args), **d) + + but I'm guessing that there would be minimal performance improvement + since it compiles to a load of Python API calls. + + + Summary + ======== + + I maintain that curry should be a built-in, with the semantics as + described, whether as a function or a class. + + The @ syntax proposal is withdrawn. + + Copyright ========= *************** *** 123,125 **** fill-column: 70 End: - --- 218,219 ---- From goodger@users.sourceforge.net Wed Feb 19 00:53:10 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Tue, 18 Feb 2003 16:53:10 -0800 Subject: [Python-checkins] python/nondist/peps pep-0000.txt,1.232,1.233 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv11849 Modified Files: pep-0000.txt Log Message: title change to PEP 309 Index: pep-0000.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0000.txt,v retrieving revision 1.232 retrieving revision 1.233 diff -C2 -d -r1.232 -r1.233 *** pep-0000.txt 14 Feb 2003 15:37:24 -0000 1.232 --- pep-0000.txt 19 Feb 2003 00:53:08 -0000 1.233 *************** *** 110,114 **** S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR, Hettinger ! S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore S 311 Simplified GIL Acquisition for Extensions Hammond --- 110,114 ---- S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR, Hettinger ! S 309 Built-in Curry Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore S 311 Simplified GIL Acquisition for Extensions Hammond *************** *** 313,317 **** S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR, Hettinger ! S 309 Built-in Closure Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore S 311 Simplified GIL Acquisition for Extensions Hammond --- 313,317 ---- S 307 Extensions to the pickle protocol GvR, Peters S 308 If-then-else expression GvR, Hettinger ! S 309 Built-in Curry Type Harris S 310 Reliable Acquisition/Release Pairs Hudson, Moore S 311 Simplified GIL Acquisition for Extensions Hammond From gvanrossum@users.sourceforge.net Wed Feb 19 01:19:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 17:19:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_copy.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23765/test Modified Files: test_copy.py Log Message: Use __reduce_ex__ in copy.py. The test_*copy_cant() tests are simpler again. Index: test_copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_copy.py 7 Feb 2003 17:53:23 -0000 1.6 --- test_copy.py 19 Feb 2003 01:19:28 -0000 1.7 *************** *** 47,50 **** --- 47,60 ---- y = copy.copy(x) + def test_copy_reduce_ex(self): + class C(object): + def __reduce_ex__(self, proto): + return "" + def __reduce__(self): + raise test_support.TestFailed, "shouldn't call this" + x = C() + y = copy.copy(x) + self.assert_(y is x) + def test_copy_reduce(self): class C(object): *************** *** 56,66 **** def test_copy_cant(self): ! class Meta(type): def __getattribute__(self, name): ! if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) - class C: - __metaclass__ = Meta x = C() self.assertRaises(copy.Error, copy.copy, x) --- 66,74 ---- def test_copy_cant(self): ! class C(object): def __getattribute__(self, name): ! if name.startswith("__reduce"): raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.copy, x) *************** *** 210,213 **** --- 218,231 ---- y = copy.deepcopy(x) + def test_deepcopy_reduce_ex(self): + class C(object): + def __reduce_ex__(self, proto): + return "" + def __reduce__(self): + raise test_support.TestFailed, "shouldn't call this" + x = C() + y = copy.deepcopy(x) + self.assert_(y is x) + def test_deepcopy_reduce(self): class C(object): *************** *** 219,229 **** def test_deepcopy_cant(self): ! class Meta(type): def __getattribute__(self, name): ! if name == "__reduce__": raise AttributeError, name return object.__getattribute__(self, name) - class C: - __metaclass__ = Meta x = C() self.assertRaises(copy.Error, copy.deepcopy, x) --- 237,245 ---- def test_deepcopy_cant(self): ! class C(object): def __getattribute__(self, name): ! if name.startswith("__reduce"): raise AttributeError, name return object.__getattribute__(self, name) x = C() self.assertRaises(copy.Error, copy.deepcopy, x) From gvanrossum@users.sourceforge.net Wed Feb 19 01:19:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 17:19:30 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.36,1.37 copy_reg.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv23765 Modified Files: copy.py copy_reg.py Log Message: Use __reduce_ex__ in copy.py. The test_*copy_cant() tests are simpler again. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** copy.py 7 Feb 2003 17:53:20 -0000 1.36 --- copy.py 19 Feb 2003 01:19:27 -0000 1.37 *************** *** 80,91 **** reductor = dispatch_table.get(cls) ! if not reductor: ! reductor = getattr(cls, "__reduce__", None) ! if reductor == object.__reduce__: ! reductor = _better_reduce ! elif not reductor: ! raise Error("un(shallow)copyable object of type %s" % cls) ! return _reconstruct(x, reductor(x), 0) --- 80,97 ---- reductor = dispatch_table.get(cls) ! if reductor: ! rv = reductor(x) ! else: ! reductor = getattr(x, "__reduce_ex__", None) ! if reductor: ! rv = reductor(2) ! else: ! reductor = getattr(x, "__reduce__", None) ! if reductor: ! rv = reductor() ! else: ! raise Error("un(shallow)copyable object of type %s" % cls) ! return _reconstruct(x, rv, 0) *************** *** 177,195 **** issc = 0 if issc: ! copier = _deepcopy_atomic ! else: ! copier = getattr(cls, "__deepcopy__", None) ! ! if copier: ! y = copier(x, memo) else: ! reductor = dispatch_table.get(cls) ! if not reductor: ! reductor = getattr(cls, "__reduce__", None) ! if reductor == object.__reduce__: ! reductor = _better_reduce ! elif not reductor: ! raise Error("un(deep)copyable object of type %s" % cls) ! y = _reconstruct(x, reductor(x), 1, memo) memo[d] = y --- 183,207 ---- issc = 0 if issc: ! y = _deepcopy_atomic(x, memo) else: ! copier = getattr(x, "__deepcopy__", None) ! if copier: ! y = copier(memo) ! else: ! reductor = dispatch_table.get(cls) ! if reductor: ! rv = reductor(x) ! else: ! reductor = getattr(x, "__reduce_ex__", None) ! if reductor: ! rv = reductor(2) ! else: ! reductor = getattr(x, "__reduce__", None) ! if reductor: ! rv = reductor() ! else: ! raise Error( ! "un(deep)copyable object of type %s" % cls) ! y = _reconstruct(x, rv, 1, memo) memo[d] = y Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** copy_reg.py 18 Feb 2003 22:05:11 -0000 1.21 --- copy_reg.py 19 Feb 2003 01:19:27 -0000 1.22 *************** *** 114,120 **** def _reduce_ex(obj, proto=0): obj_reduce = getattr(obj, "__reduce__", None) ! if obj_reduce and obj.__class__.__reduce__ is not object.__reduce__: ! return obj_reduce() ! elif proto < 2: return _reduce(obj) else: --- 114,125 ---- def _reduce_ex(obj, proto=0): obj_reduce = getattr(obj, "__reduce__", None) ! # XXX This fails in test_copy.py line 61 ! if obj_reduce: ! try: ! if obj.__class__.__reduce__ is not object.__reduce__: ! return obj_reduce() ! except AttributeError: ! pass ! if proto < 2: return _reduce(obj) else: From gvanrossum@users.sourceforge.net Wed Feb 19 01:20:42 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 17:20:42 -0800 Subject: [Python-checkins] python/dist/src/Lib copy.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv24642 Modified Files: copy.py Log Message: Remove now unused _better_reduce. Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** copy.py 19 Feb 2003 01:19:27 -0000 1.37 --- copy.py 19 Feb 2003 01:20:40 -0000 1.38 *************** *** 50,54 **** import types ! from copy_reg import _better_reduce, dispatch_table class Error(Exception): --- 50,54 ---- import types ! from copy_reg import dispatch_table class Error(Exception): From gvanrossum@users.sourceforge.net Wed Feb 19 01:45:16 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 17:45:16 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.139,2.140 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2051 Modified Files: cPickle.c Log Message: Use __reduce_ex__. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.139 retrieving revision 2.140 diff -C2 -d -r2.139 -r2.140 *** cPickle.c 18 Feb 2003 20:50:45 -0000 2.139 --- cPickle.c 19 Feb 2003 01:45:13 -0000 2.140 *************** *** 120,131 **** static PyObject *two_tuple; - /* object.__reduce__, the default reduce callable. */ - static PyObject *object_reduce; - - /* copy_reg._better_reduce, the protocol 2 reduction function. */ - static PyObject *better_reduce; - static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, *write_str, *append_str, *read_str, *readline_str, *__main___str, *__basicnew___str, --- 120,126 ---- static PyObject *two_tuple; static PyObject *__class___str, *__getinitargs___str, *__dict___str, *__getstate___str, *__setstate___str, *__name___str, *__reduce___str, + *__reduce_ex___str, *write_str, *append_str, *read_str, *readline_str, *__main___str, *__basicnew___str, *************** *** 2506,2551 **** } ! /* Get a reduction callable. This may come from ! * copy_reg.dispatch_table, the object's __reduce__ method, ! * the default object.__reduce__, or copy_reg._better_reduce. */ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type); if (__reduce__ != NULL) { Py_INCREF(__reduce__); } else { ! /* Check for a __reduce__ method. ! * Subtle: get the unbound method from the class, so that ! * protocol 2 can override the default __reduce__ that all ! * classes inherit from object. ! * XXX object.__reduce__ should really be rewritten so that ! * XXX we don't need to call back into Python code here ! * XXX (better_reduce), but no time to do that. ! */ ! __reduce__ = PyObject_GetAttr((PyObject *)type, ! __reduce___str); ! if (__reduce__ == NULL) { ! PyErr_Clear(); ! PyErr_SetObject(UnpickleableError, args); ! goto finally; } ! ! if (self->proto >= 2 && __reduce__ == object_reduce) { ! /* Proto 2 can do better than the default. */ ! Py_DECREF(__reduce__); ! Py_INCREF(better_reduce); ! __reduce__ = better_reduce; } } - /* Call the reduction callable, setting t to the result. */ - assert(__reduce__ != NULL); - assert(t == NULL); - Py_INCREF(args); - ARG_TUP(self, args); - if (self->arg) { - t = PyObject_Call(__reduce__, self->arg, NULL); - FREE_ARG_TUP(self); - } if (t == NULL) goto finally; --- 2501,2548 ---- } ! /* Get a reduction callable, and call it. This may come from ! * copy_reg.dispatch_table, the object's __reduce_ex__ method, ! * or the object's __reduce__ method. */ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type); if (__reduce__ != NULL) { Py_INCREF(__reduce__); + Py_INCREF(args); + ARG_TUP(self, args); + if (self->arg) { + t = PyObject_Call(__reduce__, self->arg, NULL); + FREE_ARG_TUP(self); + } } else { ! /* Check for a __reduce_ex__ method. */ ! __reduce__ = PyObject_GetAttr(args, __reduce_ex___str); ! if (__reduce__ != NULL) { ! t = PyInt_FromLong(self->proto); ! if (t != NULL) { ! ARG_TUP(self, t); ! t = NULL; ! if (self->arg) { ! t = PyObject_Call(__reduce__, ! self->arg, NULL); ! FREE_ARG_TUP(self); ! } ! } } ! else { ! PyErr_Clear(); ! /* Check for a __reduce__ method. */ ! __reduce__ = PyObject_GetAttr(args, __reduce___str); ! if (__reduce__ != NULL) { ! t = PyObject_Call(__reduce__, ! empty_tuple, NULL); ! } ! else { ! PyErr_SetObject(UnpickleableError, args); ! goto finally; ! } } } if (t == NULL) goto finally; *************** *** 5591,5594 **** --- 5588,5592 ---- INIT_STR(__main__); INIT_STR(__reduce__); + INIT_STR(__reduce_ex__); INIT_STR(write); INIT_STR(append); *************** *** 5619,5630 **** if (!extension_cache) return -1; - better_reduce = PyObject_GetAttrString(copy_reg, "_better_reduce"); - if (!better_reduce) return -1; - Py_DECREF(copy_reg); - - object_reduce = PyObject_GetAttrString((PyObject *)&PyBaseObject_Type, - "__reduce__"); - if (object_reduce == NULL) return -1; if (!(empty_tuple = PyTuple_New(0))) --- 5617,5621 ---- From gvanrossum@users.sourceforge.net Wed Feb 19 01:58:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 17:58:56 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv6456 Modified Files: copy_reg.py Log Message: Rename _better_reduce to _reduce_2, to make sure that any code that was still referencing it will fail. Also removed some debug cruft from _reduce_ex. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** copy_reg.py 19 Feb 2003 01:19:27 -0000 1.22 --- copy_reg.py 19 Feb 2003 01:58:53 -0000 1.23 *************** *** 81,85 **** return cls.__new__(cls, *args) ! def _better_reduce(obj): cls = obj.__class__ getnewargs = getattr(obj, "__getnewargs__", None) --- 81,85 ---- return cls.__new__(cls, *args) ! def _reduce_2(obj): cls = obj.__class__ getnewargs = getattr(obj, "__getnewargs__", None) *************** *** 114,128 **** def _reduce_ex(obj, proto=0): obj_reduce = getattr(obj, "__reduce__", None) ! # XXX This fails in test_copy.py line 61 ! if obj_reduce: ! try: ! if obj.__class__.__reduce__ is not object.__reduce__: ! return obj_reduce() ! except AttributeError: ! pass ! if proto < 2: return _reduce(obj) else: ! return _better_reduce(obj) def _slotnames(cls): --- 114,123 ---- def _reduce_ex(obj, proto=0): obj_reduce = getattr(obj, "__reduce__", None) ! if obj_reduce and obj.__class__.__reduce__ is not object.__reduce__: ! return obj_reduce() ! elif proto < 2: return _reduce(obj) else: ! return _reduce_2(obj) def _slotnames(cls): From gvanrossum@users.sourceforge.net Wed Feb 19 02:00:02 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 18:00:02 -0800 Subject: [Python-checkins] python/nondist/peps pep-0307.txt,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv6685 Modified Files: pep-0307.txt Log Message: Document __reduce_ex__. Index: pep-0307.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0307.txt,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** pep-0307.txt 13 Feb 2003 16:08:06 -0000 1.29 --- pep-0307.txt 19 Feb 2003 01:59:59 -0000 1.30 *************** *** 142,157 **** also __getinitargs__, and we're adding __getnewargs__ below.) ! There are two ways to provide __reduce__ functionality: a class ! can implement a __reduce__ method, or a reduce function can be ! declared in copy_reg (copy_reg.dispatch_table maps classes to ! functions). The return values are interpreted exactly the same, ! though, and we'll refer to these collectively as __reduce__. ! IMPORTANT: while a classic class can implement a __reduce__() ! method, pickling its instances ignores the method, so that a classic ! class cannot provide __reduce__ functionality in the sense intended ! here. (The copy_reg dispatch table is not consulted for classic ! classes either.) A classic class must use __getinitargs__ and/or ! __gestate__ to customize pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns --- 142,158 ---- also __getinitargs__, and we're adding __getnewargs__ below.) ! There are several ways to provide __reduce__ functionality: a ! class can implement a __reduce__ method or a __reduce_ex__ method ! (see next section), or a reduce function can be declared in ! copy_reg (copy_reg.dispatch_table maps classes to functions). The ! return values are interpreted exactly the same, though, and we'll ! refer to these collectively as __reduce__. ! IMPORTANT: pickling of classic class instances does not look for a ! __reduce__ or __reduce_ex__ method or a reduce function in the ! copy_reg dispatch table, so that a classic class cannot provide ! __reduce__ functionality in the sense intended here. A classic ! class must use __getinitargs__ and/or __gestate__ to customize ! pickling. These are described below. __reduce__ must return either a string or a tuple. If it returns *************** *** 246,249 **** --- 247,266 ---- + The __reduce_ex__ API + + It is sometimes useful to know the protocol version when + implementing __reduce__. This can be done by implementing a + method named __reduce_ex__ instead of __reduce__. __reduce_ex__, + when it exists, is called in preference over __reduce__ (you may + still provide __reduce__ for backwards compatibility). The + __reduce_ex__ method will be called with a single integer + argument, the protocol version. + + The 'object' class implements both __reduce__ and __reduce_ex__; + however, if a subclass overrides __reduce__ but not __reduce_ex__, + the __reduce_ex__ implementation detects this and calls + __reduce__. + + Customizing pickling absent a __reduce__ implementation *************** *** 662,665 **** --- 679,685 ---- In Python 2.3, several changes are made to the copy module: + + - __reduce_ex__ is supported (and always called with 2 as the + protocol version argument). - The four- and five-argument return values of __reduce__ are From tim_one@users.sourceforge.net Wed Feb 19 02:35:10 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 18:35:10 -0800 Subject: [Python-checkins] python/dist/src/Lib/test re_tests.py,1.32,1.33 regrtest.py,1.127,1.128 test_aepack.py,1.1,1.2 test_bisect.py,1.6,1.7 test_builtin.py,1.13,1.14 test_codeccallbacks.py,1.9,1.10 test_datetime.py,1.39,1.40 test_descr.py,1.184,1.185 test_dummy_thread.py,1.1,1.2 test_dummy_threading.py,1.1,1.2 test_locale.py,1.6,1.7 test_macfs.py,1.2,1.3 test_macostools.py,1.3,1.4 test_parser.py,1.15,1.16 test_string.py,1.22,1.23 test_sys.py,1.3,1.4 test_tarfile.py,1.2,1.3 test_userlist.py,1.7,1.8 test_xpickle.py,1.2,1.3 test_zipimport.py,1.6,1.7 test_zlib.py,1.20,1.21 tokenize_tests.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv17279/test Modified Files: re_tests.py regrtest.py test_aepack.py test_bisect.py test_builtin.py test_codeccallbacks.py test_datetime.py test_descr.py test_dummy_thread.py test_dummy_threading.py test_locale.py test_macfs.py test_macostools.py test_parser.py test_string.py test_sys.py test_tarfile.py test_userlist.py test_xpickle.py test_zipimport.py test_zlib.py tokenize_tests.py Log Message: Whitespace normalization. Index: re_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/re_tests.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** re_tests.py 13 Feb 2003 03:01:18 -0000 1.32 --- re_tests.py 19 Feb 2003 02:35:04 -0000 1.33 *************** *** 554,558 **** ('(?=100000: ! v += (100000, 500000, 1000000) s = u"".join([unichr(x) for x in v]) codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors) --- 533,537 ---- v = (1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000) if sys.maxunicode>=100000: ! v += (100000, 500000, 1000000) s = u"".join([unichr(x) for x in v]) codecs.register_error("test.xmlcharrefreplace", codecs.xmlcharrefreplace_errors) Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_datetime.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** test_datetime.py 8 Feb 2003 03:46:31 -0000 1.39 --- test_datetime.py 19 Feb 2003 02:35:05 -0000 1.40 *************** *** 104,110 **** self.failUnless(type(orig) is tzinfo) for pickler, unpickler, proto in pickle_choices: ! green = pickler.dumps(orig, proto) ! derived = unpickler.loads(green) ! self.failUnless(type(derived) is tzinfo) def test_pickling_subclass(self): --- 104,110 ---- self.failUnless(type(orig) is tzinfo) for pickler, unpickler, proto in pickle_choices: ! green = pickler.dumps(orig, proto) ! derived = unpickler.loads(green) ! self.failUnless(type(derived) is tzinfo) def test_pickling_subclass(self): *************** *** 117,126 **** self.assertEqual(orig.tzname(None), 'cookie') for pickler, unpickler, proto in pickle_choices: ! green = pickler.dumps(orig, proto) ! derived = unpickler.loads(green) ! self.failUnless(isinstance(derived, tzinfo)) ! self.failUnless(type(derived) is PicklableFixedOffset) ! self.assertEqual(derived.utcoffset(None), offset) ! self.assertEqual(derived.tzname(None), 'cookie') ############################################################################# --- 117,126 ---- self.assertEqual(orig.tzname(None), 'cookie') for pickler, unpickler, proto in pickle_choices: ! green = pickler.dumps(orig, proto) ! derived = unpickler.loads(green) ! self.failUnless(isinstance(derived, tzinfo)) ! self.failUnless(type(derived) is PicklableFixedOffset) ! self.assertEqual(derived.utcoffset(None), offset) ! self.assertEqual(derived.tzname(None), 'cookie') ############################################################################# *************** *** 518,523 **** self.assertEqual(d, fromord) if hasattr(fromord, "hour"): ! # if we're checking something fancier than a date, verify ! # the extra fields have been zeroed out self.assertEqual(fromord.hour, 0) self.assertEqual(fromord.minute, 0) --- 518,523 ---- self.assertEqual(d, fromord) if hasattr(fromord, "hour"): ! # if we're checking something fancier than a date, verify ! # the extra fields have been zeroed out self.assertEqual(fromord.hour, 0) self.assertEqual(fromord.minute, 0) Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.184 retrieving revision 1.185 diff -C2 -d -r1.184 -r1.185 *** test_descr.py 13 Feb 2003 16:25:05 -0000 1.184 --- test_descr.py 19 Feb 2003 02:35:05 -0000 1.185 *************** *** 1838,1842 **** if not self: return 'EPS' ! return self # sys.stdout needs to be the original to trigger the recursion bug --- 1838,1842 ---- if not self: return 'EPS' ! return self # sys.stdout needs to be the original to trigger the recursion bug Index: test_dummy_thread.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_dummy_thread.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_dummy_thread.py 30 Dec 2002 22:30:22 -0000 1.1 --- test_dummy_thread.py 19 Feb 2003 02:35:05 -0000 1.2 *************** *** 32,36 **** self.failUnless(not self.lock.locked(), "Lock object did not release properly.") ! def test_improper_release(self): #Make sure release of an unlocked thread raises _thread.error --- 32,36 ---- self.failUnless(not self.lock.locked(), "Lock object did not release properly.") ! def test_improper_release(self): #Make sure release of an unlocked thread raises _thread.error *************** *** 59,63 **** self.failUnless(self.lock.acquire(1) is True, "Unconditional locking did not return True.") ! def test_uncond_acquire_blocking(self): #Make sure that unconditional acquiring of a locked lock blocks. --- 59,63 ---- self.failUnless(self.lock.acquire(1) is True, "Unconditional locking did not return True.") ! def test_uncond_acquire_blocking(self): #Make sure that unconditional acquiring of a locked lock blocks. *************** *** 126,130 **** "Argument passing for thread creation using both tuple" " and kwargs failed") ! def test_multi_creation(self): #Make sure multiple threads can be created. --- 126,130 ---- "Argument passing for thread creation using both tuple" " and kwargs failed") ! def test_multi_creation(self): #Make sure multiple threads can be created. *************** *** 133,137 **** time.sleep(delay) queue.put(_thread.get_ident()) ! thread_count = 5 delay = 1.5 --- 133,137 ---- time.sleep(delay) queue.put(_thread.get_ident()) ! thread_count = 5 delay = 1.5 *************** *** 148,152 **** print 'done' self.failUnless(testing_queue.qsize() == thread_count, ! "Not all %s threads executed properly after %s sec." % (thread_count, delay)) --- 148,152 ---- print 'done' self.failUnless(testing_queue.qsize() == thread_count, ! "Not all %s threads executed properly after %s sec." % (thread_count, delay)) Index: test_dummy_threading.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_dummy_threading.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_dummy_threading.py 30 Dec 2002 22:30:22 -0000 1.1 --- test_dummy_threading.py 19 Feb 2003 02:35:05 -0000 1.2 *************** *** 10,14 **** class TestThread(_threading.Thread): ! def run(self): global running --- 10,14 ---- class TestThread(_threading.Thread): ! def run(self): global running *************** *** 55,59 **** global threads threads = [] ! starttasks() --- 55,59 ---- global threads threads = [] ! starttasks() Index: test_locale.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_locale.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_locale.py 30 Dec 2002 23:02:55 -0000 1.6 --- test_locale.py 19 Feb 2003 02:35:05 -0000 1.7 *************** *** 4,8 **** if sys.platform == 'darwin': ! raise TestSkipped("Locale support on MacOSX is minimal and cannot be tested") oldlocale = locale.setlocale(locale.LC_NUMERIC) --- 4,8 ---- if sys.platform == 'darwin': ! raise TestSkipped("Locale support on MacOSX is minimal and cannot be tested") oldlocale = locale.setlocale(locale.LC_NUMERIC) Index: test_macfs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_macfs.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_macfs.py 5 Feb 2003 11:14:16 -0000 1.2 --- test_macfs.py 19 Feb 2003 02:35:05 -0000 1.3 *************** *** 23,31 **** fss = macfs.FSSpec(test_support.TESTFN) self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname()) ! def test_fsref(self): fsr = macfs.FSRef(test_support.TESTFN) self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname()) ! def test_coercion(self): fss = macfs.FSSpec(test_support.TESTFN) --- 23,31 ---- fss = macfs.FSSpec(test_support.TESTFN) self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname()) ! def test_fsref(self): fsr = macfs.FSRef(test_support.TESTFN) self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname()) ! def test_coercion(self): fss = macfs.FSSpec(test_support.TESTFN) *************** *** 35,39 **** self.assertEqual(fss.as_pathname(), fss2.as_pathname()) self.assertEqual(fsr.as_pathname(), fsr2.as_pathname()) ! def test_dates(self): import time --- 35,39 ---- self.assertEqual(fss.as_pathname(), fss2.as_pathname()) self.assertEqual(fsr.as_pathname(), fsr2.as_pathname()) ! def test_dates(self): import time *************** *** 43,47 **** dates = fss.GetDates() self.assertEqual(dates, (now, now-1, now-2)) ! def test_ctor_type(self): fss = macfs.FSSpec(test_support.TESTFN) --- 43,47 ---- dates = fss.GetDates() self.assertEqual(dates, (now, now-1, now-2)) ! def test_ctor_type(self): fss = macfs.FSSpec(test_support.TESTFN) *************** *** 49,53 **** filecr, filetp = fss.GetCreatorType() self.assertEqual((filecr, filetp), ('Pyth', 'TEXT')) ! def test_alias(self): fss = macfs.FSSpec(test_support.TESTFN) --- 49,53 ---- filecr, filetp = fss.GetCreatorType() self.assertEqual((filecr, filetp), ('Pyth', 'TEXT')) ! def test_alias(self): fss = macfs.FSSpec(test_support.TESTFN) *************** *** 55,64 **** fss2, changed = alias.Resolve() self.assertEqual(changed, 0) ! self.assertEqual(fss.as_pathname(), fss2.as_pathname()) ! ! def test_fss_alias(self): fss = macfs.FSSpec(test_support.TESTFN) ! def test_main(): --- 55,64 ---- fss2, changed = alias.Resolve() self.assertEqual(changed, 0) ! self.assertEqual(fss.as_pathname(), fss2.as_pathname()) ! ! def test_fss_alias(self): fss = macfs.FSSpec(test_support.TESTFN) ! def test_main(): Index: test_macostools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_macostools.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_macostools.py 5 Feb 2003 11:14:15 -0000 1.3 --- test_macostools.py 19 Feb 2003 02:35:06 -0000 1.4 *************** *** 30,34 **** except: pass ! def compareData(self): fp = open(test_support.TESTFN, 'r') --- 30,34 ---- except: pass ! def compareData(self): fp = open(test_support.TESTFN, 'r') *************** *** 49,57 **** return 'Resource forks differ' return '' ! def test_touched(self): # This really only tests that nothing unforeseen happens. macostools.touched(test_support.TESTFN) ! def test_copy(self): try: --- 49,57 ---- return 'Resource forks differ' return '' ! def test_touched(self): # This really only tests that nothing unforeseen happens. macostools.touched(test_support.TESTFN) ! def test_copy(self): try: *************** *** 61,65 **** macostools.copy(test_support.TESTFN, TESTFN2) self.assertEqual(self.compareData(), '') ! def test_mkalias(self): try: --- 61,65 ---- macostools.copy(test_support.TESTFN, TESTFN2) self.assertEqual(self.compareData(), '') ! def test_mkalias(self): try: *************** *** 70,74 **** fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ! def test_mkalias_relative(self): try: --- 70,74 ---- fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ! def test_mkalias_relative(self): try: *************** *** 79,84 **** fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ! ! def test_main(): test_support.run_unittest(TestMacostools) --- 79,84 ---- fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ! ! def test_main(): test_support.run_unittest(TestMacostools) Index: test_parser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_parser.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_parser.py 10 Feb 2003 01:54:06 -0000 1.15 --- test_parser.py 19 Feb 2003 02:35:06 -0000 1.16 *************** *** 371,375 **** (282, (1, 'foo'))), (4, ''))), (4, ''), ! (0, '')) self.check_bad_tree(tree, "malformed global ast") --- 371,375 ---- (282, (1, 'foo'))), (4, ''))), (4, ''), ! (0, '')) self.check_bad_tree(tree, "malformed global ast") Index: test_string.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_string.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** test_string.py 30 Dec 2002 10:50:32 -0000 1.22 --- test_string.py 19 Feb 2003 02:35:06 -0000 1.23 *************** *** 83,85 **** #print result pass - --- 83,84 ---- Index: test_sys.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sys.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_sys.py 18 Feb 2003 15:22:10 -0000 1.3 --- test_sys.py 19 Feb 2003 02:35:06 -0000 1.4 *************** *** 128,143 **** def test_setcheckinterval(self): ! self.assertRaises(TypeError, sys.setcheckinterval) ! sys.setcheckinterval(120) ! sys.setcheckinterval(100) def test_recursionlimit(self): ! self.assertRaises(TypeError, sys.getrecursionlimit, 42) ! oldlimit = sys.getrecursionlimit() ! self.assertRaises(TypeError, sys.setrecursionlimit) ! self.assertRaises(ValueError, sys.setrecursionlimit, -42) ! sys.setrecursionlimit(10000) ! self.assertEqual(sys.getrecursionlimit(), 10000) ! sys.setrecursionlimit(oldlimit) def test_getwindowsversion(self): --- 128,143 ---- def test_setcheckinterval(self): ! self.assertRaises(TypeError, sys.setcheckinterval) ! sys.setcheckinterval(120) ! sys.setcheckinterval(100) def test_recursionlimit(self): ! self.assertRaises(TypeError, sys.getrecursionlimit, 42) ! oldlimit = sys.getrecursionlimit() ! self.assertRaises(TypeError, sys.setrecursionlimit) ! self.assertRaises(ValueError, sys.setrecursionlimit, -42) ! sys.setrecursionlimit(10000) ! self.assertEqual(sys.getrecursionlimit(), 10000) ! sys.setrecursionlimit(oldlimit) def test_getwindowsversion(self): Index: test_tarfile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_tarfile.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_tarfile.py 17 Feb 2003 14:51:41 -0000 1.2 --- test_tarfile.py 19 Feb 2003 02:35:06 -0000 1.3 *************** *** 22,25 **** --- 22,26 ---- testtar = path("testtar.tar") + print testtar tempdir = path("testtar.dir") tempname = path("testtar.tmp") Index: test_userlist.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_userlist.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** test_userlist.py 13 Feb 2003 18:07:43 -0000 1.7 --- test_userlist.py 19 Feb 2003 02:35:06 -0000 1.8 *************** *** 259,261 **** if __name__ == "__main__": test_main() - --- 259,260 ---- Index: test_xpickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_xpickle.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** test_xpickle.py 13 Feb 2003 19:37:19 -0000 1.2 --- test_xpickle.py 19 Feb 2003 02:35:06 -0000 1.3 *************** *** 40,44 **** DumpPickle_LoadCPickle, ): ! suite.addTest(unittest.makeSuite(test)) test_support.run_suite(suite) --- 40,44 ---- DumpPickle_LoadCPickle, ): ! suite.addTest(unittest.makeSuite(test)) test_support.run_suite(suite) Index: test_zipimport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_zipimport.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_zipimport.py 17 Feb 2003 18:05:20 -0000 1.6 --- test_zipimport.py 19 Feb 2003 02:35:06 -0000 1.7 *************** *** 17,25 **** data = marshal.dumps(co) if type(mtime) is type(0.0): ! # Mac mtimes need a bit of special casing ! if mtime < 0x7fffffff: ! mtime = int(mtime) ! else: ! mtime = int(-0x100000000L + long(mtime)) pyc = imp.get_magic() + struct.pack(" Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv17279 Modified Files: cmd.py copy.py os.py trace.py Log Message: Whitespace normalization. Index: cmd.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/cmd.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** cmd.py 6 Feb 2003 01:45:10 -0000 1.35 --- cmd.py 19 Feb 2003 02:35:02 -0000 1.36 *************** *** 80,86 **** """Instantiate a line-oriented interpreter framework. ! The optional argument 'completekey' is the readline name of a ! completion key; it defaults to the Tab key. If completekey is ! not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, --- 80,86 ---- """Instantiate a line-oriented interpreter framework. ! The optional argument 'completekey' is the readline name of a ! completion key; it defaults to the Tab key. If completekey is ! not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** copy.py 19 Feb 2003 01:20:40 -0000 1.38 --- copy.py 19 Feb 2003 02:35:02 -0000 1.39 *************** *** 94,98 **** return _reconstruct(x, rv, 0) ! _copy_dispatch = d = {} --- 94,98 ---- return _reconstruct(x, rv, 0) ! _copy_dispatch = d = {} Index: os.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/os.py,v retrieving revision 1.67 retrieving revision 1.68 diff -C2 -d -r1.67 -r1.68 *** os.py 14 Feb 2003 19:35:29 -0000 1.67 --- os.py 19 Feb 2003 02:35:03 -0000 1.68 *************** *** 45,49 **** pass import posixpath as path ! import posix __all__.extend(_get_exports_list(posix)) --- 45,49 ---- pass import posixpath as path ! import posix __all__.extend(_get_exports_list(posix)) *************** *** 59,63 **** pass import ntpath as path ! import nt __all__.extend(_get_exports_list(nt)) --- 59,63 ---- pass import ntpath as path ! import nt __all__.extend(_get_exports_list(nt)) *************** *** 76,80 **** else: import os2emxpath as path ! import os2 __all__.extend(_get_exports_list(os2)) --- 76,80 ---- else: import os2emxpath as path ! import os2 __all__.extend(_get_exports_list(os2)) *************** *** 90,94 **** pass import macpath as path ! import mac __all__.extend(_get_exports_list(mac)) --- 90,94 ---- pass import macpath as path ! import mac __all__.extend(_get_exports_list(mac)) *************** *** 105,109 **** # We can use the standard Windows path. import ntpath as path ! import ce __all__.extend(_get_exports_list(ce)) --- 105,109 ---- # We can use the standard Windows path. import ntpath as path ! import ce __all__.extend(_get_exports_list(ce)) *************** *** 119,123 **** pass import riscospath as path ! import riscos __all__.extend(_get_exports_list(riscos)) --- 119,123 ---- pass import riscospath as path ! import riscos __all__.extend(_get_exports_list(riscos)) Index: trace.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/trace.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** trace.py 18 Feb 2003 15:06:17 -0000 1.1 --- trace.py 19 Feb 2003 02:35:03 -0000 1.2 *************** *** 147,151 **** class CoverageResults: def __init__(self, counts=None, calledfuncs=None, infile=None, ! outfile=None): self.counts = counts if self.counts is None: --- 147,151 ---- class CoverageResults: def __init__(self, counts=None, calledfuncs=None, infile=None, ! outfile=None): self.counts = counts if self.counts is None: *************** *** 165,169 **** # backwards compatibility for old trace.py after # Zooko touched it but before calledfuncs --Zooko ! # 2001-10-24 self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: --- 165,169 ---- # backwards compatibility for old trace.py after # Zooko touched it but before calledfuncs --Zooko ! # 2001-10-24 self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: *************** *** 174,178 **** except pickle.UnpicklingError: # backwards compatibility for old trace.py before ! # Zooko touched it --Zooko 2001-10-24 self.update(self.__class__(marshal.load(open(self.infile)))) --- 174,178 ---- except pickle.UnpicklingError: # backwards compatibility for old trace.py before ! # Zooko touched it --Zooko 2001-10-24 self.update(self.__class__(marshal.load(open(self.infile)))) *************** *** 188,192 **** # backwards compatibility for abortive attempt to # stuff calledfuncs into self.counts, by Zooko ! # --Zooko 2001-10-24 counts[key] = counts.get(key, 0) + other_counts[key] --- 188,192 ---- # backwards compatibility for abortive attempt to # stuff calledfuncs into self.counts, by Zooko ! # --Zooko 2001-10-24 counts[key] = counts.get(key, 0) + other_counts[key] *************** *** 407,422 **** """ @param count true iff it should count number of times each ! line is executed @param trace true iff it should print out each line that is ! being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides ! `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore ! all of the (recursive) contents of @param infile file from which to read stored counts to be ! added into the results @param outfile file in which to write the results """ --- 407,422 ---- """ @param count true iff it should count number of times each ! line is executed @param trace true iff it should print out each line that is ! being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides ! `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore ! all of the (recursive) contents of @param infile file from which to read stored counts to be ! added into the results @param outfile file in which to write the results """ *************** *** 517,533 **** # `getfilename(frame)' to use in place of the presumably # heavier `getframeinfo()'. --Zooko 2001-10-14 ! filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 ! # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. # --Zooko 2001-10-14 ! bname = self.pathtobasename.get(filename) if bname is None: ! # Using setdefault faster than two separate lines? # --Zooko 2001-10-14 --- 517,533 ---- # `getfilename(frame)' to use in place of the presumably # heavier `getframeinfo()'. --Zooko 2001-10-14 ! filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 ! # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. # --Zooko 2001-10-14 ! bname = self.pathtobasename.get(filename) if bname is None: ! # Using setdefault faster than two separate lines? # --Zooko 2001-10-14 *************** *** 554,558 **** filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame) ! # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. --- 554,558 ---- filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame) ! # XXX not convinced that this memoizing is a performance # win -- I don't know enough about Python guts to tell. From tim_one@users.sourceforge.net Wed Feb 19 02:41:46 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 18:41:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_tarfile.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19108/python/Lib/test Modified Files: test_tarfile.py Log Message: Removed debugging print in test_tarfile. In the Windows installer, continued the endless battle to copy over files with new one-shot extensions. Index: test_tarfile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_tarfile.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_tarfile.py 19 Feb 2003 02:35:06 -0000 1.3 --- test_tarfile.py 19 Feb 2003 02:41:43 -0000 1.4 *************** *** 22,26 **** testtar = path("testtar.tar") - print testtar tempdir = path("testtar.dir") tempname = path("testtar.tmp") --- 22,25 ---- From tim_one@users.sourceforge.net Wed Feb 19 02:41:46 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 18:41:46 -0800 Subject: [Python-checkins] python/dist/src/PCbuild python20.wse,1.117,1.118 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv19108/python/PCbuild Modified Files: python20.wse Log Message: Removed debugging print in test_tarfile. In the Windows installer, continued the endless battle to copy over files with new one-shot extensions. Index: python20.wse =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/python20.wse,v retrieving revision 1.117 retrieving revision 1.118 diff -C2 -d -r1.117 -r1.118 *** python20.wse 18 Feb 2003 21:58:53 -0000 1.117 --- python20.wse 19 Feb 2003 02:41:44 -0000 1.118 *************** *** 2321,2324 **** --- 2321,2342 ---- Flags=0000000000000010 end + item: Install File + Source=..\lib\test\*.bz2 + Destination=%MAINDIR%\Lib\test + Description=Python Test files + Flags=0000000000000010 + end + item: Install File + Source=..\lib\test\*.tar + Destination=%MAINDIR%\Lib\test + Description=Python Test files + Flags=0000000000000010 + end + item: Install File + Source=..\lib\test\*.gz + Destination=%MAINDIR%\Lib\test + Description=Python Test files + Flags=0000000000000010 + end item: Remark end From tim_one@users.sourceforge.net Wed Feb 19 02:44:15 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 18 Feb 2003 18:44:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/test tokenize_tests.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19963/Lib/test Modified Files: tokenize_tests.py Log Message: Reverted whitespace normalization on this file. I should really change this thing so it doesn't rely on being unnormalized. (That's the editorial "I", if anyone's listening .) Index: tokenize_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/tokenize_tests.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** tokenize_tests.py 19 Feb 2003 02:35:07 -0000 1.6 --- tokenize_tests.py 19 Feb 2003 02:44:12 -0000 1.7 *************** *** 1,4 **** # Tests for the 'tokenize' module. ! # Large bits stolen from test_grammar.py. # Comments --- 1,4 ---- # Tests for the 'tokenize' module. ! # Large bits stolen from test_grammar.py. # Comments *************** *** 130,144 **** x = 2 if 1: ! x = 2 if 1: while 0: ! if 0: ! x = 2 ! x = 2 if 0: ! if 2: ! while 0: ! if 1: ! x = 2 # Operators --- 130,144 ---- x = 2 if 1: ! x = 2 if 1: while 0: ! if 0: ! x = 2 ! x = 2 if 0: ! if 2: ! while 0: ! if 1: ! x = 2 # Operators *************** *** 173,174 **** --- 173,175 ---- import sys, time x = sys.modules['time'].time() + From gvanrossum@users.sourceforge.net Wed Feb 19 03:19:32 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 19:19:32 -0800 Subject: [Python-checkins] python/dist/src/Objects object.c,2.198,2.199 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv30040 Modified Files: object.c Log Message: PyObject_Generic{Get,Set}Attr: Don't access tp_descr_{get,set} of a descriptor without checking the flag bits of the descriptor's type. While we know that the main type (the type of the object whose attribute is being accessed) has all the right flag bits (or else PyObject_Generic{Get,Set}Attr wouldn't be called), we don't know that for its class attributes! Will backport to 2.2. Index: object.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v retrieving revision 2.198 retrieving revision 2.199 diff -C2 -d -r2.198 -r2.199 *** object.c 18 Feb 2003 16:40:09 -0000 2.198 --- object.c 19 Feb 2003 03:19:29 -0000 2.199 *************** *** 1363,1367 **** f = NULL; ! if (descr != NULL) { f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { --- 1363,1368 ---- f = NULL; ! if (descr != NULL && ! PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { *************** *** 1455,1459 **** descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL) { f = descr->ob_type->tp_descr_set; if (f != NULL && PyDescr_IsData(descr)) { --- 1456,1461 ---- descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL && ! PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { f = descr->ob_type->tp_descr_set; if (f != NULL && PyDescr_IsData(descr)) { From gvanrossum@users.sourceforge.net Wed Feb 19 03:21:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 19:21:23 -0800 Subject: [Python-checkins] python/dist/src/Objects object.c,2.162.6.9,2.162.6.10 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv30436 Modified Files: Tag: release22-maint object.c Log Message: Backport of rev 2.199 from trunk. PyObject_Generic{Get,Set}Attr: Don't access tp_descr_{get,set} of a descriptor without checking the flag bits of the descriptor's type. While we know that the main type (the type of the object whose attribute is being accessed) has all the right flag bits (or else PyObject_Generic{Get,Set}Attr wouldn't be called), we don't know that for its class attributes! Index: object.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v retrieving revision 2.162.6.9 retrieving revision 2.162.6.10 diff -C2 -d -r2.162.6.9 -r2.162.6.10 *** object.c 13 Jan 2003 20:17:04 -0000 2.162.6.9 --- object.c 19 Feb 2003 03:21:21 -0000 2.162.6.10 *************** *** 1260,1264 **** descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL) { f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { --- 1260,1265 ---- descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL && ! PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { *************** *** 1334,1338 **** descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL) { f = descr->ob_type->tp_descr_set; if (f != NULL && PyDescr_IsData(descr)) { --- 1335,1340 ---- descr = _PyType_Lookup(tp, name); f = NULL; ! if (descr != NULL && ! PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) { f = descr->ob_type->tp_descr_set; if (f != NULL && PyDescr_IsData(descr)) { From gvanrossum@users.sourceforge.net Wed Feb 19 03:52:50 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 18 Feb 2003 19:52:50 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.61,1.337.2.4.2.62 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv6993 Modified Files: Tag: release22-maint NEWS Log Message: Backport of rev 2.199 from trunk. PyObject_Generic{Get,Set}Attr: Don't access tp_descr_{get,set} of a descriptor without checking the flag bits of the descriptor's type. While we know that the main type (the type of the object whose attribute is being accessed) has all the right flag bits (or else PyObject_Generic{Get,Set}Attr wouldn't be called), we don't know that for its class attributes! Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.61 retrieving revision 1.337.2.4.2.62 diff -C2 -d -r1.337.2.4.2.61 -r1.337.2.4.2.62 *** NEWS 13 Feb 2003 17:06:02 -0000 1.337.2.4.2.61 --- NEWS 19 Feb 2003 03:52:47 -0000 1.337.2.4.2.62 *************** *** 3,6 **** --- 3,11 ---- ============================ + - Fixed two places in PyObject_Generic{Get,Set}Attr() where the + tp_descr_{get,set} slot of a descriptor's type was accessed without + checking tp_flags whether those slots actually exist. This could + cause segfaults in Zope. + - The imp module now has ways to acquire and release the "import lock": imp.acquire_lock() and imp.release_lock(). Note: this is a From mhammond@users.sourceforge.net Wed Feb 19 04:08:29 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Tue, 18 Feb 2003 20:08:29 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.285,2.286 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv10940 Modified Files: posixmodule.c Log Message: os.mkdir() would crash with a Unicode filename and mode param. Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.285 retrieving revision 2.286 diff -C2 -d -r2.285 -r2.286 *** posixmodule.c 17 Feb 2003 18:17:03 -0000 2.285 --- posixmodule.c 19 Feb 2003 04:08:27 -0000 2.286 *************** *** 1864,1868 **** if (unicode_file_names()) { PyUnicodeObject *po; ! if (PyArg_ParseTuple(args, "U|i:mkdir", &po)) { Py_BEGIN_ALLOW_THREADS /* PyUnicode_AS_UNICODE OK without thread lock as --- 1864,1868 ---- if (unicode_file_names()) { PyUnicodeObject *po; ! if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { Py_BEGIN_ALLOW_THREADS /* PyUnicode_AS_UNICODE OK without thread lock as From jackjansen@users.sourceforge.net Wed Feb 19 10:37:11 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Wed, 19 Feb 2003 02:37:11 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX/PythonLauncher factorySettings.plist,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher In directory sc8-pr-cvs1:/tmp/cvs-serv26228/PythonLauncher Modified Files: factorySettings.plist Log Message: Use pythonw as the default interpreter also for .py scripts (overridable by the user), as this will cause the least surprises with scripts brought over from other unixen. Suggested by Kevin Altis. Index: factorySettings.plist =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/PythonLauncher/factorySettings.plist,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** factorySettings.plist 17 Feb 2003 15:40:00 -0000 1.3 --- factorySettings.plist 19 Feb 2003 10:37:08 -0000 1.4 *************** *** 38,45 **** interpreter_list - /usr/local/bin/python - /sw/bin/python - /Library/Frameworks/Python.framework/Versions/Current/bin/python - /usr/bin/python /usr/local/bin/pythonw /sw/bin/pythonw --- 38,41 ---- *************** *** 47,50 **** --- 43,50 ---- /usr/bin/pythonw /Applications/MacPython-OSX/python-additions/Python.app/Contents/MacOS/python + /usr/local/bin/python + /sw/bin/python + /Library/Frameworks/Python.framework/Versions/Current/bin/python + /usr/bin/python honourhashbang *************** *** 69,72 **** --- 69,77 ---- interpreter_list + /usr/local/bin/pythonw + /sw/bin/pythonw + /Library/Frameworks/Python.framework/Versions/Current/Resources/Python.app/Contents/MacOS/python + /usr/bin/pythonw + /Applications/MacPython-OSX/python-additions/Python.app/Contents/MacOS/python /usr/local/bin/python /sw/bin/python From aimacintyre@users.sourceforge.net Wed Feb 19 12:42:38 2003 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 19 Feb 2003 04:42:38 -0800 Subject: [Python-checkins] python/dist/src/PC/os2emx Makefile,1.8,1.9 python23.def,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/PC/os2emx In directory sc8-pr-cvs1:/tmp/cvs-serv8566 Modified Files: Makefile python23.def Log Message: OS/2 EMX build updates for recent CVS changes Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/os2emx/Makefile,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Makefile 2 Jan 2003 12:38:39 -0000 1.8 --- Makefile 19 Feb 2003 12:42:35 -0000 1.9 *************** *** 394,397 **** --- 394,398 ---- _hotshot \ imageop \ + itertool \ md5 \ operator \ *************** *** 531,534 **** --- 532,542 ---- imageop$(MODULE.EXT): $(OUT)imageop$O $(OUT)imageop_m.def $(PYTHON.IMPLIB) $(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) $(LIBS) + + # itertools needs to be renamed to be useful + itertools$(MODULE.EXT): $(OUT)itertoolsmodule$O $(OUT)itertools_m.def $(PYTHON.IMPLIB) + $(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) $(LIBS) + + itertool$(MODULE.EXT): itertools$(MODULE.EXT) + cp $^ $@ md5$(MODULE.EXT): $(OUT)md5module$O $(OUT)md5c$O $(OUT)md5_m.def $(PYTHON.IMPLIB) Index: python23.def =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/os2emx/python23.def,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** python23.def 31 Dec 2002 11:25:42 -0000 1.5 --- python23.def 19 Feb 2003 12:42:36 -0000 1.6 *************** *** 299,302 **** --- 299,303 ---- "PyFunction_GetCode" "PyFunction_GetGlobals" + "PyFunction_GetModule" "PyFunction_GetDefaults" "PyFunction_SetDefaults" *************** *** 348,351 **** --- 349,354 ---- "PyLong_AsLong" "PyLong_AsUnsignedLong" + "_PyLong_Sign" + "_PyLong_NumBits" "_PyLong_FromByteArray" "_PyLong_AsByteArray" *************** *** 363,367 **** ; From python23_s.lib(methodobject) ! "PyCFunction_New" "PyCFunction_GetFunction" "PyCFunction_GetSelf" --- 366,370 ---- ; From python23_s.lib(methodobject) ! "PyCFunction_NewEx" "PyCFunction_GetFunction" "PyCFunction_GetSelf" *************** *** 371,374 **** --- 374,378 ---- "Py_FindMethod" "PyCFunction_Fini" + "PyCFunction_New" "PyCFunction_Type" *************** *** 388,394 **** "_PyObject_NewVar" "_PyObject_Del" - "PyObject_Print" "PyObject_Str" "PyObject_Repr" "_PyObject_Dump" "PyObject_Unicode" --- 392,398 ---- "_PyObject_NewVar" "_PyObject_Del" "PyObject_Str" "PyObject_Repr" + "PyObject_Print" "_PyObject_Dump" "PyObject_Unicode" *************** *** 667,670 **** --- 671,675 ---- ; From python23_s.lib(ceval) + "PyEval_GetCallStats" "PyEval_InitThreads" "PyEval_AcquireLock" From aimacintyre@users.sourceforge.net Wed Feb 19 12:51:37 2003 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 19 Feb 2003 04:51:37 -0800 Subject: [Python-checkins] python/dist/src/Lib tarfile.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv12330 Modified Files: tarfile.py Log Message: OS/2 has no concept of file ownership, like DOS & MS Windows version prior to NT. EMX has a number of Posix emulation routines, including geteuid() but lacks chown(), so silently skip trying to actually set a file ownership when extracting a file from a tar archive. Index: tarfile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/tarfile.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** tarfile.py 29 Jan 2003 03:49:43 -0000 1.2 --- tarfile.py 19 Feb 2003 12:51:34 -0000 1.3 *************** *** 1506,1510 **** os.lchown(targetpath, u, g) else: ! os.chown(targetpath, u, g) except EnvironmentError, e: raise ExtractError, "could not change owner" --- 1506,1511 ---- os.lchown(targetpath, u, g) else: ! if sys.platform != "os2emx": ! os.chown(targetpath, u, g) except EnvironmentError, e: raise ExtractError, "could not change owner" From akuchling@users.sourceforge.net Wed Feb 19 13:46:22 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 19 Feb 2003 05:46:22 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.122,1.123 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv3004 Modified Files: whatsnew23.tex Log Message: logging.warn() renamed to warning() Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.122 retrieving revision 1.123 diff -C2 -d -r1.122 -r1.123 *** whatsnew23.tex 18 Feb 2003 00:56:56 -0000 1.122 --- whatsnew23.tex 19 Feb 2003 13:46:18 -0000 1.123 *************** *** 446,450 **** logging.debug('Debugging information') logging.info('Informational message') ! logging.warn('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') --- 446,450 ---- logging.debug('Debugging information') logging.info('Informational message') ! logging.warning('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') *************** *** 454,458 **** \begin{verbatim} ! WARN:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down --- 454,458 ---- \begin{verbatim} ! WARNING:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down *************** *** 464,468 **** \method{setLevel()} method on the root logger. ! Notice the \function{warn()} call's use of string formatting operators; all of the functions for logging messages take the arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the --- 464,468 ---- \method{setLevel()} method on the root logger. ! Notice the \function{warning()} call's use of string formatting operators; all of the functions for logging messages take the arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the From akuchling@users.sourceforge.net Wed Feb 19 13:49:37 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 19 Feb 2003 05:49:37 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command register.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv4351 Modified Files: register.py Log Message: [Patch #684398] Rename verbose argument to show-response; don't conditionalize the get_classifiers() call Index: register.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/register.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** register.py 18 Feb 2003 21:28:20 -0000 1.2 --- register.py 19 Feb 2003 13:49:35 -0000 1.3 *************** *** 27,39 **** ('list-classifiers', None, 'list the valid Trove classifiers'), ! ('verbose', None, ! 'display full response from server'), ] ! boolean_options = ['verify', 'verbose', 'list-classifiers'] def initialize_options(self): self.repository = None self.verify = 0 ! self.verbose = 0 self.list_classifiers = 0 --- 27,39 ---- ('list-classifiers', None, 'list the valid Trove classifiers'), ! ('show-response', None, ! 'display full response text from server'), ] ! boolean_options = ['verify', 'show-response', 'list-classifiers'] def initialize_options(self): self.repository = None self.verify = 0 ! self.show_response = 0 self.list_classifiers = 0 *************** *** 233,239 **** 'keywords': meta.get_keywords(), 'platform': meta.get_platforms(), } - if hasattr(meta, 'classifiers'): - data['classifiers'] = meta.get_classifiers() return data --- 233,238 ---- 'keywords': meta.get_keywords(), 'platform': meta.get_platforms(), + 'classifiers': meta.get_classifiers(), } return data *************** *** 278,282 **** result = opener.open(req) except urllib2.HTTPError, e: ! if self.verbose: data = e.fp.read() result = e.code, e.msg --- 277,281 ---- result = opener.open(req) except urllib2.HTTPError, e: ! if self.show_response: data = e.fp.read() result = e.code, e.msg *************** *** 284,291 **** result = 500, str(e) else: ! if self.verbose: data = result.read() result = 200, 'OK' ! if self.verbose: print '-'*75, data, '-'*75 return result --- 283,290 ---- result = 500, str(e) else: ! if self.show_response: data = result.read() result = 200, 'OK' ! if self.show_response: print '-'*75, data, '-'*75 return result From akuchling@users.sourceforge.net Wed Feb 19 14:16:09 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 19 Feb 2003 06:16:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils core.py,1.57,1.58 dist.py,1.61,1.62 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv17324 Modified Files: core.py dist.py Log Message: [Patch #683939] Add download_url field to metadata Index: core.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/core.py,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** core.py 27 Jan 2003 16:30:35 -0000 1.57 --- core.py 19 Feb 2003 14:16:00 -0000 1.58 *************** *** 48,52 **** 'maintainer', 'maintainer_email', 'url', 'license', 'description', 'long_description', 'keywords', ! 'platforms', 'classifiers') # Legal keyword arguments for the Extension constructor --- 48,52 ---- 'maintainer', 'maintainer_email', 'url', 'license', 'description', 'long_description', 'keywords', ! 'platforms', 'classifiers', 'download_url') # Legal keyword arguments for the Extension constructor Index: dist.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/dist.py,v retrieving revision 1.61 retrieving revision 1.62 diff -C2 -d -r1.61 -r1.62 *** dist.py 3 Jan 2003 15:24:36 -0000 1.61 --- dist.py 19 Feb 2003 14:16:01 -0000 1.62 *************** *** 967,971 **** "license", "description", "long_description", "keywords", "platforms", "fullname", "contact", ! "contact_email", "licence", "classifiers") def __init__ (self): --- 967,972 ---- "license", "description", "long_description", "keywords", "platforms", "fullname", "contact", ! "contact_email", "licence", "classifiers", ! "download_url") def __init__ (self): *************** *** 983,986 **** --- 984,988 ---- self.platforms = None self.classifiers = None + self.download_url = None def write_pkg_info (self, base_dir): *************** *** 998,1001 **** --- 1000,1005 ---- pkg_info.write('Author-email: %s\n' % self.get_contact_email() ) pkg_info.write('License: %s\n' % self.get_license() ) + if self.download_url: + pkg_info.write('Download-URL: %s\n' % self.download_url) long_desc = rfc822_escape( self.get_long_description() ) *************** *** 1070,1073 **** --- 1074,1080 ---- def get_classifiers(self): return self.classifiers or [] + + def get_download_url(self): + return self.download_url or "UNKNOWN" # class DistributionMetadata From akuchling@users.sourceforge.net Wed Feb 19 14:27:23 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 19 Feb 2003 06:27:23 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command register.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv22494 Modified Files: register.py Log Message: Include download_url in the data POSTed to the catalog server Index: register.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/register.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** register.py 19 Feb 2003 13:49:35 -0000 1.3 --- register.py 19 Feb 2003 14:27:21 -0000 1.4 *************** *** 234,237 **** --- 234,238 ---- 'platform': meta.get_platforms(), 'classifiers': meta.get_classifiers(), + 'download_url': meta.get_download_url(), } return data From gvanrossum@users.sourceforge.net Wed Feb 19 15:25:12 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:25:12 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.665,1.666 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv17920/Misc Modified Files: NEWS Log Message: - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. (SF patch #664376, by Skip Montanaro.) Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.665 retrieving revision 1.666 diff -C2 -d -r1.665 -r1.666 *** NEWS 18 Feb 2003 23:32:47 -0000 1.665 --- NEWS 19 Feb 2003 15:24:36 -0000 1.666 *************** *** 13,16 **** --- 13,20 ---- ----------------- + - sys.path[0] (the directory from which the script is loaded) is now + turned into an absolute pathname, unless it is the empty string. + (SF patch #664376.) + - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. From gvanrossum@users.sourceforge.net Wed Feb 19 15:25:13 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:25:13 -0800 Subject: [Python-checkins] python/dist/src/Python sysmodule.c,2.113,2.114 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv17920/Python Modified Files: sysmodule.c Log Message: - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. (SF patch #664376, by Skip Montanaro.) Index: sysmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/sysmodule.c,v retrieving revision 2.113 retrieving revision 2.114 diff -C2 -d -r2.113 -r2.114 *** sysmodule.c 5 Feb 2003 23:13:00 -0000 2.113 --- sysmodule.c 19 Feb 2003 15:24:39 -0000 2.114 *************** *** 994,998 **** PySys_SetArgv(int argc, char **argv) { ! #ifdef MS_WINDOWS char fullpath[MAX_PATH]; #endif --- 994,1000 ---- PySys_SetArgv(int argc, char **argv) { ! #if defined(HAVE_REALPATH) ! char fullpath[MAXPATHLEN]; ! #elif defined(MS_WINDOWS) char fullpath[MAX_PATH]; #endif *************** *** 1060,1065 **** } #else /* All other filename syntaxes */ ! if (argc > 0 && argv0 != NULL) p = strrchr(argv0, SEP); if (p != NULL) { #ifndef RISCOS --- 1062,1073 ---- } #else /* All other filename syntaxes */ ! if (argc > 0 && argv0 != NULL) { ! #if defined(HAVE_REALPATH) ! if (realpath(argv0, fullpath)) { ! argv0 = fullpath; ! } ! #endif p = strrchr(argv0, SEP); + } if (p != NULL) { #ifndef RISCOS From gvanrossum@users.sourceforge.net Wed Feb 19 15:25:14 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:25:14 -0800 Subject: [Python-checkins] python/dist/src configure,1.377,1.378 configure.in,1.388,1.389 pyconfig.h.in,1.71,1.72 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv17920 Modified Files: configure configure.in pyconfig.h.in Log Message: - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. (SF patch #664376, by Skip Montanaro.) Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.377 retrieving revision 1.378 diff -C2 -d -r1.377 -r1.378 *** configure 13 Feb 2003 02:11:07 -0000 1.377 --- configure 19 Feb 2003 15:24:41 -0000 1.378 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.387 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.389 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 12096,12099 **** --- 12096,12100 ---- + for ac_func in alarm chown clock confstr ctermid execv \ fchdir flock fork fsync fdatasync fpathconf ftime ftruncate \ *************** *** 12102,12106 **** hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ ! putenv readlink \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setuid setvbuf snprintf \ --- 12103,12107 ---- hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ ! putenv readlink realpath \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setuid setvbuf snprintf \ Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.388 retrieving revision 1.389 diff -C2 -d -r1.388 -r1.389 *** configure.in 13 Feb 2003 02:11:06 -0000 1.388 --- configure.in 19 Feb 2003 15:25:07 -0000 1.389 *************** *** 1844,1848 **** hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ ! putenv readlink \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setuid setvbuf snprintf \ --- 1844,1848 ---- hstrerror inet_aton inet_pton kill killpg lchown lstat mkfifo mknod mktime \ mremap nice pathconf pause plock poll pthread_init \ ! putenv readlink realpath \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setuid setvbuf snprintf \ Index: pyconfig.h.in =================================================================== RCS file: /cvsroot/python/python/dist/src/pyconfig.h.in,v retrieving revision 1.71 retrieving revision 1.72 diff -C2 -d -r1.71 -r1.72 *** pyconfig.h.in 13 Feb 2003 02:11:09 -0000 1.71 --- pyconfig.h.in 19 Feb 2003 15:25:10 -0000 1.72 *************** *** 343,346 **** --- 343,349 ---- #undef HAVE_READLINK + /* Define to 1 if you have the `realpath' function. */ + #undef HAVE_REALPATH + /* Define if you have readline 2.2 */ #undef HAVE_RL_COMPLETION_APPEND_CHARACTER From gvanrossum@users.sourceforge.net Wed Feb 19 15:53:20 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:53:20 -0800 Subject: [Python-checkins] python/dist/src/Python ceval.c,2.349,2.350 pystate.c,2.22,2.23 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv6893/Python Modified Files: ceval.c pystate.c Log Message: - PyEval_GetFrame() is now declared to return a PyFrameObject * instead of a plain PyObject *. (SF patch #686601 by Ben Laurie.) Index: ceval.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/ceval.c,v retrieving revision 2.349 retrieving revision 2.350 diff -C2 -d -r2.349 -r2.350 *** ceval.c 10 Feb 2003 08:21:08 -0000 2.349 --- ceval.c 19 Feb 2003 15:53:16 -0000 2.350 *************** *** 3078,3082 **** PyEval_GetBuiltins(void) { ! PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); if (current_frame == NULL) return PyThreadState_Get()->interp->builtins; --- 3078,3082 ---- PyEval_GetBuiltins(void) { ! PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) return PyThreadState_Get()->interp->builtins; *************** *** 3088,3092 **** PyEval_GetLocals(void) { ! PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); if (current_frame == NULL) return NULL; --- 3088,3092 ---- PyEval_GetLocals(void) { ! PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) return NULL; *************** *** 3098,3102 **** PyEval_GetGlobals(void) { ! PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); if (current_frame == NULL) return NULL; --- 3098,3102 ---- PyEval_GetGlobals(void) { ! PyFrameObject *current_frame = PyEval_GetFrame(); if (current_frame == NULL) return NULL; *************** *** 3105,3113 **** } ! PyObject * PyEval_GetFrame(void) { PyThreadState *tstate = PyThreadState_Get(); ! return _PyThreadState_GetFrame((PyObject *)tstate); } --- 3105,3113 ---- } ! PyFrameObject * PyEval_GetFrame(void) { PyThreadState *tstate = PyThreadState_Get(); ! return _PyThreadState_GetFrame(tstate); } *************** *** 3115,3119 **** PyEval_GetRestricted(void) { ! PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); return current_frame == NULL ? 0 : current_frame->f_restricted; } --- 3115,3119 ---- PyEval_GetRestricted(void) { ! PyFrameObject *current_frame = PyEval_GetFrame(); return current_frame == NULL ? 0 : current_frame->f_restricted; } *************** *** 3122,3126 **** PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { ! PyFrameObject *current_frame = (PyFrameObject *)PyEval_GetFrame(); int result = cf->cf_flags != 0; --- 3122,3126 ---- PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { ! PyFrameObject *current_frame = PyEval_GetFrame(); int result = cf->cf_flags != 0; Index: pystate.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/pystate.c,v retrieving revision 2.22 retrieving revision 2.23 diff -C2 -d -r2.22 -r2.23 *** pystate.c 8 Nov 2002 12:53:11 -0000 2.22 --- pystate.c 19 Feb 2003 15:53:17 -0000 2.23 *************** *** 36,40 **** PyThreadState *_PyThreadState_Current = NULL; ! unaryfunc _PyThreadState_GetFrame = NULL; --- 36,40 ---- PyThreadState *_PyThreadState_Current = NULL; ! PyThreadFrameGetter _PyThreadState_GetFrame = NULL; *************** *** 127,131 **** PyThreadState *tstate = PyMem_NEW(PyThreadState, 1); if (_PyThreadState_GetFrame == NULL) ! _PyThreadState_GetFrame = (unaryfunc)threadstate_getframe; if (tstate != NULL) { --- 127,131 ---- PyThreadState *tstate = PyMem_NEW(PyThreadState, 1); if (_PyThreadState_GetFrame == NULL) ! _PyThreadState_GetFrame = threadstate_getframe; if (tstate != NULL) { From gvanrossum@users.sourceforge.net Wed Feb 19 15:53:46 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:53:46 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.666,1.667 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv6893/Misc Modified Files: NEWS Log Message: - PyEval_GetFrame() is now declared to return a PyFrameObject * instead of a plain PyObject *. (SF patch #686601 by Ben Laurie.) Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.666 retrieving revision 1.667 diff -C2 -d -r1.666 -r1.667 *** NEWS 19 Feb 2003 15:24:36 -0000 1.666 --- NEWS 19 Feb 2003 15:53:11 -0000 1.667 *************** *** 327,330 **** --- 327,333 ---- ----- + - PyEval_GetFrame() is now declared to return a PyFrameObject * + instead of a plain PyObject *. (SF patch #686601.) + - PyNumber_Check() now checks that the object has a nb_int or nb_float slot, rather than simply checking whether it has a non-NULL From gvanrossum@users.sourceforge.net Wed Feb 19 15:53:47 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:53:47 -0800 Subject: [Python-checkins] python/dist/src/Include ceval.h,2.47,2.48 pystate.h,2.21,2.22 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv6893/Include Modified Files: ceval.h pystate.h Log Message: - PyEval_GetFrame() is now declared to return a PyFrameObject * instead of a plain PyObject *. (SF patch #686601 by Ben Laurie.) Index: ceval.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/ceval.h,v retrieving revision 2.47 retrieving revision 2.48 diff -C2 -d -r2.47 -r2.48 *** ceval.h 5 Feb 2003 23:12:56 -0000 2.47 --- ceval.h 19 Feb 2003 15:53:14 -0000 2.48 *************** *** 26,34 **** PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *); PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void); PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void); PyAPI_FUNC(PyObject *) PyEval_GetLocals(void); PyAPI_FUNC(PyObject *) PyEval_GetOwner(void); ! PyAPI_FUNC(PyObject *) PyEval_GetFrame(void); PyAPI_FUNC(int) PyEval_GetRestricted(void); --- 26,36 ---- PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *); + struct _frame; /* Avoid including frameobject.h */ + PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void); PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void); PyAPI_FUNC(PyObject *) PyEval_GetLocals(void); PyAPI_FUNC(PyObject *) PyEval_GetOwner(void); ! PyAPI_FUNC(struct _frame *) PyEval_GetFrame(void); PyAPI_FUNC(int) PyEval_GetRestricted(void); Index: pystate.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pystate.h,v retrieving revision 2.21 retrieving revision 2.22 diff -C2 -d -r2.21 -r2.22 *** pystate.h 8 Nov 2002 12:53:10 -0000 2.21 --- pystate.h 19 Feb 2003 15:53:14 -0000 2.22 *************** *** 108,113 **** PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *); /* hook for PyEval_GetFrame(), requested for Psyco */ ! PyAPI_DATA(unaryfunc) _PyThreadState_GetFrame; #ifdef __cplusplus --- 108,115 ---- PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *); + typedef struct _frame *(*PyThreadFrameGetter)(PyThreadState *self_); + /* hook for PyEval_GetFrame(), requested for Psyco */ ! PyAPI_DATA(PyThreadFrameGetter) _PyThreadState_GetFrame; #ifdef __cplusplus From gvanrossum@users.sourceforge.net Wed Feb 19 15:53:49 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 07:53:49 -0800 Subject: [Python-checkins] python/dist/src/Modules signalmodule.c,2.71,2.72 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv6893/Modules Modified Files: signalmodule.c Log Message: - PyEval_GetFrame() is now declared to return a PyFrameObject * instead of a plain PyObject *. (SF patch #686601 by Ben Laurie.) Index: signalmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/signalmodule.c,v retrieving revision 2.71 retrieving revision 2.72 diff -C2 -d -r2.71 -r2.72 *** signalmodule.c 2 Aug 2002 02:27:13 -0000 2.71 --- signalmodule.c 19 Feb 2003 15:53:15 -0000 2.72 *************** *** 767,771 **** return 0; #endif ! if (!(f = PyEval_GetFrame())) f = Py_None; --- 767,771 ---- return 0; #endif ! if (!(f = (PyObject *)PyEval_GetFrame())) f = Py_None; From fdrake@users.sourceforge.net Wed Feb 19 16:08:15 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Wed, 19 Feb 2003 08:08:15 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.123,1.124 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv21496 Modified Files: whatsnew23.tex Log Message: Added a note about the new itertools module. (Omission noted by Gerrit Holl in email to python-docs.) Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.123 retrieving revision 1.124 diff -C2 -d -r1.123 -r1.124 *** whatsnew23.tex 19 Feb 2003 13:46:18 -0000 1.123 --- whatsnew23.tex 19 Feb 2003 16:08:08 -0000 1.124 *************** *** 1358,1361 **** --- 1358,1365 ---- (Contributed by Piers Lauder and Tino Lange.) + \item The \ulink{\module{itertools}}{../lib/module-itertools.html} + module provides several functions to support efficient looping using + iterators. + \item Two new functions in the \module{math} module, \function{degrees(\var{rads})} and \function{radians(\var{degs})}, From doerwalter@users.sourceforge.net Wed Feb 19 16:34:18 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Wed, 19 Feb 2003 08:34:18 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.667,1.668 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv9274/Misc Modified Files: NEWS Log Message: Add a note about the recent PEP 293 changes. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.667 retrieving revision 1.668 diff -C2 -d -r1.667 -r1.668 *** NEWS 19 Feb 2003 15:53:11 -0000 1.667 --- NEWS 19 Feb 2003 16:34:11 -0000 1.668 *************** *** 13,16 **** --- 13,20 ---- ----------------- + - Negative positions returned from PEP 293 error callbacks are now + treated as being relative to the end of the input string. Positions + that are out of bounds raise an IndexError. + - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. From gvanrossum@users.sourceforge.net Wed Feb 19 17:50:22 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 09:50:22 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.256,1.257 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv24517 Modified Files: socketmodule.c Log Message: The connect timeout code wasn't working on Windows. Rather than trying to second-guess the various error returns of a second connect(), use select() to determine whether the socket becomes writable (which means connected). Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.256 retrieving revision 1.257 diff -C2 -d -r1.256 -r1.257 *** socketmodule.c 13 Feb 2003 03:13:40 -0000 1.256 --- socketmodule.c 19 Feb 2003 17:50:16 -0000 1.257 *************** *** 1337,1352 **** if (s->sock_timeout > 0.0) { if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) { ! internal_select(s, 1); ! res = connect(s->sock_fd, addr, addrlen); ! if (res < 0) { ! /* On Win98, WSAEISCONN was seen here. But ! * on Win2K, WSAEINVAL. So accept both as ! * meaning "fine". ! */ ! int code = WSAGetLastError(); ! if (code == WSAEISCONN || ! code == WSAEINVAL) ! res = 0; ! } } } --- 1337,1353 ---- if (s->sock_timeout > 0.0) { if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK) { ! /* This is a mess. Best solution: trust select */ ! fd_set fds; ! struct timeval tv; ! tv.tv_sec = (int)s->sock_timeout; ! tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); ! FD_ZERO(&fds); ! FD_SET(s->sock_fd, &fds); ! res = select(s->sock_fd+1, NULL, &fds, NULL, &tv); ! if (res == 0) ! res = WSAEWOULDBLOCK; ! else if (res > 0) ! res = 0; ! /* else if (res < 0) an error occurred */ } } From gvanrossum@users.sourceforge.net Wed Feb 19 18:18:50 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 10:18:50 -0800 Subject: [Python-checkins] python/dist/src README,1.168,1.169 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv4356 Modified Files: README Log Message: Update versions/dates for release of 2.3a2. Added some last-minute news. Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/README,v retrieving revision 1.168 retrieving revision 1.169 diff -C2 -d -r1.168 -r1.169 *** README 2 Feb 2003 23:37:05 -0000 1.168 --- README 19 Feb 2003 18:18:46 -0000 1.169 *************** *** 1,3 **** ! This is Python version 2.3 alpha 1 ================================== --- 1,3 ---- ! This is Python version 2.3 alpha 2 ================================== From gvanrossum@users.sourceforge.net Wed Feb 19 18:18:52 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 10:18:52 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.668,1.669 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv4356/Misc Modified Files: NEWS Log Message: Update versions/dates for release of 2.3a2. Added some last-minute news. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.668 retrieving revision 1.669 diff -C2 -d -r1.668 -r1.669 *** NEWS 19 Feb 2003 16:34:11 -0000 1.668 --- NEWS 19 Feb 2003 18:18:47 -0000 1.669 *************** *** 8,12 **** ================================= ! *Release date: XX-XXX-2003* Core and builtins --- 8,12 ---- ================================= ! *Release date: 19-Feb-2003* Core and builtins *************** *** 347,363 **** raise a TypeError. - - New platforms - ------------- - - TBD - Tests ----- ! TBD Windows ------- - distutils' msvccompiler class now passes the preprocessor options to --- 347,361 ---- raise a TypeError. Tests ----- ! - Several tests weren't being run. Now they are. Windows ------- + + - The timeout code for socket connect() didn't work right; this has + now been fixed. test_timeout.py should pass (at least most of the + time). - distutils' msvccompiler class now passes the preprocessor options to From gvanrossum@users.sourceforge.net Wed Feb 19 19:10:37 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 11:10:37 -0800 Subject: [Python-checkins] python/nondist/peps pep-0283.txt,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv29128 Modified Files: pep-0283.txt Log Message: Adjust schedule. Add some issues that might be resulved before 2.3b1. Index: pep-0283.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0283.txt,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** pep-0283.txt 1 Feb 2003 19:02:10 -0000 1.29 --- pep-0283.txt 19 Feb 2003 19:10:33 -0000 1.30 *************** *** 28,35 **** alpha 2 -- mid February ! beta 1 -- mid March ! beta 2 -- mid April ! rc 1 -- mid May ! final -- end of May --- 28,35 ---- alpha 2 -- mid February ! beta 1 -- late March ! beta 2 -- late April ! rc 1 -- late May ! final -- early June *************** *** 137,140 **** --- 137,142 ---- have been fixed post-release). + - A new pickling protocol. See PEP 307. + Planned features for 2.3 *************** *** 149,156 **** life of the 2.3 development process. ! - A new pickling protocol. See PEP 307. - For a class defined inside another class, the __name__ should be ! "outer.inner", and pickling should work. --- 151,164 ---- life of the 2.3 development process. ! - We need a new PyArg_Parse*() format code that returns an ! unsigned C long int that receives the lower LONG_BIT bits of the ! Python argument, truncating without range checking. (SF ! 595026.) - For a class defined inside another class, the __name__ should be ! "outer.inner", and pickling should work. (SF 633930. I'm no ! longer certain this is easy or even right.) ! ! - The import lock could use some redesign. (SF 683658.) From gvanrossum@users.sourceforge.net Wed Feb 19 19:36:30 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 11:36:30 -0800 Subject: [Python-checkins] python/nondist/peps pep-0283.txt,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv10865 Modified Files: pep-0283.txt Log Message: Explain feature freeze. Mention IDLE. Index: pep-0283.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0283.txt,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** pep-0283.txt 19 Feb 2003 19:10:33 -0000 1.30 --- pep-0283.txt 19 Feb 2003 19:36:27 -0000 1.31 *************** *** 13,18 **** This document describes the development and release schedule for Python 2.3. The schedule primarily concerns itself with PEP-sized ! items. Small features may be added until the first beta release. ! Bugs may be fixed until the final release. There will be at least two alpha releases, two beta releases, and --- 13,18 ---- This document describes the development and release schedule for Python 2.3. The schedule primarily concerns itself with PEP-sized ! items. Small features may be added up to and including the first ! beta release. Bugs may be fixed until the final release. There will be at least two alpha releases, two beta releases, and *************** *** 23,31 **** least one week apart (excepting again blunder corrections). ! Based on the first alpha release, which was made on Dec. 31, 2002, ! here's a fairly aggressive release schedule that follows the above guidelines: ! alpha 2 -- mid February beta 1 -- late March beta 2 -- late April --- 23,30 ---- least one week apart (excepting again blunder corrections). ! Here's a tentative release schedule that follows the above guidelines: ! alpha 2 -- February 19, 2003 beta 1 -- late March beta 2 -- late April *************** *** 150,153 **** --- 149,155 ---- feedback to python-dev@python.org; I hope to maintain this for the life of the 2.3 development process. + + - I plan to integrate the new version of IDLE from the IDLEfork + project (http://idlefork.sf.net). - We need a new PyArg_Parse*() format code that returns an From gvanrossum@users.sourceforge.net Wed Feb 19 20:23:55 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 12:23:55 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.669,1.669.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv30825 Modified Files: Tag: r23a2-branch NEWS Log Message: Some last-minute news. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.669 retrieving revision 1.669.2.1 diff -C2 -d -r1.669 -r1.669.2.1 *** NEWS 19 Feb 2003 18:18:47 -0000 1.669 --- NEWS 19 Feb 2003 20:23:45 -0000 1.669.2.1 *************** *** 108,111 **** --- 108,113 ---- imp.lock_held(). (SF bug #580952 and patch #683257.) + - Change to cPickle to match pickle.py (see below and PEP 307). + - Fix some bugs in the parser module. SF bug #678518. *************** *** 135,138 **** --- 137,142 ---- an mmap'ed file which was already closed. (SF patch #665913) + - Fixed serveral serious bugs in the zipimport implementation. + - datetime changes: *************** *** 237,240 **** --- 241,257 ---- ------- + - The logging module was updated slightly; the WARN level was renamed + to WARNING, and the matching function/method warn() to warning(). + + - The pickle and cPickle modules were updated with a new pickling + protocol (documented by pickletools.py, see below) and several + extensions to the pickle customization API (__reduce__, __setstate__ + etc.). The copy module now uses more of the pickle customization + API to copy objects that don't implement __copy__ or __deepcopy__. + See PEP 307 for details. + + - The distutils "register" command now uses http://www.python.org/pypi + as the default repository. (See PEP 301.) + - the platform dependent path related variables sep, altsep, extsep, pathsep, curdir, pardir and defpath are now defined in the platform *************** *** 350,354 **** ----- ! - Several tests weren't being run. Now they are. Windows --- 367,378 ---- ----- ! - Several tests weren't being run rom regrtest.py (test_timeout.py, ! test_tarfile.py, test_netrc.py, test_multifile.py, ! test_importhooks.py and test_imp.py). Now they are. (Note to ! developers: please read Lib/test/README when creating a new test, to ! make sure to do it right! All tests need to use either unittest or ! pydoc.) ! ! - Added test_posix.py, a test suite for the posix module. Windows *************** *** 366,370 **** - sys.path[0], if it contains a directory name, is now always an ! absolute pathname. - The new logging package is now installed by the Windows installer. It --- 390,394 ---- - sys.path[0], if it contains a directory name, is now always an ! absolute pathname. (SF patch #664376.) - The new logging package is now installed by the Windows installer. It From gvanrossum@users.sourceforge.net Wed Feb 19 20:34:06 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 12:34:06 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.669.2.1,1.669.2.2 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv2993 Modified Files: Tag: r23a2-branch NEWS Log Message: Mention test_hexoct.py. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.669.2.1 retrieving revision 1.669.2.2 diff -C2 -d -r1.669.2.1 -r1.669.2.2 *** NEWS 19 Feb 2003 20:23:45 -0000 1.669.2.1 --- NEWS 19 Feb 2003 20:33:54 -0000 1.669.2.2 *************** *** 376,379 **** --- 376,381 ---- - Added test_posix.py, a test suite for the posix module. + - Added test_hexoct.py, a test suite for hex/oct constant folding. + Windows ------- From goodger@users.sourceforge.net Wed Feb 19 23:31:54 2003 From: goodger@users.sourceforge.net (goodger@users.sourceforge.net) Date: Wed, 19 Feb 2003 15:31:54 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.669,1.670 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv7488 Modified Files: NEWS Log Message: fixed markup Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.669 retrieving revision 1.670 diff -C2 -d -r1.669 -r1.670 *** NEWS 19 Feb 2003 18:18:47 -0000 1.669 --- NEWS 19 Feb 2003 23:31:51 -0000 1.670 *************** *** 33,37 **** constructor refuses arguments in this case. This might break code that worked under Python 2.2. The simplest fix is to add a no-op ! __init__: "def __init__(self, *args, **kw): pass". - Through a bytecode optimizer bug (and I bet you didn't even know --- 33,37 ---- constructor refuses arguments in this case. This might break code that worked under Python 2.2. The simplest fix is to add a no-op ! __init__: ``def __init__(self, *args, **kw): pass``. - Through a bytecode optimizer bug (and I bet you didn't even know *************** *** 190,195 **** and time, and attach tz to it, without any conversion of date and time members. This was less than useful. Now now(tz) returns the current ! date and time as local time in tz's time zone, akin to tz.fromutc(datetime.utcnow().replace(tzinfo=utc)) where "utc" is an instance of a tzinfo subclass modeling UTC. Without a tz argument, now() continues to return the current local date and time, --- 190,197 ---- and time, and attach tz to it, without any conversion of date and time members. This was less than useful. Now now(tz) returns the current ! date and time as local time in tz's time zone, akin to :: ! tz.fromutc(datetime.utcnow().replace(tzinfo=utc)) + where "utc" is an instance of a tzinfo subclass modeling UTC. Without a tz argument, now() continues to return the current local date and time, *************** *** 212,219 **** the comparison is == then False is returned, and if the comparison is != then True is returned. Because dict lookup and the "in" operator ! only invoke __eq__, this allows, for example, if some_datetime in some_sequence: ! and some_dict[some_timedelta] = whatever --- 214,223 ---- the comparison is == then False is returned, and if the comparison is != then True is returned. Because dict lookup and the "in" operator ! only invoke __eq__, this allows, for example, :: if some_datetime in some_sequence: ! ! and :: ! some_dict[some_timedelta] = whatever *************** *** 266,270 **** Python 2.2. or 2.3. ! - realpath is now exported when doing from poxixpath import *. It is also exported for ntpath, macpath, and os2emxpath. See SF bug #659228. --- 270,274 ---- Python 2.2. or 2.3. ! - realpath is now exported when doing ``from poxixpath import *``. It is also exported for ntpath, macpath, and os2emxpath. See SF bug #659228. *************** *** 307,311 **** test_linuxaudiodev.py) are no longer run by default. This is because they don't always work, depending on your hardware and ! software. To run these tests, you must use an invocation like ./python Lib/test/regrtest.py -u audio test_ossaudiodev --- 311,316 ---- test_linuxaudiodev.py) are no longer run by default. This is because they don't always work, depending on your hardware and ! software. To run these tests, you must use an invocation like :: ! ./python Lib/test/regrtest.py -u audio test_ossaudiodev *************** *** 331,336 **** ----- ! - PyEval_GetFrame() is now declared to return a PyFrameObject * ! instead of a plain PyObject *. (SF patch #686601.) - PyNumber_Check() now checks that the object has a nb_int or nb_float --- 336,341 ---- ----- ! - PyEval_GetFrame() is now declared to return a ``PyFrameObject *`` ! instead of a plain ``PyObject *``. (SF patch #686601.) - PyNumber_Check() now checks that the object has a nb_int or nb_float From gvanrossum@users.sourceforge.net Thu Feb 20 01:38:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 17:38:35 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.670,1.671 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv18058 Modified Files: NEWS Log Message: Merge in changes made to the 2.3a2 release. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.670 retrieving revision 1.671 diff -C2 -d -r1.670 -r1.671 *** NEWS 19 Feb 2003 23:31:51 -0000 1.670 --- NEWS 20 Feb 2003 01:38:31 -0000 1.671 *************** *** 108,111 **** --- 108,113 ---- imp.lock_held(). (SF bug #580952 and patch #683257.) + - Change to cPickle to match pickle.py (see below and PEP 307). + - Fix some bugs in the parser module. SF bug #678518. *************** *** 135,138 **** --- 137,142 ---- an mmap'ed file which was already closed. (SF patch #665913) + - Fixed serveral serious bugs in the zipimport implementation. + - datetime changes: *************** *** 241,244 **** --- 245,261 ---- ------- + - The logging module was updated slightly; the WARN level was renamed + to WARNING, and the matching function/method warn() to warning(). + + - The pickle and cPickle modules were updated with a new pickling + protocol (documented by pickletools.py, see below) and several + extensions to the pickle customization API (__reduce__, __setstate__ + etc.). The copy module now uses more of the pickle customization + API to copy objects that don't implement __copy__ or __deepcopy__. + See PEP 307 for details. + + - The distutils "register" command now uses http://www.python.org/pypi + as the default repository. (See PEP 301.) + - the platform dependent path related variables sep, altsep, extsep, pathsep, curdir, pardir and defpath are now defined in the platform *************** *** 355,359 **** ----- ! - Several tests weren't being run. Now they are. Windows --- 372,385 ---- ----- ! - Several tests weren't being run rom regrtest.py (test_timeout.py, ! test_tarfile.py, test_netrc.py, test_multifile.py, ! test_importhooks.py and test_imp.py). Now they are. (Note to ! developers: please read Lib/test/README when creating a new test, to ! make sure to do it right! All tests need to use either unittest or ! pydoc.) ! ! - Added test_posix.py, a test suite for the posix module. ! ! - Added test_hexoct.py, a test suite for hex/oct constant folding. Windows *************** *** 371,375 **** - sys.path[0], if it contains a directory name, is now always an ! absolute pathname. - The new logging package is now installed by the Windows installer. It --- 397,401 ---- - sys.path[0], if it contains a directory name, is now always an ! absolute pathname. (SF patch #664376.) - The new logging package is now installed by the Windows installer. It From gvanrossum@users.sourceforge.net Thu Feb 20 01:52:51 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 17:52:51 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.671,1.672 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23876 Modified Files: NEWS Log Message: Match parentheses. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.671 retrieving revision 1.672 diff -C2 -d -r1.671 -r1.672 *** NEWS 20 Feb 2003 01:38:31 -0000 1.671 --- NEWS 20 Feb 2003 01:52:48 -0000 1.672 *************** *** 1508,1512 **** - The default encoding for Python sourcefiles in MacPython-OS9 is no longer ! mac-roman (or whatever your local Mac encoding was but "ascii", like on other platforms. If you really need sourcefiles with Mac characters in them you can change this in site.py. --- 1508,1512 ---- - The default encoding for Python sourcefiles in MacPython-OS9 is no longer ! mac-roman (or whatever your local Mac encoding was) but "ascii", like on other platforms. If you really need sourcefiles with Mac characters in them you can change this in site.py. From gvanrossum@users.sourceforge.net Thu Feb 20 01:56:19 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 17:56:19 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.672,1.673 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv25122 Modified Files: NEWS Log Message: Prepped for 2.3b1. Added an extra blank line before "What's New in Python 2.2 final?". Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.672 retrieving revision 1.673 diff -C2 -d -r1.672 -r1.673 *** NEWS 20 Feb 2003 01:52:48 -0000 1.672 --- NEWS 20 Feb 2003 01:56:17 -0000 1.673 *************** *** 5,8 **** --- 5,64 ---- (editors: check NEWS.help for information about editing NEWS using ReST.) + What's New in Python 2.3 beta 1? + ================================ + + *Release date: XX-XXX-2003* + + Core and builtins + ----------------- + + TBD + + Extension modules + ----------------- + + TBD + + Library + ------- + + TBD + + Tools/Demos + ----------- + + TBD + + Build + ----- + + TBD + + C API + ----- + + TBD + + New platforms + ------------- + + TBD + + Tests + ----- + + TBD + + Windows + ------- + + TBD + + Mac + --- + + TBD + + What's New in Python 2.3 alpha 2? ================================= *************** *** 1511,1514 **** --- 1567,1571 ---- other platforms. If you really need sourcefiles with Mac characters in them you can change this in site.py. + What's New in Python 2.2 final? From gvanrossum@users.sourceforge.net Thu Feb 20 02:09:33 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 18:09:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils log.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv29953 Modified Files: log.py Log Message: set_verbosity(): do something reasonable for out-of-range verbosity levels. (Previously, -vvv would be the same as -q!) Index: log.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/log.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** log.py 19 Nov 2002 13:12:27 -0000 1.3 --- log.py 20 Feb 2003 02:09:30 -0000 1.4 *************** *** 54,61 **** def set_verbosity(v): ! if v == 0: set_threshold(WARN) ! if v == 1: set_threshold(INFO) ! if v == 2: set_threshold(DEBUG) --- 54,61 ---- def set_verbosity(v): ! if v <= 0: set_threshold(WARN) ! elif v == 1: set_threshold(INFO) ! elif v >= 2: set_threshold(DEBUG) From gvanrossum@users.sourceforge.net Thu Feb 20 02:10:11 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 18:10:11 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils cmd.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv30149 Modified Files: cmd.py Log Message: announce(): use the level argument to control the log level. Index: cmd.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/cmd.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** cmd.py 19 Nov 2002 13:12:27 -0000 1.33 --- cmd.py 20 Feb 2003 02:10:08 -0000 1.34 *************** *** 192,196 **** 'level' print 'msg' to stdout. """ ! log.debug(msg) def debug_print (self, msg): --- 192,196 ---- 'level' print 'msg' to stdout. """ ! log.log(level, msg) def debug_print (self, msg): From gvanrossum@users.sourceforge.net Thu Feb 20 02:11:45 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 18:11:45 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.146,1.147 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv30600 Modified Files: setup.py Log Message: Don't use self.announce() in a function that's not a method. Use level=3 (i.e. log.WARN) for the warnings about failed imports. (Hmm... Why is that code in an "if 1: ..."? What's the else branch for?) Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.146 retrieving revision 1.147 diff -C2 -d -r1.146 -r1.147 *** setup.py 18 Feb 2003 10:24:34 -0000 1.146 --- setup.py 20 Feb 2003 02:11:43 -0000 1.147 *************** *** 89,93 **** return module if len(list) > 1: ! self.announce("WARNING: multiple copies of %s found"%module) return os.path.join(list[0], module) --- 89,93 ---- return module if len(list) > 1: ! log.info("WARNING: multiple copies of %s found"%module) return os.path.join(list[0], module) *************** *** 212,216 **** if 1: self.announce('*** WARNING: renaming "%s" since importing it' ! ' failed: %s' % (ext.name, why)) assert not self.inplace basename, tail = os.path.splitext(ext_filename) --- 212,216 ---- if 1: self.announce('*** WARNING: renaming "%s" since importing it' ! ' failed: %s' % (ext.name, why), level=3) assert not self.inplace basename, tail = os.path.splitext(ext_filename) *************** *** 232,236 **** else: self.announce('*** WARNING: importing extension "%s" ' ! 'failed: %s' % (ext.name, why)) def get_platform (self): --- 232,236 ---- else: self.announce('*** WARNING: importing extension "%s" ' ! 'failed: %s' % (ext.name, why), level=3) def get_platform (self): From gvanrossum@users.sourceforge.net Thu Feb 20 02:52:07 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 19 Feb 2003 18:52:07 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.147,1.148 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv12633 Modified Files: setup.py Log Message: Add PEP 301 metadata. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.147 retrieving revision 1.148 diff -C2 -d -r1.147 -r1.148 *** setup.py 20 Feb 2003 02:11:43 -0000 1.147 --- setup.py 20 Feb 2003 02:52:04 -0000 1.148 *************** *** 1057,1066 **** return hasattr(os, 'chmod') def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) ! setup(name = 'Python standard library', ! version = '%d.%d' % sys.version_info[:2], cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall, 'install_lib':PyBuildInstallLib}, --- 1057,1106 ---- return hasattr(os, 'chmod') + SUMMARY = """ + Python is an interpreted, interactive, object-oriented programming + language. It is often compared to Tcl, Perl, Scheme or Java. + + Python combines remarkable power with very clear syntax. It has + modules, classes, exceptions, very high level dynamic data types, and + dynamic typing. There are interfaces to many system calls and + libraries, as well as to various windowing systems (X11, Motif, Tk, + Mac, MFC). New built-in modules are easily written in C or C++. Python + is also usable as an extension language for applications that need a + programmable interface. + + The Python implementation is portable: it runs on many brands of UNIX, + on Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't + listed here, it may still be supported, if there's a C compiler for + it. Ask around on comp.lang.python -- or just try compiling Python + yourself. + """ + + CLASSIFIERS = """ + Development Status :: 3 - Alpha + Development Status :: 6 - Mature + License :: OSI Approved :: Python Software Foundation License + Natural Language :: English + Programming Language :: C + Programming Language :: Python + Topic :: Software Development + """ + def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) ! setup(# PyPI Metadata (PEP 301) ! name = "Python", ! version = sys.version.split()[0], ! url = "http://www.python.org/%s" % sys.version[:3], ! maintainer = "Guido van Rossum and the Python community", ! maintainer_email = "python-dev@python.org", ! description = "A high-level object-oriented programming language", ! long_description = SUMMARY.strip(), ! license = "PSF license", ! classifiers = filter(None, CLASSIFIERS.split("\n")), ! platforms = ["Many"], ! ! # Build info cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall, 'install_lib':PyBuildInstallLib}, From mwh@users.sourceforge.net Thu Feb 20 17:59:20 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 20 Feb 2003 09:59:20 -0800 Subject: [Python-checkins] python/dist/src/Include ceval.h,2.48,2.49 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv19490 Modified Files: ceval.h Log Message: As far as I can tell PyEval_GetOwner was removed in 1997 (when it was called something else!). I can't imagine removing the prototype is going to hurt, but put it back if *you* can. Index: ceval.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/ceval.h,v retrieving revision 2.48 retrieving revision 2.49 diff -C2 -d -r2.48 -r2.49 *** ceval.h 19 Feb 2003 15:53:14 -0000 2.48 --- ceval.h 20 Feb 2003 17:59:17 -0000 2.49 *************** *** 31,35 **** PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void); PyAPI_FUNC(PyObject *) PyEval_GetLocals(void); - PyAPI_FUNC(PyObject *) PyEval_GetOwner(void); PyAPI_FUNC(struct _frame *) PyEval_GetFrame(void); PyAPI_FUNC(int) PyEval_GetRestricted(void); --- 31,34 ---- From gvanrossum@users.sourceforge.net Thu Feb 20 18:46:57 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 20 Feb 2003 10:46:57 -0800 Subject: [Python-checkins] python/dist/src/Include patchlevel.h,2.64,2.65 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv14016 Modified Files: patchlevel.h Log Message: Update PY_VERSION to indicate that we're beyond 2.3a2 now. Index: patchlevel.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/patchlevel.h,v retrieving revision 2.64 retrieving revision 2.65 diff -C2 -d -r2.64 -r2.65 *** patchlevel.h 18 Feb 2003 21:58:43 -0000 2.64 --- patchlevel.h 20 Feb 2003 18:46:54 -0000 2.65 *************** *** 27,31 **** /* Version as a string */ ! #define PY_VERSION "2.3a2" /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. --- 27,31 ---- /* Version as a string */ ! #define PY_VERSION "2.3a2+" /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. From theller@users.sourceforge.net Thu Feb 20 20:32:18 2003 From: theller@users.sourceforge.net (theller@users.sourceforge.net) Date: Thu, 20 Feb 2003 12:32:18 -0800 Subject: [Python-checkins] python/dist/src/Objects intobject.c,2.102,2.103 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv12346 Modified Files: intobject.c Log Message: Strange control flow in PyInt_AsLong. When nb_int is called inside the PyInt_AsLong function, and this returns a long, the value is first retrieved with PyLong_AsLong, but afterwards overwritten by a call to PyInt_AS_LONG. Fixes SF #690253. Index: intobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/intobject.c,v retrieving revision 2.102 retrieving revision 2.103 diff -C2 -d -r2.102 -r2.103 *** intobject.c 12 Feb 2003 20:43:33 -0000 2.102 --- intobject.c 20 Feb 2003 20:32:11 -0000 2.103 *************** *** 163,170 **** /* got a long? => retry int conversion */ val = PyLong_AsLong((PyObject *)io); ! if (PyErr_Occurred()) { ! Py_DECREF(io); return -1; ! } } else --- 163,170 ---- /* got a long? => retry int conversion */ val = PyLong_AsLong((PyObject *)io); ! Py_DECREF(io); ! if ((val == -1) && PyErr_Occurred()) return -1; ! return val; } else From nnorwitz@users.sourceforge.net Fri Feb 21 00:26:35 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 20 Feb 2003 16:26:35 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libpickle.tex,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv13633/Doc/lib Modified Files: libpickle.tex Log Message: Add some notes about HIGHEST_PROTOCOL. Index: libpickle.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpickle.tex,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** libpickle.tex 13 Feb 2003 03:12:48 -0000 1.39 --- libpickle.tex 21 Feb 2003 00:26:33 -0000 1.40 *************** *** 145,150 **** If a \var{protocol} is not specified, protocol 0 is used. ! If \var{protocol} is specified as a negative value, ! the highest protocol version will be used. \versionchanged[The \var{bin} parameter is deprecated and only provided --- 145,151 ---- If a \var{protocol} is not specified, protocol 0 is used. ! If \var{protocol} is specified as a negative value ! or \constant{HIGHEST_PROTOCOL}, ! the highest protocol version available will be used. \versionchanged[The \var{bin} parameter is deprecated and only provided *************** *** 163,166 **** --- 164,175 ---- stream, you first create an unpickler, then you call the unpickler's \method{load()} method. The \module{pickle} module provides the + following constant: + + \begin{datadesc}{HIGHEST_PROTOCOL} + The highest protocol version available. This value can be passed + as a \var{protocol} value. + \end{datadesc} + + The \module{pickle} module provides the following functions to make this process more convenient: *************** *** 171,175 **** If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value, the highest protocol version will be used. --- 180,185 ---- If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value ! or \constant{HIGHEST_PROTOCOL}, the highest protocol version will be used. *************** *** 210,214 **** If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value, the highest protocol version will be used. --- 220,225 ---- If the \var{protocol} parameter is ommitted, protocol 0 is used. ! If \var{protocol} is specified as a negative value ! or \constant{HIGHEST_PROTOCOL}, the highest protocol version will be used. From nnorwitz@users.sourceforge.net Fri Feb 21 00:30:20 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 20 Feb 2003 16:30:20 -0800 Subject: [Python-checkins] python/dist/src/Modules readline.c,2.60,2.61 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv15230/Modules Modified Files: readline.c Log Message: flex_complete looks like a private (but callback) function, so make it static Index: readline.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/readline.c,v retrieving revision 2.60 retrieving revision 2.61 diff -C2 -d -r2.60 -r2.61 *** readline.c 30 Jan 2003 14:17:16 -0000 2.60 --- readline.c 21 Feb 2003 00:30:18 -0000 2.61 *************** *** 578,582 **** * before calling the normal completer */ ! char ** flex_complete(char *text, int start, int end) { --- 578,582 ---- * before calling the normal completer */ ! static char ** flex_complete(char *text, int start, int end) { From rhettinger@users.sourceforge.net Fri Feb 21 01:41:38 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 17:41:38 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_random.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6447 Modified Files: test_random.py Log Message: SF bug #690083: test_random fails sometimes time.sleep(1) sometimes delays for fractionally less than a second resulting in too short of an interval for C's time.time() function to create a distinct seed. Index: test_random.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_random.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** test_random.py 4 Feb 2003 05:47:30 -0000 1.8 --- test_random.py 21 Feb 2003 01:41:36 -0000 1.9 *************** *** 20,24 **** self.gen.seed() state1 = self.gen.getstate() ! time.sleep(1) self.gen.seed() # diffent seeds at different times state2 = self.gen.getstate() --- 20,24 ---- self.gen.seed() state1 = self.gen.getstate() ! time.sleep(1.1) self.gen.seed() # diffent seeds at different times state2 = self.gen.getstate() From rhettinger@users.sourceforge.net Fri Feb 21 01:45:37 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 17:45:37 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv9511 Modified Files: libitertools.tex Log Message: Markup and nits. Index: libitertools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libitertools.tex,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** libitertools.tex 11 Feb 2003 14:24:13 -0000 1.4 --- libitertools.tex 21 Feb 2003 01:45:34 -0000 1.5 *************** *** 19,30 **** each with their own quirks and naming conventions. ! The tools are designed to combine readily with each another. This makes it easy to construct more specialized tools succinctly and efficiently in pure Python. ! For instance, SML provides a tabulation tool: \code{tabulate(\var{f})} which produces a sequence \code{f(0), f(1), ...}. This toolbox provides \function{imap()} and \function{count()} which can be combined ! to form \code{imap(\var{f}, count())} and produce an equivalent result. Whether cast in pure python form or C code, tools that use iterators --- 19,30 ---- each with their own quirks and naming conventions. ! The tools are designed to combine readily with one another. This makes it easy to construct more specialized tools succinctly and efficiently in pure Python. ! For instance, SML provides a tabulation tool: \code{tabulate(f)} which produces a sequence \code{f(0), f(1), ...}. This toolbox provides \function{imap()} and \function{count()} which can be combined ! to form \code{imap(f, count())} and produce an equivalent result. Whether cast in pure python form or C code, tools that use iterators *************** *** 76,83 **** \begin{verbatim} def count(n=0): - cnt = n while True: ! yield cnt ! cnt += 1 \end{verbatim} --- 76,82 ---- \begin{verbatim} def count(n=0): while True: ! yield n ! n += 1 \end{verbatim} *************** *** 209,222 **** \end{funcdesc} ! \begin{funcdesc}{repeat}{obj} ! Make an iterator that returns \var{obj} over and over again. Used as argument to \function{imap()} for invariant parameters ! to the called function. Also used with function{izip()} to create an invariant part of a tuple record. Equivalent to: \begin{verbatim} ! def repeat(x): while True: ! yield x \end{verbatim} \end{funcdesc} --- 208,221 ---- \end{funcdesc} ! \begin{funcdesc}{repeat}{object} ! Make an iterator that returns \var{object} over and over again. Used as argument to \function{imap()} for invariant parameters ! to the called function. Also used with \function{izip()} to create an invariant part of a tuple record. Equivalent to: \begin{verbatim} ! def repeat(object): while True: ! yield object \end{verbatim} \end{funcdesc} *************** *** 227,231 **** argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between ! \function{imap()} and \function{starmap} parallels the distinction between \code{function(a,b)} and \code{function(*c)}. Equivalent to: --- 226,230 ---- argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between ! \function{imap()} and \function{starmap()} parallels the distinction between \code{function(a,b)} and \code{function(*c)}. Equivalent to: From rhettinger@users.sourceforge.net Fri Feb 21 02:47:12 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 18:47:12 -0800 Subject: [Python-checkins] python/dist/src/Doc/dist dist.tex,1.48,1.49 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/dist In directory sc8-pr-cvs1:/tmp/cvs-serv29459 Modified Files: dist.tex Log Message: SF bug #690377: Dud footnote reference in distutils docs Index: dist.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/dist/dist.tex,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** dist.tex 3 Jan 2003 15:42:14 -0000 1.48 --- dist.tex 21 Feb 2003 02:47:09 -0000 1.49 *************** *** 696,700 **** \lineiii{maintainer}{package maintainer's name}{(2)} \lineiii{maintainer_email}{email address of the package maintainer}{(2)} ! \lineiii{home_page}{a URL}{(1)} \lineiii{license}{the terms the package is released under}{} \lineiii{description}{a short, summary description of the package}{} --- 696,700 ---- \lineiii{maintainer}{package maintainer's name}{(2)} \lineiii{maintainer_email}{email address of the package maintainer}{(2)} ! \lineiii{home_page}{url}{(1)} \lineiii{license}{the terms the package is released under}{} \lineiii{description}{a short, summary description of the package}{} *************** *** 702,706 **** \lineiii{keywords}{some keywords appropriate to the package}{} \lineiii{platform}{a list of the target platforms}{} ! \lineiii{classifiers}{a list of Trove classifiers}{(2)} \end{tableiii} --- 702,706 ---- \lineiii{keywords}{some keywords appropriate to the package}{} \lineiii{platform}{a list of the target platforms}{} ! \lineiii{classifiers}{a list of Trove classifiers}{(3)} \end{tableiii} From rhettinger@users.sourceforge.net Fri Feb 21 03:14:11 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 19:14:11 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libturtle.tex,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv6105 Modified Files: libturtle.tex Log Message: SF bug #685775: turtle circle() documentation error Index: libturtle.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libturtle.tex,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** libturtle.tex 15 Nov 2001 20:41:03 -0000 1.4 --- libturtle.tex 21 Feb 2003 03:14:08 -0000 1.5 *************** *** 96,102 **** \begin{funcdesc}{circle}{radius\optional{, extent}} ! Draw a circle with radius \var{radius} whose center-point is where the ! pen would be if a \code{forward(\var{radius})} were ! called. \var{extent} determines which part of a circle is drawn: if not given it defaults to a full circle. --- 96,102 ---- \begin{funcdesc}{circle}{radius\optional{, extent}} ! Draw a circle with radius \var{radius} whose center-point is ! \var{radius} units left of the turtle. ! \var{extent} determines which part of a circle is drawn: if not given it defaults to a full circle. *************** *** 104,108 **** current pen position. The arc is drawn in a counter clockwise direction if \var{radius} is positive, otherwise in a clockwise ! direction. \end{funcdesc} --- 104,109 ---- current pen position. The arc is drawn in a counter clockwise direction if \var{radius} is positive, otherwise in a clockwise ! direction. In the process, the direction of the turtle is changed ! by the amount of the \var{extent}. \end{funcdesc} From rhettinger@users.sourceforge.net Fri Feb 21 03:42:31 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 19:42:31 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libturtle.tex,1.4,1.4.8.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv15142 Modified Files: Tag: release22-maint libturtle.tex Log Message: SF bug #685775: turtle circle() documentation error Index: libturtle.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libturtle.tex,v retrieving revision 1.4 retrieving revision 1.4.8.1 diff -C2 -d -r1.4 -r1.4.8.1 *** libturtle.tex 15 Nov 2001 20:41:03 -0000 1.4 --- libturtle.tex 21 Feb 2003 03:42:28 -0000 1.4.8.1 *************** *** 96,102 **** \begin{funcdesc}{circle}{radius\optional{, extent}} ! Draw a circle with radius \var{radius} whose center-point is where the ! pen would be if a \code{forward(\var{radius})} were ! called. \var{extent} determines which part of a circle is drawn: if not given it defaults to a full circle. --- 96,102 ---- \begin{funcdesc}{circle}{radius\optional{, extent}} ! Draw a circle with radius \var{radius} whose center-point is ! \var{radius} units left of the turtle. ! \var{extent} determines which part of a circle is drawn: if not given it defaults to a full circle. *************** *** 104,108 **** current pen position. The arc is drawn in a counter clockwise direction if \var{radius} is positive, otherwise in a clockwise ! direction. \end{funcdesc} --- 104,109 ---- current pen position. The arc is drawn in a counter clockwise direction if \var{radius} is positive, otherwise in a clockwise ! direction. In the process, the direction of the turtle is changed ! by the amount of the \var{extent}. \end{funcdesc} From rhettinger@users.sourceforge.net Fri Feb 21 04:18:34 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 20:18:34 -0800 Subject: [Python-checkins] python/dist/src/Tools/idle EditorWindow.py,1.38.18.4,1.38.18.5 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/idle In directory sc8-pr-cvs1:/tmp/cvs-serv26701 Modified Files: Tag: release22-maint EditorWindow.py Log Message: Backport 1.45: Failed module import was dumping to the console instead of creating a nice dialog window. Index: EditorWindow.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/idle/EditorWindow.py,v retrieving revision 1.38.18.4 retrieving revision 1.38.18.5 diff -C2 -d -r1.38.18.4 -r1.38.18.5 *** EditorWindow.py 5 Oct 2002 03:58:16 -0000 1.38.18.4 --- EditorWindow.py 21 Feb 2003 04:18:32 -0000 1.38.18.5 *************** *** 93,97 **** break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) ! path = module.__path__ return file, filename, descr --- 93,100 ---- break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) ! try: ! path = module.__path__ ! except AttributeError: ! raise ImportError, 'No source for module ' + module.__name__ return file, filename, descr From rhettinger@users.sourceforge.net Fri Feb 21 04:22:49 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 20:22:49 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libstringio.tex,1.6,1.6.18.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv28224 Modified Files: Tag: release22-maint libstringio.tex Log Message: Backport 1.7: Clarify when a read-only object is created. Index: libstringio.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libstringio.tex,v retrieving revision 1.6 retrieving revision 1.6.18.1 diff -C2 -d -r1.6 -r1.6.18.1 *** libstringio.tex 6 Jul 2001 20:30:11 -0000 1.6 --- libstringio.tex 21 Feb 2003 04:22:47 -0000 1.6.18.1 *************** *** 60,63 **** --- 60,68 ---- strings that cannot be encoded as plain \ASCII{} strings. + Another difference from the \refmodule{StringIO} module is that calling + \function{StringIO()} with a string parameter creates a read-only object. + Unlike an object created without a string parameter, it does not have + write methods. + The following data objects are provided as well: From rhettinger@users.sourceforge.net Fri Feb 21 05:42:15 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 21:42:15 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib liboperator.tex,1.26,1.27 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv19304a Modified Files: liboperator.tex Log Message: Fill in missing table entries. Index: liboperator.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/liboperator.tex,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** liboperator.tex 18 Jan 2003 23:22:20 -0000 1.26 --- liboperator.tex 21 Feb 2003 05:42:13 -0000 1.27 *************** *** 49,53 **** The logical operations are also generally applicable to all objects, ! and support truth tests, identity tests, and Boolean operations: \begin{funcdesc}{not_}{o} --- 49,53 ---- The logical operations are also generally applicable to all objects, ! and support truth tests, identity tests, and boolean operations: \begin{funcdesc}{not_}{o} *************** *** 329,332 **** --- 329,336 ---- \lineiii{Exponentiation}{\code{\var{a} ** \var{b}}} {\code{pow(\var{a}, \var{b})}} + \lineiii{Identity}{\code{\var{a} is \var{b}}} + {\code{is_(\var{a}, \var{b})}} + \lineiii{Identity}{\code{\var{a} is not \var{b}}} + {\code{is_not(\var{a}, \var{b})}} \lineiii{Indexed Assignment}{\code{\var{o}[\var{k}] = \var{v}}} {\code{setitem(\var{o}, \var{k}, \var{v})}} From rhettinger@users.sourceforge.net Fri Feb 21 05:59:19 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 21:59:19 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libtime.tex,1.48.6.4,1.48.6.5 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv23851 Modified Files: Tag: release22-maint libtime.tex Log Message: Backport libtime.tex 1.53: Fixed longstanding bug in the description of strftime's %W code. Index: libtime.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libtime.tex,v retrieving revision 1.48.6.4 retrieving revision 1.48.6.5 diff -C2 -d -r1.48.6.4 -r1.48.6.5 *** libtime.tex 4 Feb 2003 15:13:25 -0000 1.48.6.4 --- libtime.tex 21 Feb 2003 05:59:16 -0000 1.48.6.5 *************** *** 237,241 **** \lineiii{\%W}{Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year ! preceding the first Sunday are considered to be in week 0.}{} \lineiii{\%x}{Locale's appropriate date representation.}{} \lineiii{\%X}{Locale's appropriate time representation.}{} --- 237,241 ---- \lineiii{\%W}{Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year ! preceding the first Monday are considered to be in week 0.}{} \lineiii{\%x}{Locale's appropriate date representation.}{} \lineiii{\%X}{Locale's appropriate time representation.}{} From rhettinger@users.sourceforge.net Fri Feb 21 06:03:09 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 22:03:09 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib liburlparse.tex,1.20.6.1,1.20.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv25147 Modified Files: Tag: release22-maint liburlparse.tex Log Message: Typo Index: liburlparse.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/liburlparse.tex,v retrieving revision 1.20.6.1 retrieving revision 1.20.6.2 diff -C2 -d -r1.20.6.1 -r1.20.6.2 *** liburlparse.tex 16 Oct 2002 21:26:01 -0000 1.20.6.1 --- liburlparse.tex 21 Feb 2003 06:03:06 -0000 1.20.6.2 *************** *** 120,124 **** \seerfc{1808}{Relative Uniform Resource Locators}{ This Request For Comments includes the rules for joining an ! absolute and a relative URL, including a fair normal of ``Abnormal Examples'' which govern the treatment of border cases.} --- 120,124 ---- \seerfc{1808}{Relative Uniform Resource Locators}{ This Request For Comments includes the rules for joining an ! absolute and a relative URL, including a fair number of ``Abnormal Examples'' which govern the treatment of border cases.} From rhettinger@users.sourceforge.net Fri Feb 21 06:05:48 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 22:05:48 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libxdrlib.tex,1.23,1.23.24.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv26739 Modified Files: Tag: release22-maint libxdrlib.tex Log Message: Typo Index: libxdrlib.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libxdrlib.tex,v retrieving revision 1.23 retrieving revision 1.23.24.1 diff -C2 -d -r1.23 -r1.23.24.1 *** libxdrlib.tex 10 Oct 2000 17:02:34 -0000 1.23 --- libxdrlib.tex 21 Feb 2003 06:05:45 -0000 1.23.24.1 *************** *** 34,38 **** defined the encoding of data which was XDR at the time this module was originally written. It has ! appearantly been obsoleted by \rfc{1832}.} \seerfc{1832}{XDR: External Data Representation Standard}{Newer RFC --- 34,38 ---- defined the encoding of data which was XDR at the time this module was originally written. It has ! apparently been obsoleted by \rfc{1832}.} \seerfc{1832}{XDR: External Data Representation Standard}{Newer RFC From rhettinger@users.sourceforge.net Fri Feb 21 06:59:09 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 22:59:09 -0800 Subject: [Python-checkins] python/dist/src/Lib Cookie.py,1.11,1.11.16.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv9646 Modified Files: Tag: release22-maint Cookie.py Log Message: Spelling error Index: Cookie.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/Cookie.py,v retrieving revision 1.11 retrieving revision 1.11.16.1 diff -C2 -d -r1.11 -r1.11.16.1 *** Cookie.py 2 Aug 2001 07:15:29 -0000 1.11 --- Cookie.py 21 Feb 2003 06:59:07 -0000 1.11.16.1 *************** *** 52,56 **** Most of the time you start by creating a cookie. Cookies come in ! three flavors, each with slighly different encoding semanitcs, but more on that later. --- 52,56 ---- Most of the time you start by creating a cookie. Cookies come in ! three flavors, each with slightly different encoding semanitcs, but more on that later. From rhettinger@users.sourceforge.net Fri Feb 21 07:16:39 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 20 Feb 2003 23:16:39 -0800 Subject: [Python-checkins] python/dist/src/Lib asyncore.py,1.28.4.3,1.28.4.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv16179 Modified Files: Tag: release22-maint asyncore.py Log Message: Backport 1.38: Fix an old bug in poll(). When a signal is handled while we're blocked in select(), this will raise select.error with errno set to EINTR. The except clauses correctly ignores this error, but the rest of the logic will then call read() for all objects in select's *input* list of read file descriptors. Then when an object's read_handler() is naive, it will call recv() on its socket, which will raise an IOError, and then asyncore decides to close the socket. To fix this, we simply return in this case. Backport candidate. Backport 1.40: Fix spelling error Index: asyncore.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/asyncore.py,v retrieving revision 1.28.4.3 retrieving revision 1.28.4.4 diff -C2 -d -r1.28.4.3 -r1.28.4.4 *** asyncore.py 24 Sep 2002 17:44:40 -0000 1.28.4.3 --- asyncore.py 21 Feb 2003 07:16:37 -0000 1.28.4.4 *************** *** 85,89 **** if err[0] != EINTR: raise ! r = []; w = []; e = [] if DEBUG: --- 85,90 ---- if err[0] != EINTR: raise ! else: ! return if DEBUG: *************** *** 371,375 **** return getattr (self.socket, attr) ! # log and log_info maybe overriden to provide more sophisitcated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging. --- 372,376 ---- return getattr (self.socket, attr) ! # log and log_info maybe overriden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging # and 'log_info' is for informational, warning and error logging. From jlt63@users.sourceforge.net Fri Feb 21 12:18:19 2003 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Fri, 21 Feb 2003 04:18:19 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.73.4.14,1.73.4.15 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv8463 Modified Files: Tag: release22-maint setup.py Log Message: Patch #491107: Cygwin setup.py import workaround patch Back patched to the 2.2.x branch. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.73.4.14 retrieving revision 1.73.4.15 diff -C2 -d -r1.73.4.14 -r1.73.4.15 *** setup.py 24 Dec 2002 14:52:49 -0000 1.73.4.14 --- setup.py 21 Feb 2003 12:18:17 -0000 1.73.4.15 *************** *** 162,165 **** --- 162,171 ---- ext.name) return + # Workaround for Cygwin: Cygwin currently has fork issues when many + # modules have been imported + if self.get_platform() == 'cygwin': + self.announce('WARNING: skipping import check for Cygwin-based "%s"' + % ext.name) + return ext_filename = os.path.join( self.build_lib, From doerwalter@users.sourceforge.net Fri Feb 21 12:53:52 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 21 Feb 2003 04:53:52 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_string,1.1,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv28904/Lib/test/output Removed Files: test_string Log Message: Port all string tests to PyUnit and share as much tests between str, unicode, UserString and the string module as possible. This increases code coverage in stringobject.c from 83% to 86% and should help keep the string classes in sync in the future. From SF patch #662807 --- test_string DELETED --- From doerwalter@users.sourceforge.net Fri Feb 21 12:53:51 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 21 Feb 2003 04:53:51 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_str.py,NONE,1.1 string_tests.py,1.26,1.27 test_string.py,1.23,1.24 test_unicode.py,1.78,1.79 test_userstring.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28904/Lib/test Modified Files: string_tests.py test_string.py test_unicode.py test_userstring.py Added Files: test_str.py Log Message: Port all string tests to PyUnit and share as much tests between str, unicode, UserString and the string module as possible. This increases code coverage in stringobject.c from 83% to 86% and should help keep the string classes in sync in the future. From SF patch #662807 --- NEW FILE: test_str.py --- import unittest from test import test_support, string_tests class StrTest( string_tests.CommonTest, string_tests.MixinStrUnicodeUserStringTest, string_tests.MixinStrUserStringTest ): type2test = str # We don't need to propagate to str def fixtype(self, obj): return obj def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(StrTest)) test_support.run_suite(suite) if __name__ == "__main__": test_main() Index: string_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/string_tests.py,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** string_tests.py 12 Dec 2002 20:03:19 -0000 1.26 --- string_tests.py 21 Feb 2003 12:53:49 -0000 1.27 *************** *** 1,13 **** ! """Common tests shared by test_string and test_userstring""" ! ! import string ! from test.test_support import verify, vereq, verbose, TestFailed, have_unicode ! ! transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' from UserList import UserList class Sequence: ! def __init__(self): self.seq = 'wxyz' def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] --- 1,12 ---- ! """ ! Common tests shared by test_str, test_unicode, test_userstring and test_string. ! """ + import unittest, string, sys + from test import test_support from UserList import UserList class Sequence: ! def __init__(self, seq='wxyz'): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] *************** *** 20,331 **** def __len__(self): return 8 ! def run_module_tests(test): ! """Run all tests that exercise a function in the string module""" ! test('atoi', " 1 ", 1) ! test('atoi', " 1x", ValueError) ! test('atoi', " x1 ", ValueError) ! test('atol', " 1 ", 1L) ! test('atol', " 1x ", ValueError) ! test('atol', " x1 ", ValueError) ! test('atof', " 1 ", 1.0) ! test('atof', " 1x ", ValueError) ! test('atof', " x1 ", ValueError) ! test('maketrans', 'abc', transtable, 'xyz') ! test('maketrans', 'abc', ValueError, 'xyzq') ! # join now works with any sequence type ! test('join', ['a', 'b', 'c', 'd'], 'a b c d') ! test('join', ('a', 'b', 'c', 'd'), 'abcd', '') ! test('join', Sequence(), 'w x y z') ! test('join', 7, TypeError) ! test('join', BadSeq1(), TypeError) ! test('join', BadSeq2(), 'a b c') ! # try a few long ones ! print ":".join(['x' * 100] * 100) ! print ":".join(('x' * 100,) * 100) ! def run_method_tests(test): ! """Run all tests that exercise a method of a string object""" ! test('capitalize', ' hello ', ' hello ') ! test('capitalize', 'hello ', 'Hello ') ! test('capitalize', 'aaaa', 'Aaaa') ! test('capitalize', 'AaAa', 'Aaaa') ! test('count', 'aaa', 3, 'a') ! test('count', 'aaa', 0, 'b') ! test('find', 'abcdefghiabc', 0, 'abc') ! test('find', 'abcdefghiabc', 9, 'abc', 1) ! test('find', 'abcdefghiabc', -1, 'def', 4) ! test('rfind', 'abcdefghiabc', 9, 'abc') ! test('lower', 'HeLLo', 'hello') ! test('lower', 'hello', 'hello') ! test('upper', 'HeLLo', 'HELLO') ! test('upper', 'HELLO', 'HELLO') ! test('title', ' hello ', ' Hello ') ! test('title', 'hello ', 'Hello ') ! test('title', "fOrMaT thIs aS titLe String", 'Format This As Title String') ! test('title', "fOrMaT,thIs-aS*titLe;String", 'Format,This-As*Title;String') ! test('title', "getInt", 'Getint') ! test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi') ! test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 8) ! test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 4) ! test('expandtabs', 'abc\r\nab\tdef\ng\thi', 'abc\r\nab def\ng hi', 4) ! test('islower', 'a', 1) ! test('islower', 'A', 0) ! test('islower', '\n', 0) ! test('islower', 'abc', 1) ! test('islower', 'aBc', 0) ! test('islower', 'abc\n', 1) ! test('isupper', 'a', 0) ! test('isupper', 'A', 1) ! test('isupper', '\n', 0) ! test('isupper', 'ABC', 1) ! test('isupper', 'AbC', 0) ! test('isupper', 'ABC\n', 1) ! test('istitle', 'a', 0) ! test('istitle', 'A', 1) ! test('istitle', '\n', 0) ! test('istitle', 'A Titlecased Line', 1) ! test('istitle', 'A\nTitlecased Line', 1) ! test('istitle', 'A Titlecased, Line', 1) ! test('istitle', 'Not a capitalized String', 0) ! test('istitle', 'Not\ta Titlecase String', 0) ! test('istitle', 'Not--a Titlecase String', 0) ! test('isalpha', 'a', 1) ! test('isalpha', 'A', 1) ! test('isalpha', '\n', 0) ! test('isalpha', 'abc', 1) ! test('isalpha', 'aBc123', 0) ! test('isalpha', 'abc\n', 0) ! test('isalnum', 'a', 1) ! test('isalnum', 'A', 1) ! test('isalnum', '\n', 0) ! test('isalnum', '123abc456', 1) ! test('isalnum', 'a1b3c', 1) ! test('isalnum', 'aBc000 ', 0) ! test('isalnum', 'abc\n', 0) ! # join now works with any sequence type ! test('join', ' ', 'a b c d', ['a', 'b', 'c', 'd']) ! test('join', '', 'abcd', ('a', 'b', 'c', 'd')) ! test('join', ' ', 'w x y z', Sequence()) ! test('join', 'a', 'abc', ('abc',)) ! test('join', 'a', 'z', UserList(['z'])) ! if have_unicode: ! test('join', unicode('.'), unicode('a.b.c'), ['a', 'b', 'c']) ! test('join', '.', unicode('a.b.c'), [unicode('a'), 'b', 'c']) ! test('join', '.', unicode('a.b.c'), ['a', unicode('b'), 'c']) ! test('join', '.', unicode('a.b.c'), ['a', 'b', unicode('c')]) ! test('join', '.', TypeError, ['a', unicode('b'), 3]) ! for i in [5, 25, 125]: ! test('join', '-', ((('a' * i) + '-') * i)[:-1], ! ['a' * i] * i) ! test('join', ' ', TypeError, BadSeq1()) ! test('join', ' ', 'a b c', BadSeq2()) ! test('splitlines', "abc\ndef\n\rghi", ['abc', 'def', '', 'ghi']) ! test('splitlines', "abc\ndef\n\r\nghi", ['abc', 'def', '', 'ghi']) ! test('splitlines', "abc\ndef\r\nghi", ['abc', 'def', 'ghi']) ! test('splitlines', "abc\ndef\r\nghi\n", ['abc', 'def', 'ghi']) ! test('splitlines', "abc\ndef\r\nghi\n\r", ['abc', 'def', 'ghi', '']) ! test('splitlines', "\nabc\ndef\r\nghi\n\r", ['', 'abc', 'def', 'ghi', '']) ! test('splitlines', "\nabc\ndef\r\nghi\n\r", ['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], 1) ! test('split', 'this is the split function', ! ['this', 'is', 'the', 'split', 'function']) ! test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|') ! test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2) ! test('split', 'a b c d', ['a', 'b c d'], None, 1) ! test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) ! test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3) ! test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4) ! test('split', 'a b c d', ['a b c d'], None, 0) ! test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) ! test('split', 'a b c d ', ['a', 'b', 'c', 'd']) ! test('strip', ' hello ', 'hello') ! test('lstrip', ' hello ', 'hello ') ! test('rstrip', ' hello ', ' hello') ! test('strip', 'hello', 'hello') ! # strip/lstrip/rstrip with None arg ! test('strip', ' hello ', 'hello', None) ! test('lstrip', ' hello ', 'hello ', None) ! test('rstrip', ' hello ', ' hello', None) ! test('strip', 'hello', 'hello', None) ! # strip/lstrip/rstrip with str arg ! test('strip', 'xyzzyhelloxyzzy', 'hello', 'xyz') ! test('lstrip', 'xyzzyhelloxyzzy', 'helloxyzzy', 'xyz') ! test('rstrip', 'xyzzyhelloxyzzy', 'xyzzyhello', 'xyz') ! test('strip', 'hello', 'hello', 'xyz') ! # strip/lstrip/rstrip with unicode arg ! if have_unicode: ! test('strip', 'xyzzyhelloxyzzy', ! unicode('hello', 'ascii'), unicode('xyz', 'ascii')) ! test('lstrip', 'xyzzyhelloxyzzy', ! unicode('helloxyzzy', 'ascii'), unicode('xyz', 'ascii')) ! test('rstrip', 'xyzzyhelloxyzzy', ! unicode('xyzzyhello', 'ascii'), unicode('xyz', 'ascii')) ! test('strip', 'hello', ! unicode('hello', 'ascii'), unicode('xyz', 'ascii')) ! test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS') ! test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def') ! table = string.maketrans('a', 'A') ! test('translate', 'abc', 'Abc', table) ! test('translate', 'xyz', 'xyz', table) ! test('translate', 'xyz', ValueError, 'too short', 'strip') ! test('translate', 'xyz', ValueError, 'too short') ! test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1) ! test('replace', 'one!two!three!', 'onetwothree', '!', '') ! test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2) ! test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3) ! test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4) ! test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0) ! test('replace', 'one!two!three!', 'one@two@three@', '!', '@') ! test('replace', 'one!two!three!', 'one!two!three!', 'x', '@') ! test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2) ! test('replace', 'abc', '-a-b-c-', '', '-') ! test('replace', 'abc', '-a-b-c', '', '-', 3) ! test('replace', 'abc', 'abc', '', '-', 0) ! test('replace', '', '', '', '') ! # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with ! # MemoryError due to empty result (platform malloc issue when requesting ! # 0 bytes). ! test('replace', '123', '', '123', '') ! test('replace', '123123', '', '123', '') ! test('replace', '123x123', 'x', '123', '') ! test('startswith', 'hello', 1, 'he') ! test('startswith', 'hello', 1, 'hello') ! test('startswith', 'hello', 0, 'hello world') ! test('startswith', 'hello', 1, '') ! test('startswith', 'hello', 0, 'ello') ! test('startswith', 'hello', 1, 'ello', 1) ! test('startswith', 'hello', 1, 'o', 4) ! test('startswith', 'hello', 0, 'o', 5) ! test('startswith', 'hello', 1, '', 5) ! test('startswith', 'hello', 0, 'lo', 6) ! test('startswith', 'helloworld', 1, 'lowo', 3) ! test('startswith', 'helloworld', 1, 'lowo', 3, 7) ! test('startswith', 'helloworld', 0, 'lowo', 3, 6) ! # test negative indices in startswith ! test('startswith', 'hello', 1, 'he', 0, -1) ! test('startswith', 'hello', 1, 'he', -53, -1) ! test('startswith', 'hello', 0, 'hello', 0, -1) ! test('startswith', 'hello', 0, 'hello world', -1, -10) ! test('startswith', 'hello', 0, 'ello', -5) ! test('startswith', 'hello', 1, 'ello', -4) ! test('startswith', 'hello', 0, 'o', -2) ! test('startswith', 'hello', 1, 'o', -1) ! test('startswith', 'hello', 1, '', -3, -3) ! test('startswith', 'hello', 0, 'lo', -9) ! test('endswith', 'hello', 1, 'lo') ! test('endswith', 'hello', 0, 'he') ! test('endswith', 'hello', 1, '') ! test('endswith', 'hello', 0, 'hello world') ! test('endswith', 'helloworld', 0, 'worl') ! test('endswith', 'helloworld', 1, 'worl', 3, 9) ! test('endswith', 'helloworld', 1, 'world', 3, 12) ! test('endswith', 'helloworld', 1, 'lowo', 1, 7) ! test('endswith', 'helloworld', 1, 'lowo', 2, 7) ! test('endswith', 'helloworld', 1, 'lowo', 3, 7) ! test('endswith', 'helloworld', 0, 'lowo', 4, 7) ! test('endswith', 'helloworld', 0, 'lowo', 3, 8) ! test('endswith', 'ab', 0, 'ab', 0, 1) ! test('endswith', 'ab', 0, 'ab', 0, 0) ! # test negative indices in endswith ! test('endswith', 'hello', 1, 'lo', -2) ! test('endswith', 'hello', 0, 'he', -2) ! test('endswith', 'hello', 1, '', -3, -3) ! test('endswith', 'hello', 0, 'hello world', -10, -2) ! test('endswith', 'helloworld', 0, 'worl', -6) ! test('endswith', 'helloworld', 1, 'worl', -5, -1) ! test('endswith', 'helloworld', 1, 'worl', -5, 9) ! test('endswith', 'helloworld', 1, 'world', -7, 12) ! test('endswith', 'helloworld', 1, 'lowo', -99, -3) ! test('endswith', 'helloworld', 1, 'lowo', -8, -3) ! test('endswith', 'helloworld', 1, 'lowo', -7, -3) ! test('endswith', 'helloworld', 0, 'lowo', 3, -4) ! test('endswith', 'helloworld', 0, 'lowo', -8, -2) ! test('zfill', '123', '123', 2) ! test('zfill', '123', '123', 3) ! test('zfill', '123', '0123', 4) ! test('zfill', '+123', '+123', 3) ! test('zfill', '+123', '+123', 4) ! test('zfill', '+123', '+0123', 5) ! test('zfill', '-123', '-123', 3) ! test('zfill', '-123', '-123', 4) ! test('zfill', '-123', '-0123', 5) ! test('zfill', '', '000', 3) ! test('zfill', '34', '34', 1) ! test('zfill', '34', '0034', 4) ! test('__mod__', '+%s+', '+hello+', 'hello') ! test('__mod__', '+%d+', '+10+', 10) ! # Encoding/decoding ! codecs = [('rot13', 'uryyb jbeyq'), ! ('base64', 'aGVsbG8gd29ybGQ=\n'), ! ('hex', '68656c6c6f20776f726c64'), ! ('uu', 'begin 666 \n+:&5L;&\\@=V]R;&0 \n \nend\n')] ! for encoding, data in codecs: ! test('encode', 'hello world', data, encoding) ! test('decode', data, 'hello world', encoding) ! # zlib is optional, so we make the test optional too... ! try: ! import zlib ! except ImportError: ! pass ! else: ! data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' ! verify('hello world'.encode('zlib') == data) ! verify(data.decode('zlib') == 'hello world') ! def test_exception(lhs, rhs, msg): ! try: ! lhs in rhs ! except TypeError: ! pass ! else: ! raise TestFailed, msg ! def run_contains_tests(test): ! test('__contains__', '', True, '') # vereq('' in '', True) ! test('__contains__', 'abc', True, '') # vereq('' in 'abc', True) ! test('__contains__', 'abc', False, '\0') # vereq('\0' in 'abc', False) ! test('__contains__', '\0abc', True, '\0') # vereq('\0' in '\0abc', True) ! test('__contains__', 'abc\0', True, '\0') # vereq('\0' in 'abc\0', True) ! test('__contains__', '\0abc', True, 'a') # vereq('a' in '\0abc', True) ! test('__contains__', 'asdf', True, 'asdf') # vereq('asdf' in 'asdf', True) ! test('__contains__', 'asd', False, 'asdf') # vereq('asdf' in 'asd', False) ! test('__contains__', '', False, 'asdf') # vereq('asdf' in '', False) ! def run_inplace_tests(constructor): ! # Verify clearing of SF bug #592573 ! s = t = constructor('abc') ! s += constructor('def') ! verify(s != t, 'in-place concatenate should create a new object') --- 19,630 ---- def __len__(self): return 8 ! class CommonTest(unittest.TestCase): ! # This testcase contains test that can be used in all ! # stringlike classes. Currently this is str, unicode ! # UserString and the string module. ! # The type to be tested ! # Change in subclasses to change the behaviour of fixtesttype() ! type2test = None ! # All tests pass their arguments to the testing methods ! # as str objects. fixtesttype() can be used to propagate ! # these arguments to the appropriate type ! def fixtype(self, obj): ! if isinstance(obj, str): ! return self.__class__.type2test(obj) ! elif isinstance(obj, list): ! return [self.fixtype(x) for x in obj] ! elif isinstance(obj, tuple): ! return tuple([self.fixtype(x) for x in obj]) ! elif isinstance(obj, dict): ! return dict([ ! (self.fixtype(key), self.fixtype(value)) ! for (key, value) in obj.iteritems() ! ]) ! else: ! return obj ! # check that object.method(*args) returns result ! def checkequal(self, result, object, methodname, *args): ! result = self.fixtype(result) ! object = self.fixtype(object) ! args = self.fixtype(args) ! realresult = getattr(object, methodname)(*args) ! self.assertEqual( ! result, ! realresult ! ) ! # if the original is returned make sure that ! # this doesn't happen with subclasses ! if object == realresult: ! class subtype(self.__class__.type2test): ! pass ! object = subtype(object) ! realresult = getattr(object, methodname)(*args) ! self.assert_(object is not realresult) ! # check that object.method(*args) raises exc ! def checkraises(self, exc, object, methodname, *args): ! object = self.fixtype(object) ! args = self.fixtype(args) ! self.assertRaises( ! exc, ! getattr(object, methodname), ! *args ! ) ! # call object.method(*args) without any checks ! def checkcall(self, object, methodname, *args): ! object = self.fixtype(object) ! args = self.fixtype(args) ! getattr(object, methodname)(*args) + def test_capitalize(self): + self.checkequal(' hello ', ' hello ', 'capitalize') + self.checkequal('Hello ', 'Hello ','capitalize') + self.checkequal('Hello ', 'hello ','capitalize') + self.checkequal('Aaaa', 'aaaa', 'capitalize') + self.checkequal('Aaaa', 'AaAa', 'capitalize') ! self.checkraises(TypeError, 'hello', 'capitalize', 42) ! def test_count(self): ! self.checkequal(3, 'aaa', 'count', 'a') ! self.checkequal(0, 'aaa', 'count', 'b') ! self.checkequal(3, 'aaa', 'count', 'a') ! self.checkequal(0, 'aaa', 'count', 'b') ! self.checkequal(3, 'aaa', 'count', 'a') ! self.checkequal(0, 'aaa', 'count', 'b') ! self.checkequal(0, 'aaa', 'count', 'b') ! self.checkequal(1, 'aaa', 'count', 'a', -1) ! self.checkequal(3, 'aaa', 'count', 'a', -10) ! self.checkequal(2, 'aaa', 'count', 'a', 0, -1) ! self.checkequal(0, 'aaa', 'count', 'a', 0, -10) ! self.checkraises(TypeError, 'hello', 'count') ! self.checkraises(TypeError, 'hello', 'count', 42) ! def test_find(self): ! self.checkequal(0, 'abcdefghiabc', 'find', 'abc') ! self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1) ! self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4) ! self.checkraises(TypeError, 'hello', 'find') ! self.checkraises(TypeError, 'hello', 'find', 42) ! def test_rfind(self): ! self.checkequal(9, 'abcdefghiabc', 'rfind', 'abc') ! self.checkequal(12, 'abcdefghiabc', 'rfind', '') ! self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd') ! self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz') ! self.checkraises(TypeError, 'hello', 'rfind') ! self.checkraises(TypeError, 'hello', 'rfind', 42) ! def test_index(self): ! self.checkequal(0, 'abcdefghiabc', 'index', '') ! self.checkequal(3, 'abcdefghiabc', 'index', 'def') ! self.checkequal(0, 'abcdefghiabc', 'index', 'abc') ! self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1) ! self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib') ! self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1) ! self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8) ! self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1) ! self.checkraises(TypeError, 'hello', 'index') ! self.checkraises(TypeError, 'hello', 'index', 42) ! def test_rindex(self): ! self.checkequal(12, 'abcdefghiabc', 'rindex', '') ! self.checkequal(3, 'abcdefghiabc', 'rindex', 'def') ! self.checkequal(9, 'abcdefghiabc', 'rindex', 'abc') ! self.checkequal(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1) ! self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib') ! self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1) ! self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1) ! self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8) ! self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1) ! self.checkraises(TypeError, 'hello', 'rindex') ! self.checkraises(TypeError, 'hello', 'rindex', 42) ! def test_lower(self): ! self.checkequal('hello', 'HeLLo', 'lower') ! self.checkequal('hello', 'hello', 'lower') ! self.checkraises(TypeError, 'hello', 'lower', 42) ! def test_upper(self): ! self.checkequal('HELLO', 'HeLLo', 'upper') ! self.checkequal('HELLO', 'HELLO', 'upper') ! self.checkraises(TypeError, 'hello', 'upper', 42) ! def test_expandtabs(self): ! self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') ! self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) ! self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4) ! self.checkequal('abc\r\nab def\ng hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4) ! self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs') ! self.checkequal('abc\rab def\ng hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8) ! self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4) ! self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42) ! def test_split(self): ! self.checkequal(['this', 'is', 'the', 'split', 'function'], ! 'this is the split function', 'split') ! self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|') ! self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2) ! self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1) ! self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2) ! self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3) ! self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4) ! self.checkequal(['a b c d'], 'a b c d', 'split', None, 0) ! self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2) ! self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split') ! self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//') ! self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test') ! self.checkraises(TypeError, 'hello', 'split', 42, 42, 42) ! def test_strip(self): ! self.checkequal('hello', ' hello ', 'strip') ! self.checkequal('hello ', ' hello ', 'lstrip') ! self.checkequal(' hello', ' hello ', 'rstrip') ! self.checkequal('hello', 'hello', 'strip') ! def test_ljust(self): ! self.checkequal('abc ', 'abc', 'ljust', 10) ! self.checkequal('abc ', 'abc', 'ljust', 6) ! self.checkequal('abc', 'abc', 'ljust', 3) ! self.checkequal('abc', 'abc', 'ljust', 2) ! self.checkraises(TypeError, 'abc', 'ljust') ! def test_rjust(self): ! self.checkequal(' abc', 'abc', 'rjust', 10) ! self.checkequal(' abc', 'abc', 'rjust', 6) ! self.checkequal('abc', 'abc', 'rjust', 3) ! self.checkequal('abc', 'abc', 'rjust', 2) ! self.checkraises(TypeError, 'abc', 'rjust') ! def test_center(self): ! self.checkequal(' abc ', 'abc', 'center', 10) ! self.checkequal(' abc ', 'abc', 'center', 6) ! self.checkequal('abc', 'abc', 'center', 3) ! self.checkequal('abc', 'abc', 'center', 2) ! self.checkraises(TypeError, 'abc', 'center') ! def test_swapcase(self): ! self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase') ! self.checkraises(TypeError, 'hello', 'swapcase', 42) ! def test_replace(self): ! self.checkequal('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1) ! self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '') ! self.checkequal('one@two@three!', 'one!two!three!', 'replace', '!', '@', 2) ! self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 3) ! self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@', 4) ! self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0) ! self.checkequal('one@two@three@', 'one!two!three!', 'replace', '!', '@') ! self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@') ! self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2) ! self.checkequal('-a-b-c-', 'abc', 'replace', '', '-') ! self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3) ! self.checkequal('abc', 'abc', 'replace', '', '-', 0) ! self.checkequal('', '', 'replace', '', '') ! self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0) ! self.checkequal('abc', 'abc', 'replace', 'xy', '--') ! # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with ! # MemoryError due to empty result (platform malloc issue when requesting ! # 0 bytes). ! self.checkequal('', '123', 'replace', '123', '') ! self.checkequal('', '123123', 'replace', '123', '') ! self.checkequal('x', '123x123', 'replace', '123', '') ! self.checkraises(TypeError, 'hello', 'replace') ! self.checkraises(TypeError, 'hello', 'replace', 42) ! self.checkraises(TypeError, 'hello', 'replace', 42, 'h') ! self.checkraises(TypeError, 'hello', 'replace', 'h', 42) ! def test_zfill(self): ! self.checkequal('123', '123', 'zfill', 2) ! self.checkequal('123', '123', 'zfill', 3) ! self.checkequal('0123', '123', 'zfill', 4) ! self.checkequal('+123', '+123', 'zfill', 3) ! self.checkequal('+123', '+123', 'zfill', 4) ! self.checkequal('+0123', '+123', 'zfill', 5) ! self.checkequal('-123', '-123', 'zfill', 3) ! self.checkequal('-123', '-123', 'zfill', 4) ! self.checkequal('-0123', '-123', 'zfill', 5) ! self.checkequal('000', '', 'zfill', 3) ! self.checkequal('34', '34', 'zfill', 1) ! self.checkequal('0034', '34', 'zfill', 4) ! self.checkraises(TypeError, '123', 'zfill') ! ! class MixinStrUnicodeUserStringTest: ! # additional tests that only work for ! # stringlike objects, i.e. str, unicode, UserString ! # (but not the string module) ! ! def test_islower(self): ! self.checkequal(False, '', 'islower') ! self.checkequal(True, 'a', 'islower') ! self.checkequal(False, 'A', 'islower') ! self.checkequal(False, '\n', 'islower') ! self.checkequal(True, 'abc', 'islower') ! self.checkequal(False, 'aBc', 'islower') ! self.checkequal(True, 'abc\n', 'islower') ! self.checkraises(TypeError, 'abc', 'islower', 42) ! ! def test_isupper(self): ! self.checkequal(False, '', 'isupper') ! self.checkequal(False, 'a', 'isupper') ! self.checkequal(True, 'A', 'isupper') ! self.checkequal(False, '\n', 'isupper') ! self.checkequal(True, 'ABC', 'isupper') ! self.checkequal(False, 'AbC', 'isupper') ! self.checkequal(True, 'ABC\n', 'isupper') ! self.checkraises(TypeError, 'abc', 'isupper', 42) ! ! def test_istitle(self): ! self.checkequal(False, '', 'istitle') ! self.checkequal(False, 'a', 'istitle') ! self.checkequal(True, 'A', 'istitle') ! self.checkequal(False, '\n', 'istitle') ! self.checkequal(True, 'A Titlecased Line', 'istitle') ! self.checkequal(True, 'A\nTitlecased Line', 'istitle') ! self.checkequal(True, 'A Titlecased, Line', 'istitle') ! self.checkequal(False, 'Not a capitalized String', 'istitle') ! self.checkequal(False, 'Not\ta Titlecase String', 'istitle') ! self.checkequal(False, 'Not--a Titlecase String', 'istitle') ! self.checkequal(False, 'NOT', 'istitle') ! self.checkraises(TypeError, 'abc', 'istitle', 42) ! ! def test_isspace(self): ! self.checkequal(False, '', 'isspace') ! self.checkequal(False, 'a', 'isspace') ! self.checkequal(True, ' ', 'isspace') ! self.checkequal(True, '\t', 'isspace') ! self.checkequal(True, '\r', 'isspace') ! self.checkequal(True, '\n', 'isspace') ! self.checkequal(True, ' \t\r\n', 'isspace') ! self.checkequal(False, ' \t\r\na', 'isspace') ! self.checkraises(TypeError, 'abc', 'isspace', 42) ! ! def test_isalpha(self): ! self.checkequal(False, '', 'isalpha') ! self.checkequal(True, 'a', 'isalpha') ! self.checkequal(True, 'A', 'isalpha') ! self.checkequal(False, '\n', 'isalpha') ! self.checkequal(True, 'abc', 'isalpha') ! self.checkequal(False, 'aBc123', 'isalpha') ! self.checkequal(False, 'abc\n', 'isalpha') ! self.checkraises(TypeError, 'abc', 'isalpha', 42) ! ! def test_isalnum(self): ! self.checkequal(False, '', 'isalnum') ! self.checkequal(True, 'a', 'isalnum') ! self.checkequal(True, 'A', 'isalnum') ! self.checkequal(False, '\n', 'isalnum') ! self.checkequal(True, '123abc456', 'isalnum') ! self.checkequal(True, 'a1b3c', 'isalnum') ! self.checkequal(False, 'aBc000 ', 'isalnum') ! self.checkequal(False, 'abc\n', 'isalnum') ! self.checkraises(TypeError, 'abc', 'isalnum', 42) ! ! def test_isdigit(self): ! self.checkequal(False, '', 'isdigit') ! self.checkequal(False, 'a', 'isdigit') ! self.checkequal(True, '0', 'isdigit') ! self.checkequal(True, '0123456789', 'isdigit') ! self.checkequal(False, '0123456789a', 'isdigit') ! ! self.checkraises(TypeError, 'abc', 'isdigit', 42) ! ! def test_title(self): ! self.checkequal(' Hello ', ' hello ', 'title') ! self.checkequal('Hello ', 'hello ', 'title') ! self.checkequal('Hello ', 'Hello ', 'title') ! self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title') ! self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', ) ! self.checkequal('Getint', "getInt", 'title') ! self.checkraises(TypeError, 'hello', 'title', 42) ! ! def test_splitlines(self): ! self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines') ! self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines') ! self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines') ! self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines') ! self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines') ! self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines') ! self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1) ! ! self.checkraises(TypeError, 'abc', 'splitlines', 42, 42) ! ! def test_startswith(self): ! self.checkequal(True, 'hello', 'startswith', 'he') ! self.checkequal(True, 'hello', 'startswith', 'hello') ! self.checkequal(False, 'hello', 'startswith', 'hello world') ! self.checkequal(True, 'hello', 'startswith', '') ! self.checkequal(False, 'hello', 'startswith', 'ello') ! self.checkequal(True, 'hello', 'startswith', 'ello', 1) ! self.checkequal(True, 'hello', 'startswith', 'o', 4) ! self.checkequal(False, 'hello', 'startswith', 'o', 5) ! self.checkequal(True, 'hello', 'startswith', '', 5) ! self.checkequal(False, 'hello', 'startswith', 'lo', 6) ! self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3) ! self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7) ! self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6) ! ! # test negative indices ! self.checkequal(True, 'hello', 'startswith', 'he', 0, -1) ! self.checkequal(True, 'hello', 'startswith', 'he', -53, -1) ! self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1) ! self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10) ! self.checkequal(False, 'hello', 'startswith', 'ello', -5) ! self.checkequal(True, 'hello', 'startswith', 'ello', -4) ! self.checkequal(False, 'hello', 'startswith', 'o', -2) ! self.checkequal(True, 'hello', 'startswith', 'o', -1) ! self.checkequal(True, 'hello', 'startswith', '', -3, -3) ! self.checkequal(False, 'hello', 'startswith', 'lo', -9) ! ! self.checkraises(TypeError, 'hello', 'startswith') ! self.checkraises(TypeError, 'hello', 'startswith', 42) ! ! def test_endswith(self): ! self.checkequal(True, 'hello', 'endswith', 'lo') ! self.checkequal(False, 'hello', 'endswith', 'he') ! self.checkequal(True, 'hello', 'endswith', '') ! self.checkequal(False, 'hello', 'endswith', 'hello world') ! self.checkequal(False, 'helloworld', 'endswith', 'worl') ! self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9) ! self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7) ! self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7) ! self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8) ! self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1) ! self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0) ! ! # test negative indices ! self.checkequal(True, 'hello', 'endswith', 'lo', -2) ! self.checkequal(False, 'hello', 'endswith', 'he', -2) ! self.checkequal(True, 'hello', 'endswith', '', -3, -3) ! self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2) ! self.checkequal(False, 'helloworld', 'endswith', 'worl', -6) ! self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1) ! self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9) ! self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3) ! self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3) ! self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4) ! self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2) ! ! self.checkraises(TypeError, 'hello', 'endswith') ! self.checkraises(TypeError, 'hello', 'endswith', 42) ! ! def test_strip_args(self): ! # strip/lstrip/rstrip with None arg ! self.checkequal('hello', ' hello ', 'strip', None) ! self.checkequal('hello ', ' hello ', 'lstrip', None) ! self.checkequal(' hello', ' hello ', 'rstrip', None) ! self.checkequal('hello', 'hello', 'strip', None) ! ! # strip/lstrip/rstrip with str arg ! self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz') ! self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz') ! self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz') ! self.checkequal('hello', 'hello', 'strip', 'xyz') ! ! # strip/lstrip/rstrip with unicode arg ! if test_support.have_unicode: ! self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy', ! 'strip', unicode('xyz', 'ascii')) ! self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy', ! 'lstrip', unicode('xyz', 'ascii')) ! self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy', ! 'rstrip', unicode('xyz', 'ascii')) ! self.checkequal(unicode('hello', 'ascii'), 'hello', ! 'strip', unicode('xyz', 'ascii')) ! ! self.checkraises(TypeError, 'hello', 'strip', 42, 42) ! self.checkraises(TypeError, 'hello', 'lstrip', 42, 42) ! self.checkraises(TypeError, 'hello', 'rstrip', 42, 42) ! ! def test___contains__(self): ! self.checkequal(True, '', '__contains__', '') # vereq('' in '', True) ! self.checkequal(True, 'abc', '__contains__', '') # vereq('' in 'abc', True) ! self.checkequal(False, 'abc', '__contains__', '\0') # vereq('\0' in 'abc', False) ! self.checkequal(True, '\0abc', '__contains__', '\0') # vereq('\0' in '\0abc', True) ! self.checkequal(True, 'abc\0', '__contains__', '\0') # vereq('\0' in 'abc\0', True) ! self.checkequal(True, '\0abc', '__contains__', 'a') # vereq('a' in '\0abc', True) ! self.checkequal(True, 'asdf', '__contains__', 'asdf') # vereq('asdf' in 'asdf', True) ! self.checkequal(False, 'asd', '__contains__', 'asdf') # vereq('asdf' in 'asd', False) ! self.checkequal(False, '', '__contains__', 'asdf') # vereq('asdf' in '', False) ! ! def test_subscript(self): ! self.checkequal(u'a', 'abc', '__getitem__', 0) ! self.checkequal(u'c', 'abc', '__getitem__', -1) ! self.checkequal(u'a', 'abc', '__getitem__', 0L) ! self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3)) ! self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000)) ! self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1)) ! self.checkequal(u'', 'abc', '__getitem__', slice(0, 0)) ! # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice) ! ! self.checkraises(TypeError, 'abc', '__getitem__', 'def') ! ! def test_slice(self): ! self.checkequal('abc', 'abc', '__getslice__', 0, 1000) ! self.checkequal('abc', 'abc', '__getslice__', 0, 3) ! self.checkequal('ab', 'abc', '__getslice__', 0, 2) ! self.checkequal('bc', 'abc', '__getslice__', 1, 3) ! self.checkequal('b', 'abc', '__getslice__', 1, 2) ! self.checkequal('', 'abc', '__getslice__', 2, 2) ! self.checkequal('', 'abc', '__getslice__', 1000, 1000) ! self.checkequal('', 'abc', '__getslice__', 2000, 1000) ! self.checkequal('', 'abc', '__getslice__', 2, 1) ! # FIXME What about negative indizes? This is handled differently by [] and __getslice__ ! ! self.checkraises(TypeError, 'abc', '__getslice__', 'def') ! ! def test_mul(self): ! self.checkequal('', 'abc', '__mul__', -1) ! self.checkequal('', 'abc', '__mul__', 0) ! self.checkequal('abc', 'abc', '__mul__', 1) ! self.checkequal('abcabcabc', 'abc', '__mul__', 3) ! self.checkraises(TypeError, 'abc', '__mul__') ! self.checkraises(TypeError, 'abc', '__mul__', '') ! self.checkraises(OverflowError, 10000*'abc', '__mul__', sys.maxint) ! ! def test_join(self): ! # join now works with any sequence type ! # moved here, because the argument order is ! # different in string.join (see the test in ! # test.test_string.StringTest.test_join) ! self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) ! self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd')) ! self.checkequal('w x y z', ' ', 'join', Sequence()) ! self.checkequal('abc', 'a', 'join', ('abc',)) ! self.checkequal('z', 'a', 'join', UserList(['z'])) ! if test_support.have_unicode: ! self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c']) ! self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c']) ! self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c']) ! self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')]) ! self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3]) ! for i in [5, 25, 125]: ! self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ! ['a' * i] * i) ! self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ! ('a' * i,) * i) ! ! self.checkraises(TypeError, ' ', 'join', BadSeq1()) ! self.checkequal('a b c', ' ', 'join', BadSeq2()) ! ! self.checkraises(TypeError, ' ', 'join') ! self.checkraises(TypeError, ' ', 'join', 7) ! self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L])) ! ! def test_formatting(self): ! self.checkequal('+hello+', '+%s+', '__mod__', 'hello') ! self.checkequal('+10+', '+%d+', '__mod__', 10) ! self.checkequal('a', "%c", '__mod__', "a") ! self.checkequal('a', "%c", '__mod__', "a") ! self.checkequal('"', "%c", '__mod__', 34) ! self.checkequal('$', "%c", '__mod__', 36) ! self.checkequal('10', "%d", '__mod__', 10) ! ! for ordinal in (-100, 0x200000): ! # unicode raises ValueError, str raises OverflowError ! self.checkraises((ValueError, OverflowError), '%c', '__mod__', ordinal) ! ! self.checkequal(' 42', '%3ld', '__mod__', 42) ! self.checkequal('0042.00', '%07.2f', '__mod__', 42) ! ! self.checkraises(TypeError, 'abc', '__mod__') ! self.checkraises(TypeError, '%(foo)s', '__mod__', 42) ! self.checkraises(TypeError, '%s%s', '__mod__', (42,)) ! self.checkraises(TypeError, '%c', '__mod__', (None,)) ! self.checkraises(ValueError, '%(foo', '__mod__', {}) ! self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42)) ! ! # argument names with properly nested brackets are supported ! self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'}) ! ! # 100 is a magic number in PyUnicode_Format, this forces a resize ! self.checkequal(103*'a'+'x', '%sx', '__mod__', 103*'a') ! ! self.checkraises(TypeError, '%*s', '__mod__', ('foo', 'bar')) ! self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.)) ! self.checkraises(ValueError, '%10', '__mod__', (42,)) ! ! def test_floatformatting(self): ! # float formatting ! for prec in xrange(100): ! format = '%%.%if' % prec ! value = 0.01 ! for x in xrange(60): ! value = value * 3.141592655 / 3.0 * 10.0 ! # The formatfloat() code in stringobject.c and ! # unicodeobject.c uses a 120 byte buffer and switches from ! # 'f' formatting to 'g' at precision 50, so we expect ! # OverflowErrors for the ranges x < 50 and prec >= 67. ! if x < 50 and prec >= 67: ! self.checkraises(OverflowError, format, "__mod__", value) ! else: ! self.checkcall(format, "__mod__", value) ! ! class MixinStrStringUserStringTest: ! # Additional tests for 8bit strings, i.e. str, UserString and ! # the string module ! ! def test_maketrans(self): ! self.assertEqual( ! ''.join(map(chr, xrange(256))).replace('abc', 'xyz'), ! string.maketrans('abc', 'xyz') ! ) ! self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw') ! ! def test_translate(self): ! table = string.maketrans('abc', 'xyz') ! self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def') ! ! table = string.maketrans('a', 'A') ! self.checkequal('Abc', 'abc', 'translate', table) ! self.checkequal('xyz', 'xyz', 'translate', table) ! self.checkequal('yz', 'xyz', 'translate', table, 'x') ! self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip') ! self.checkraises(ValueError, 'xyz', 'translate', 'too short') ! ! ! class MixinStrUserStringTest: ! # Additional tests that only work with ! # 8bit compatible object, i.e. str and UserString ! ! def test_encoding_decoding(self): ! codecs = [('rot13', 'uryyb jbeyq'), ! ('base64', 'aGVsbG8gd29ybGQ=\n'), ! ('hex', '68656c6c6f20776f726c64'), ! ('uu', 'begin 666 \n+:&5L;&\\@=V]R;&0 \n \nend\n')] ! for encoding, data in codecs: ! self.checkequal(data, 'hello world', 'encode', encoding) ! self.checkequal('hello world', data, 'decode', encoding) ! # zlib is optional, so we make the test optional too... ! try: ! import zlib ! except ImportError: ! pass ! else: ! data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' ! self.checkequal(data, 'hello world', 'encode', 'zlib') ! self.checkequal('hello world', data, 'decode', 'zlib') Index: test_string.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_string.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** test_string.py 19 Feb 2003 02:35:06 -0000 1.23 --- test_string.py 21 Feb 2003 12:53:49 -0000 1.24 *************** *** 1,84 **** ! from test.test_support import verbose, TestSkipped ! from test import string_tests ! import string, sys ! # XXX: kludge... short circuit if strings don't have methods ! try: ! ''.join ! except AttributeError: ! raise TestSkipped ! def test(name, input, output, *args): ! if verbose: ! print 'string.%s%s =? %s... ' % (name, (input,) + args, output), ! try: ! # Prefer string methods over string module functions ! try: ! f = getattr(input, name) ! value = apply(f, args) ! except AttributeError: ! f = getattr(string, name) ! value = apply(f, (input,) + args) ! except: ! value = sys.exc_type ! f = name ! if value == output: ! # if the original is returned make sure that ! # this doesn't happen with subclasses ! if value is input: ! class ssub(str): ! def __repr__(self): ! return 'ssub(%r)' % str.__repr__(self) ! input = ssub(input) ! try: ! f = getattr(input, name) ! value = apply(f, args) ! except AttributeError: ! f = getattr(string, name) ! value = apply(f, (input,) + args) ! if value is input: ! if verbose: ! print 'no' ! print '*',f, `input`, `output`, `value` ! return ! if value != output: ! if verbose: ! print 'no' ! print f, `input`, `output`, `value` ! else: ! if verbose: ! print 'yes' ! string_tests.run_module_tests(test) ! string_tests.run_method_tests(test) ! string_tests.run_contains_tests(test) ! string_tests.run_inplace_tests(str) ! string.whitespace ! string.lowercase ! string.uppercase ! # Float formatting ! for prec in range(100): ! formatstring = '%%.%if' % prec ! value = 0.01 ! for x in range(60): ! value = value * 3.141592655 / 3.0 * 10.0 ! #print 'Overflow check for x=%i and prec=%i:' % \ ! # (x, prec), ! try: ! result = formatstring % value ! except OverflowError: ! # The formatfloat() code in stringobject.c and ! # unicodeobject.c uses a 120 byte buffer and switches from ! # 'f' formatting to 'g' at precision 50, so we expect ! # OverflowErrors for the ranges x < 50 and prec >= 67. ! if x >= 50 or \ ! prec < 67: ! print '*** unexpected OverflowError for x=%i and prec=%i' % (x, prec) ! else: ! #print 'OverflowError' ! pass ! else: ! #print result ! pass --- 1,104 ---- ! import unittest, string ! from test import test_support, string_tests ! from UserList import UserList ! class StringTest( ! string_tests.CommonTest, ! string_tests.MixinStrStringUserStringTest ! ): ! type2test = str ! def checkequal(self, result, object, methodname, *args): ! realresult = getattr(string, methodname)(object, *args) ! self.assertEqual( ! result, ! realresult ! ) ! def checkraises(self, exc, object, methodname, *args): ! self.assertRaises( ! exc, ! getattr(string, methodname), ! object, ! *args ! ) ! def checkcall(self, object, methodname, *args): ! getattr(string, methodname)(object, *args) ! ! def test_join(self): ! # These are the same checks as in string_test.ObjectTest.test_join ! # but the argument order ist different ! self.checkequal('a b c d', ['a', 'b', 'c', 'd'], 'join', ' ') ! self.checkequal('abcd', ('a', 'b', 'c', 'd'), 'join', '') ! self.checkequal('w x y z', string_tests.Sequence(), 'join', ' ') ! self.checkequal('abc', ('abc',), 'join', 'a') ! self.checkequal('z', UserList(['z']), 'join', 'a') ! if test_support.have_unicode: ! self.checkequal(unicode('a.b.c'), ['a', 'b', 'c'], 'join', unicode('.')) ! self.checkequal(unicode('a.b.c'), [unicode('a'), 'b', 'c'], 'join', '.') ! self.checkequal(unicode('a.b.c'), ['a', unicode('b'), 'c'], 'join', '.') ! self.checkequal(unicode('a.b.c'), ['a', 'b', unicode('c')], 'join', '.') ! self.checkraises(TypeError, ['a', unicode('b'), 3], 'join', '.') ! for i in [5, 25, 125]: ! self.checkequal( ! ((('a' * i) + '-') * i)[:-1], ! ['a' * i] * i, 'join', '-') ! self.checkequal( ! ((('a' * i) + '-') * i)[:-1], ! ('a' * i,) * i, 'join', '-') ! ! self.checkraises(TypeError, string_tests.BadSeq1(), 'join', ' ') ! self.checkequal('a b c', string_tests.BadSeq2(), 'join', ' ') ! ! class ModuleTest(unittest.TestCase): ! ! def test_attrs(self): ! string.whitespace ! string.lowercase ! string.uppercase ! string.letters ! string.digits ! string.hexdigits ! string.octdigits ! string.punctuation ! string.printable ! ! def test_atoi(self): ! self.assertEqual(string.atoi(" 1 "), 1) ! self.assertRaises(ValueError, string.atoi, " 1x") ! self.assertRaises(ValueError, string.atoi, " x1 ") ! ! def test_atol(self): ! self.assertEqual(string.atol(" 1 "), 1L) ! self.assertRaises(ValueError, string.atol, " 1x ") ! self.assertRaises(ValueError, string.atol, " x1 ") ! ! def test_atof(self): ! self.assertAlmostEqual(string.atof(" 1 "), 1.0) ! self.assertRaises(ValueError, string.atof, " 1x ") ! self.assertRaises(ValueError, string.atof, " x1 ") ! ! def test_maketrans(self): ! transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' ! ! self.assertEqual(string.maketrans('abc', 'xyz'), transtable) ! self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzq') ! ! def test_capwords(self): ! self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi') ! self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi') ! self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi') ! self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi') ! self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi') ! self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi') ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(StringTest)) ! suite.addTest(unittest.makeSuite(ModuleTest)) ! test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() Index: test_unicode.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_unicode.py,v retrieving revision 1.78 retrieving revision 1.79 diff -C2 -d -r1.78 -r1.79 *** test_unicode.py 10 Feb 2003 17:51:03 -0000 1.78 --- test_unicode.py 21 Feb 2003 12:53:49 -0000 1.79 *************** *** 7,14 **** """#" ! import unittest, test.test_support ! import sys, string, codecs ! class UnicodeTest(unittest.TestCase): def test_repr(self): --- 7,36 ---- """#" ! import unittest, sys, string, codecs, new ! from test import test_support, string_tests ! class UnicodeTest( ! string_tests.CommonTest, ! string_tests.MixinStrUnicodeUserStringTest ! ): ! type2test = unicode ! ! def checkequalnofix(self, result, object, methodname, *args): ! method = getattr(object, methodname) ! realresult = method(*args) ! self.assertEqual(realresult, result) ! self.assert_(type(realresult) is type(result)) ! ! # if the original is returned make sure that ! # this doesn't happen with subclasses ! if realresult is object: ! class usub(unicode): ! def __repr__(self): ! return 'usub(%r)' % unicode.__repr__(self) ! object = usub(object) ! method = getattr(object, methodname) ! realresult = method(*args) ! self.assertEqual(realresult, result) ! self.assert_(object is not realresult) def test_repr(self): *************** *** 46,106 **** self.assertEqual(testrepr, latin1repr) - def checkmethod(self, method, input, output, *args): - f = getattr(input, method) - value = f(*args) - self.assertEqual(output, value) - self.assert_(type(output) is type(value)) - - # if the original is returned make sure that - # this doesn't happen with subclasses - if value is input: - class usub(unicode): - def __repr__(self): - return 'usub(%r)' % unicode.__repr__(self) - input = usub(input) - f = getattr(input, method) - value = f(*args) - self.assertEqual(output, value) - self.assert_(input is not value) - - def test_capitalize(self): - self.checkmethod('capitalize', u' hello ', u' hello ') - self.checkmethod('capitalize', u'Hello ', u'Hello ') - self.checkmethod('capitalize', u'hello ', u'Hello ') - self.checkmethod('capitalize', u'aaaa', u'Aaaa') - self.checkmethod('capitalize', u'AaAa', u'Aaaa') - - self.assertRaises(TypeError, u'hello'.capitalize, 42) - def test_count(self): ! self.checkmethod('count', u'aaa', 3, u'a') ! self.checkmethod('count', u'aaa', 0, u'b') ! self.checkmethod('count', 'aaa', 3, u'a') ! self.checkmethod('count', 'aaa', 0, u'b') ! self.checkmethod('count', u'aaa', 3, 'a') ! self.checkmethod('count', u'aaa', 0, 'b') ! self.checkmethod('count', u'aaa', 0, 'b') ! self.checkmethod('count', u'aaa', 1, 'a', -1) ! self.checkmethod('count', u'aaa', 3, 'a', -10) ! self.checkmethod('count', u'aaa', 2, 'a', 0, -1) ! self.checkmethod('count', u'aaa', 0, 'a', 0, -10) ! ! self.assertRaises(TypeError, u'hello'.count) ! self.assertRaises(TypeError, u'hello'.count, 42) ! ! def test_title(self): ! self.checkmethod('title', u' hello ', u' Hello ') ! self.checkmethod('title', u'Hello ', u'Hello ') ! self.checkmethod('title', u'hello ', u'Hello ') ! self.checkmethod('title', u"fOrMaT thIs aS titLe String", u'Format This As Title String') ! self.checkmethod('title', u"fOrMaT,thIs-aS*titLe;String", u'Format,This-As*Title;String') ! self.checkmethod('title', u"getInt", u'Getint') ! ! self.assertRaises(TypeError, u'hello'.title, 42) def test_find(self): ! self.checkmethod('find', u'abcdefghiabc', 0, u'abc') ! self.checkmethod('find', u'abcdefghiabc', 9, u'abc', 1) ! self.checkmethod('find', u'abcdefghiabc', -1, u'def', 4) self.assertRaises(TypeError, u'hello'.find) --- 68,88 ---- self.assertEqual(testrepr, latin1repr) def test_count(self): ! string_tests.CommonTest.test_count(self) ! # check mixed argument types ! self.checkequalnofix(3, 'aaa', 'count', u'a') ! self.checkequalnofix(0, 'aaa', 'count', u'b') ! self.checkequalnofix(3, u'aaa', 'count', 'a') ! self.checkequalnofix(0, u'aaa', 'count', 'b') ! self.checkequalnofix(0, u'aaa', 'count', 'b') ! self.checkequalnofix(1, u'aaa', 'count', 'a', -1) ! self.checkequalnofix(3, u'aaa', 'count', 'a', -10) ! self.checkequalnofix(2, u'aaa', 'count', 'a', 0, -1) ! self.checkequalnofix(0, u'aaa', 'count', 'a', 0, -10) def test_find(self): ! self.checkequalnofix(0, u'abcdefghiabc', 'find', u'abc') ! self.checkequalnofix(9, u'abcdefghiabc', 'find', u'abc', 1) ! self.checkequalnofix(-1, u'abcdefghiabc', 'find', u'def', 4) self.assertRaises(TypeError, u'hello'.find) *************** *** 108,364 **** def test_rfind(self): ! self.checkmethod('rfind', u'abcdefghiabc', 9, u'abc') ! self.checkmethod('rfind', 'abcdefghiabc', 9, u'abc') ! self.checkmethod('rfind', 'abcdefghiabc', 12, u'') ! self.checkmethod('rfind', u'abcdefghiabc', 12, '') ! self.checkmethod('rfind', u'abcdefghiabc', 12, u'') ! ! self.assertRaises(TypeError, u'hello'.rfind) ! self.assertRaises(TypeError, u'hello'.rfind, 42) def test_index(self): ! self.checkmethod('index', u'abcdefghiabc', 0, u'') ! self.checkmethod('index', u'abcdefghiabc', 3, u'def') ! self.checkmethod('index', u'abcdefghiabc', 0, u'abc') ! self.checkmethod('index', u'abcdefghiabc', 9, u'abc', 1) ! ! self.assertRaises(ValueError, u'abcdefghiabc'.index, u'hib') ! self.assertRaises(ValueError, u'abcdefghiab'.index, u'abc', 1) ! self.assertRaises(ValueError, u'abcdefghi'.index, u'ghi', 8) ! self.assertRaises(ValueError, u'abcdefghi'.index, u'ghi', -1) ! ! self.assertRaises(TypeError, u'hello'.index) ! self.assertRaises(TypeError, u'hello'.index, 42) def test_rindex(self): ! self.checkmethod('rindex', u'abcdefghiabc', 12, u'') ! self.checkmethod('rindex', u'abcdefghiabc', 3, u'def') ! self.checkmethod('rindex', u'abcdefghiabc', 9, u'abc') ! self.checkmethod('rindex', u'abcdefghiabc', 0, u'abc', 0, -1) ! ! self.assertRaises(ValueError, u'abcdefghiabc'.rindex, u'hib') ! self.assertRaises(ValueError, u'defghiabc'.rindex, u'def', 1) ! self.assertRaises(ValueError, u'defghiabc'.rindex, u'abc', 0, -1) ! self.assertRaises(ValueError, u'abcdefghi'.rindex, u'ghi', 0, 8) ! self.assertRaises(ValueError, u'abcdefghi'.rindex, u'ghi', 0, -1) ! ! self.assertRaises(TypeError, u'hello'.rindex) ! self.assertRaises(TypeError, u'hello'.rindex, 42) ! ! def test_lower(self): ! self.checkmethod('lower', u'HeLLo', u'hello') ! self.checkmethod('lower', u'hello', u'hello') ! ! self.assertRaises(TypeError, u"hello".lower, 42) ! ! def test_upper(self): ! self.checkmethod('upper', u'HeLLo', u'HELLO') ! self.checkmethod('upper', u'HELLO', u'HELLO') ! self.assertRaises(TypeError, u'hello'.upper, 42) def test_translate(self): ! if 0: ! transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' ! ! self.checkmethod('maketrans', u'abc', transtable, u'xyz') ! self.checkmethod('maketrans', u'abc', ValueError, u'xyzq') ! ! self.checkmethod('translate', u'xyzabcdef', u'xyzxyz', transtable, u'def') ! ! table = string.maketrans('a', u'A') ! self.checkmethod('translate', u'abc', u'Abc', table) ! self.checkmethod('translate', u'xyz', u'xyz', table) ! ! self.checkmethod('translate', u"abababc", u'bbbc', {ord('a'):None}) ! self.checkmethod('translate', u"abababc", u'iiic', {ord('a'):None, ord('b'):ord('i')}) ! self.checkmethod('translate', u"abababc", u'iiix', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'}) ! self.checkmethod('translate', u"abababc", u'c', {ord('a'):None, ord('b'):u''}) ! self.checkmethod('translate', u"abababc", u'c', {ord('a'):None, ord('b'):u''}) self.assertRaises(TypeError, u'hello'.translate) def test_split(self): ! self.checkmethod( ! 'split', ! u'this is the split function', ! [u'this', u'is', u'the', u'split', u'function'] ! ) ! self.checkmethod('split', u'a|b|c|d', [u'a', u'b', u'c', u'd'], u'|') ! self.checkmethod('split', u'a|b|c|d', [u'a', u'b', u'c|d'], u'|', 2) ! self.checkmethod('split', u'a b c d', [u'a', u'b c d'], None, 1) ! self.checkmethod('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) ! self.checkmethod('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 3) ! self.checkmethod('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 4) ! self.checkmethod('split', u'a b c d', [u'a b c d'], None, 0) ! self.checkmethod('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) ! self.checkmethod('split', u'a b c d ', [u'a', u'b', u'c', u'd']) ! self.checkmethod('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') ! self.checkmethod('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], '//') ! self.checkmethod('split', 'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') ! self.checkmethod('split', u'endcase test', [u'endcase ', u''], u'test') ! self.checkmethod('split', u'endcase test', [u'endcase ', u''], 'test') ! self.checkmethod('split', 'endcase test', [u'endcase ', u''], u'test') ! self.assertRaises(TypeError, u"hello".split, 42, 42, 42) def test_join(self): ! # join now works with any sequence type ! class Sequence: ! def __init__(self, seq): self.seq = seq ! def __len__(self): return len(self.seq) ! def __getitem__(self, i): return self.seq[i] ! ! self.checkmethod('join', u' ', u'a b c d', [u'a', u'b', u'c', u'd']) ! self.checkmethod('join', u' ', u'a b c d', ['a', 'b', u'c', u'd']) ! self.checkmethod('join', u'', u'abcd', (u'a', u'b', u'c', u'd')) ! self.checkmethod('join', u' ', u'w x y z', Sequence('wxyz')) ! self.assertRaises(TypeError, u' '.join, 7) ! self.assertRaises(TypeError, u' '.join, Sequence([7, u'hello', 123L])) ! self.checkmethod('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd']) ! self.checkmethod('join', ' ', u'a b c d', ['a', 'b', u'c', u'd']) ! self.checkmethod('join', '', u'abcd', (u'a', u'b', u'c', u'd')) ! self.checkmethod('join', ' ', u'w x y z', Sequence(u'wxyz')) ! self.assertRaises(TypeError, ' '.join, TypeError) ! ! result = u'' ! for i in range(10): ! if i > 0: ! result = result + u':' ! result = result + u'x'*10 ! ! self.checkmethod('join', u':', result, [u'x' * 10] * 10) ! self.checkmethod('join', u':', result, (u'x' * 10,) * 10) ! self.assertRaises(TypeError, u"hello".join) def test_strip(self): ! self.checkmethod('strip', u' hello ', u'hello') ! self.checkmethod('lstrip', u' hello ', u'hello ') ! self.checkmethod('rstrip', u' hello ', u' hello') ! self.checkmethod('strip', u'hello', u'hello') ! ! # strip/lstrip/rstrip with None arg ! self.checkmethod('strip', u' hello ', u'hello', None) ! self.checkmethod('lstrip', u' hello ', u'hello ', None) ! self.checkmethod('rstrip', u' hello ', u' hello', None) ! self.checkmethod('strip', u'hello', u'hello', None) ! ! # strip/lstrip/rstrip with unicode arg ! self.checkmethod('strip', u'xyzzyhelloxyzzy', u'hello', u'xyz') ! self.checkmethod('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', u'xyz') ! self.checkmethod('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', u'xyz') ! self.checkmethod('strip', u'hello', u'hello', u'xyz') ! ! # strip/lstrip/rstrip with str arg ! self.checkmethod('strip', u'xyzzyhelloxyzzy', u'hello', 'xyz') ! self.checkmethod('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', 'xyz') ! self.checkmethod('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', 'xyz') ! self.checkmethod('strip', u'hello', u'hello', 'xyz') ! ! self.assertRaises(TypeError, u"hello".strip, 42, 42) self.assertRaises(UnicodeError, u"hello".strip, "\xff") - def test_swapcase(self): - self.checkmethod('swapcase', u'HeLLo cOmpUteRs', u'hEllO CoMPuTErS') - - self.assertRaises(TypeError, u"hello".swapcase, 42) - def test_replace(self): ! self.checkmethod('replace', u'one!two!three!', u'one@two!three!', u'!', u'@', 1) ! self.checkmethod('replace', u'one!two!three!', u'onetwothree', '!', '') ! self.checkmethod('replace', u'one!two!three!', u'one@two@three!', u'!', u'@', 2) ! self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 3) ! self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 4) ! self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'!', u'@', 0) ! self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@') ! self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'x', u'@') ! self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'x', u'@', 2) ! self.checkmethod('replace', u'abc', u'-a-b-c-', u'', u'-') ! self.checkmethod('replace', u'abc', u'-a-b-c', u'', u'-', 3) ! self.checkmethod('replace', u'abc', u'abc', u'', u'-', 0) ! self.checkmethod('replace', u'abc', u'abc', u'ab', u'--', 0) ! self.checkmethod('replace', u'abc', u'abc', u'xy', u'--') ! self.checkmethod('replace', u'', u'', u'', u'') # method call forwarded from str implementation because of unicode argument ! self.checkmethod('replace', 'one!two!three!', u'one@two!three!', u'!', u'@', 1) ! self.assertRaises(TypeError, 'replace'.replace, 42) self.assertRaises(TypeError, 'replace'.replace, u"r", 42) - self.assertRaises(TypeError, u"hello".replace) - self.assertRaises(TypeError, u"hello".replace, 42, u"h") - self.assertRaises(TypeError, u"hello".replace, u"h", 42) - - def test_startswith(self): - self.checkmethod('startswith', u'hello', True, u'he') - self.checkmethod('startswith', u'hello', True, u'hello') - self.checkmethod('startswith', u'hello', False, u'hello world') - self.checkmethod('startswith', u'hello', True, u'') - self.checkmethod('startswith', u'hello', False, u'ello') - self.checkmethod('startswith', u'hello', True, u'ello', 1) - self.checkmethod('startswith', u'hello', True, u'o', 4) - self.checkmethod('startswith', u'hello', False, u'o', 5) - self.checkmethod('startswith', u'hello', True, u'', 5) - self.checkmethod('startswith', u'hello', False, u'lo', 6) - self.checkmethod('startswith', u'helloworld', True, u'lowo', 3) - self.checkmethod('startswith', u'helloworld', True, u'lowo', 3, 7) - self.checkmethod('startswith', u'helloworld', False, u'lowo', 3, 6) - - self.assertRaises(TypeError, u"hello".startswith) - self.assertRaises(TypeError, u"hello".startswith, 42) - - def test_endswith(self): - self.checkmethod('endswith', u'hello', True, u'lo') - self.checkmethod('endswith', u'hello', False, u'he') - self.checkmethod('endswith', u'hello', True, u'') - self.checkmethod('endswith', u'hello', False, u'hello world') - self.checkmethod('endswith', u'helloworld', False, u'worl') - self.checkmethod('endswith', u'helloworld', True, u'worl', 3, 9) - self.checkmethod('endswith', u'helloworld', True, u'world', 3, 12) - self.checkmethod('endswith', u'helloworld', True, u'lowo', 1, 7) - self.checkmethod('endswith', u'helloworld', True, u'lowo', 2, 7) - self.checkmethod('endswith', u'helloworld', True, u'lowo', 3, 7) - self.checkmethod('endswith', u'helloworld', False, u'lowo', 4, 7) - self.checkmethod('endswith', u'helloworld', False, u'lowo', 3, 8) - self.checkmethod('endswith', u'ab', False, u'ab', 0, 1) - self.checkmethod('endswith', u'ab', False, u'ab', 0, 0) - self.checkmethod('endswith', 'helloworld', True, u'd') - self.checkmethod('endswith', 'helloworld', False, u'l') - - self.assertRaises(TypeError, u"hello".endswith) - self.assertRaises(TypeError, u"hello".endswith, 42) - - def test_expandtabs(self): - self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi') - self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 8) - self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 4) - self.checkmethod('expandtabs', u'abc\r\nab\tdef\ng\thi', u'abc\r\nab def\ng hi', 4) - self.checkmethod('expandtabs', u'abc\r\nab\r\ndef\ng\r\nhi', u'abc\r\nab\r\ndef\ng\r\nhi', 4) - - self.assertRaises(TypeError, u"hello".expandtabs, 42, 42) - - def test_capwords(self): - if 0: - self.checkmethod('capwords', u'abc def ghi', u'Abc Def Ghi') - self.checkmethod('capwords', u'abc\tdef\nghi', u'Abc Def Ghi') - self.checkmethod('capwords', u'abc\t def \nghi', u'Abc Def Ghi') - - def test_zfill(self): - self.checkmethod('zfill', u'123', u'123', 2) - self.checkmethod('zfill', u'123', u'123', 3) - self.checkmethod('zfill', u'123', u'0123', 4) - self.checkmethod('zfill', u'+123', u'+123', 3) - self.checkmethod('zfill', u'+123', u'+123', 4) - self.checkmethod('zfill', u'+123', u'+0123', 5) - self.checkmethod('zfill', u'-123', u'-123', 3) - self.checkmethod('zfill', u'-123', u'-123', 4) - self.checkmethod('zfill', u'-123', u'-0123', 5) - self.checkmethod('zfill', u'', u'000', 3) - self.checkmethod('zfill', u'34', u'34', 1) - self.checkmethod('zfill', u'34', u'00034', 5) - - self.assertRaises(TypeError, u"123".zfill) - def test_comparison(self): # Comparisons: --- 90,168 ---- def test_rfind(self): ! string_tests.CommonTest.test_rfind(self) ! # check mixed argument types ! self.checkequalnofix(9, 'abcdefghiabc', 'rfind', u'abc') ! self.checkequalnofix(12, 'abcdefghiabc', 'rfind', u'') ! self.checkequalnofix(12, u'abcdefghiabc', 'rfind', '') def test_index(self): ! string_tests.CommonTest.test_index(self) ! # check mixed argument types ! for (t1, t2) in ((str, unicode), (unicode, str)): ! self.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2('')) ! self.checkequalnofix(3, t1('abcdefghiabc'), 'index', t2('def')) ! self.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2('abc')) ! self.checkequalnofix(9, t1('abcdefghiabc'), 'index', t2('abc'), 1) ! self.assertRaises(ValueError, t1('abcdefghiabc').index, t2('hib')) ! self.assertRaises(ValueError, t1('abcdefghiab').index, t2('abc'), 1) ! self.assertRaises(ValueError, t1('abcdefghi').index, t2('ghi'), 8) ! self.assertRaises(ValueError, t1('abcdefghi').index, t2('ghi'), -1) def test_rindex(self): ! string_tests.CommonTest.test_rindex(self) ! # check mixed argument types ! for (t1, t2) in ((str, unicode), (unicode, str)): ! self.checkequalnofix(12, t1('abcdefghiabc'), 'rindex', t2('')) ! self.checkequalnofix(3, t1('abcdefghiabc'), 'rindex', t2('def')) ! self.checkequalnofix(9, t1('abcdefghiabc'), 'rindex', t2('abc')) ! self.checkequalnofix(0, t1('abcdefghiabc'), 'rindex', t2('abc'), 0, -1) ! self.assertRaises(ValueError, t1('abcdefghiabc').rindex, t2('hib')) ! self.assertRaises(ValueError, t1('defghiabc').rindex, t2('def'), 1) ! self.assertRaises(ValueError, t1('defghiabc').rindex, t2('abc'), 0, -1) ! self.assertRaises(ValueError, t1('abcdefghi').rindex, t2('ghi'), 0, 8) ! self.assertRaises(ValueError, t1('abcdefghi').rindex, t2('ghi'), 0, -1) def test_translate(self): ! self.checkequalnofix(u'bbbc', u'abababc', 'translate', {ord('a'):None}) ! self.checkequalnofix(u'iiic', u'abababc', 'translate', {ord('a'):None, ord('b'):ord('i')}) ! self.checkequalnofix(u'iiix', u'abababc', 'translate', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'}) ! self.checkequalnofix(u'c', u'abababc', 'translate', {ord('a'):None, ord('b'):u''}) ! self.checkequalnofix(u'c', u'abababc', 'translate', {ord('a'):None, ord('b'):u''}) self.assertRaises(TypeError, u'hello'.translate) + self.assertRaises(TypeError, u'abababc'.translate, {ord('a'):''}) def test_split(self): ! string_tests.CommonTest.test_split(self) ! # Mixed arguments ! self.checkequalnofix([u'a', u'b', u'c', u'd'], u'a//b//c//d', 'split', '//') ! self.checkequalnofix([u'a', u'b', u'c', u'd'], 'a//b//c//d', 'split', u'//') ! self.checkequalnofix([u'endcase ', u''], u'endcase test', 'split', 'test') def test_join(self): ! string_tests.MixinStrUnicodeUserStringTest.test_join(self) ! # mixed arguments ! self.checkequalnofix(u'a b c d', u' ', 'join', ['a', 'b', u'c', u'd']) ! self.checkequalnofix(u'abcd', u'', 'join', (u'a', u'b', u'c', u'd')) ! self.checkequalnofix(u'w x y z', u' ', 'join', string_tests.Sequence('wxyz')) ! self.checkequalnofix(u'a b c d', ' ', 'join', [u'a', u'b', u'c', u'd']) ! self.checkequalnofix(u'a b c d', ' ', 'join', ['a', 'b', u'c', u'd']) ! self.checkequalnofix(u'abcd', '', 'join', (u'a', u'b', u'c', u'd')) ! self.checkequalnofix(u'w x y z', ' ', 'join', string_tests.Sequence(u'wxyz')) def test_strip(self): ! string_tests.CommonTest.test_strip(self) self.assertRaises(UnicodeError, u"hello".strip, "\xff") def test_replace(self): ! string_tests.CommonTest.test_replace(self) # method call forwarded from str implementation because of unicode argument ! self.checkequalnofix(u'one@two!three!', 'one!two!three!', 'replace', u'!', u'@', 1) self.assertRaises(TypeError, 'replace'.replace, u"r", 42) def test_comparison(self): # Comparisons: *************** *** 426,575 **** self.assert_(u'\ud800\udc02' < u'\ud84d\udc56') - def test_ljust(self): - self.checkmethod('ljust', u'abc', u'abc ', 10) - self.checkmethod('ljust', u'abc', u'abc ', 6) - self.checkmethod('ljust', u'abc', u'abc', 2) - - self.assertRaises(TypeError, u"abc".ljust) - - def test_rjust(self): - self.checkmethod('rjust', u'abc', u' abc', 10) - self.checkmethod('rjust', u'abc', u' abc', 6) - self.checkmethod('rjust', u'abc', u'abc', 2) - - self.assertRaises(TypeError, u"abc".rjust) - - def test_center(self): - self.checkmethod('center', u'abc', u' abc ', 10) - self.checkmethod('center', u'abc', u' abc ', 6) - self.checkmethod('center', u'abc', u'abc', 2) - - self.assertRaises(TypeError, u"abc".center) - def test_islower(self): ! self.checkmethod('islower', u'', False) ! self.checkmethod('islower', u'a', True) ! self.checkmethod('islower', u'A', False) ! self.checkmethod('islower', u'\n', False) ! self.checkmethod('islower', u'\u1FFc', False) ! self.checkmethod('islower', u'abc', True) ! self.checkmethod('islower', u'aBc', False) ! self.checkmethod('islower', u'abc\n', True) ! ! self.assertRaises(TypeError, u"abc".islower, 42) def test_isupper(self): ! self.checkmethod('isupper', u'', False) ! self.checkmethod('isupper', u'a', False) ! self.checkmethod('isupper', u'A', True) ! self.checkmethod('isupper', u'\n', False) ! if sys.platform[:4] != 'java': ! self.checkmethod('isupper', u'\u1FFc', False) ! self.checkmethod('isupper', u'ABC', True) ! self.checkmethod('isupper', u'AbC', False) ! self.checkmethod('isupper', u'ABC\n', True) ! ! self.assertRaises(TypeError, u"abc".isupper, 42) def test_istitle(self): ! self.checkmethod('istitle', u'', False) ! self.checkmethod('istitle', u'a', False) ! self.checkmethod('istitle', u'A', True) ! self.checkmethod('istitle', u'\n', False) ! self.checkmethod('istitle', u'\u1FFc', True) ! self.checkmethod('istitle', u'A Titlecased Line', True) ! self.checkmethod('istitle', u'A\nTitlecased Line', True) ! self.checkmethod('istitle', u'A Titlecased, Line', True) ! self.checkmethod('istitle', u'Greek \u1FFcitlecases ...', True) ! self.checkmethod('istitle', u'Not a capitalized String', False) ! self.checkmethod('istitle', u'Not\ta Titlecase String', False) ! self.checkmethod('istitle', u'Not--a Titlecase String', False) ! self.checkmethod('istitle', u'NOT', False) ! ! self.assertRaises(TypeError, u"abc".istitle, 42) def test_isspace(self): ! self.checkmethod('isspace', u'', False) ! self.checkmethod('isspace', u'a', False) ! self.checkmethod('isspace', u' ', True) ! self.checkmethod('isspace', u'\t', True) ! self.checkmethod('isspace', u'\r', True) ! self.checkmethod('isspace', u'\n', True) ! self.checkmethod('isspace', u' \t\r\n', True) ! self.checkmethod('isspace', u' \t\r\na', False) ! ! self.assertRaises(TypeError, u"abc".isspace, 42) def test_isalpha(self): ! self.checkmethod('isalpha', u'', False) ! self.checkmethod('isalpha', u'a', True) ! self.checkmethod('isalpha', u'A', True) ! self.checkmethod('isalpha', u'\n', False) ! self.checkmethod('isalpha', u'\u1FFc', True) ! self.checkmethod('isalpha', u'abc', True) ! self.checkmethod('isalpha', u'aBc123', False) ! self.checkmethod('isalpha', u'abc\n', False) ! ! self.assertRaises(TypeError, u"abc".isalpha, 42) ! ! def test_isalnum(self): ! self.checkmethod('isalnum', u'', False) ! self.checkmethod('isalnum', u'a', True) ! self.checkmethod('isalnum', u'A', True) ! self.checkmethod('isalnum', u'\n', False) ! self.checkmethod('isalnum', u'123abc456', True) ! self.checkmethod('isalnum', u'a1b3c', True) ! self.checkmethod('isalnum', u'aBc000 ', False) ! self.checkmethod('isalnum', u'abc\n', False) ! ! self.assertRaises(TypeError, u"abc".isalnum, 42) def test_isdecimal(self): ! self.checkmethod('isdecimal', u'', False) ! self.checkmethod('isdecimal', u'a', False) ! self.checkmethod('isdecimal', u'0', True) ! self.checkmethod('isdecimal', u'\u2460', False) # CIRCLED DIGIT ONE ! self.checkmethod('isdecimal', u'\xbc', False) # VULGAR FRACTION ONE QUARTER ! self.checkmethod('isdecimal', u'\u0660', True) # ARABIC-INDIC DIGIT ZERO ! self.checkmethod('isdecimal', u'0123456789', True) ! self.checkmethod('isdecimal', u'0123456789a', False) ! self.assertRaises(TypeError, u"abc".isdecimal, 42) def test_isdigit(self): ! self.checkmethod('isdigit', u'', False) ! self.checkmethod('isdigit', u'a', False) ! self.checkmethod('isdigit', u'0', True) ! self.checkmethod('isdigit', u'\u2460', True) ! self.checkmethod('isdigit', u'\xbc', False) ! self.checkmethod('isdigit', u'\u0660', True) ! self.checkmethod('isdigit', u'0123456789', True) ! self.checkmethod('isdigit', u'0123456789a', False) ! ! self.assertRaises(TypeError, u"abc".isdigit, 42) def test_isnumeric(self): ! self.checkmethod('isnumeric', u'', False) ! self.checkmethod('isnumeric', u'a', False) ! self.checkmethod('isnumeric', u'0', True) ! self.checkmethod('isnumeric', u'\u2460', True) ! self.checkmethod('isnumeric', u'\xbc', True) ! self.checkmethod('isnumeric', u'\u0660', True) ! self.checkmethod('isnumeric', u'0123456789', True) ! self.checkmethod('isnumeric', u'0123456789a', False) self.assertRaises(TypeError, u"abc".isnumeric, 42) - def test_splitlines(self): - self.checkmethod('splitlines', u"abc\ndef\n\rghi", [u'abc', u'def', u'', u'ghi']) - self.checkmethod('splitlines', u"abc\ndef\n\r\nghi", [u'abc', u'def', u'', u'ghi']) - self.checkmethod('splitlines', u"abc\ndef\r\nghi", [u'abc', u'def', u'ghi']) - self.checkmethod('splitlines', u"abc\ndef\r\nghi\n", [u'abc', u'def', u'ghi']) - self.checkmethod('splitlines', u"abc\ndef\r\nghi\n\r", [u'abc', u'def', u'ghi', u'']) - self.checkmethod('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'', u'abc', u'def', u'ghi', u'']) - self.checkmethod('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'\n', u'abc\n', u'def\r\n', u'ghi\n', u'\r'], True) - - self.assertRaises(TypeError, u"abc".splitlines, 42, 42) - def test_contains(self): # Testing Unicode contains method --- 230,287 ---- self.assert_(u'\ud800\udc02' < u'\ud84d\udc56') def test_islower(self): ! string_tests.MixinStrUnicodeUserStringTest.test_islower(self) ! self.checkequalnofix(False, u'\u1FFc', 'islower') def test_isupper(self): ! string_tests.MixinStrUnicodeUserStringTest.test_isupper(self) ! if not sys.platform.startswith('java'): ! self.checkequalnofix(False, u'\u1FFc', 'isupper') def test_istitle(self): ! string_tests.MixinStrUnicodeUserStringTest.test_title(self) ! self.checkequalnofix(True, u'\u1FFc', 'istitle') ! self.checkequalnofix(True, u'Greek \u1FFcitlecases ...', 'istitle') def test_isspace(self): ! string_tests.MixinStrUnicodeUserStringTest.test_isspace(self) ! self.checkequalnofix(True, u'\u2000', 'isspace') ! self.checkequalnofix(True, u'\u200a', 'isspace') ! self.checkequalnofix(False, u'\u2014', 'isspace') def test_isalpha(self): ! string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self) ! self.checkequalnofix(True, u'\u1FFc', 'isalpha') def test_isdecimal(self): ! self.checkequalnofix(False, u'', 'isdecimal') ! self.checkequalnofix(False, u'a', 'isdecimal') ! self.checkequalnofix(True, u'0', 'isdecimal') ! self.checkequalnofix(False, u'\u2460', 'isdecimal') # CIRCLED DIGIT ONE ! self.checkequalnofix(False, u'\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER ! self.checkequalnofix(True, u'\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO ! self.checkequalnofix(True, u'0123456789', 'isdecimal') ! self.checkequalnofix(False, u'0123456789a', 'isdecimal') ! self.checkraises(TypeError, 'abc', 'isdecimal', 42) def test_isdigit(self): ! string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self) ! self.checkequalnofix(True, u'\u2460', 'isdigit') ! self.checkequalnofix(False, u'\xbc', 'isdigit') ! self.checkequalnofix(True, u'\u0660', 'isdigit') def test_isnumeric(self): ! self.checkequalnofix(False, u'', 'isnumeric') ! self.checkequalnofix(False, u'a', 'isnumeric') ! self.checkequalnofix(True, u'0', 'isnumeric') ! self.checkequalnofix(True, u'\u2460', 'isnumeric') ! self.checkequalnofix(True, u'\xbc', 'isnumeric') ! self.checkequalnofix(True, u'\u0660', 'isnumeric') ! self.checkequalnofix(True, u'0123456789', 'isnumeric') ! self.checkequalnofix(False, u'0123456789a', 'isnumeric') self.assertRaises(TypeError, u"abc".isnumeric, 42) def test_contains(self): # Testing Unicode contains method *************** *** 635,638 **** --- 347,351 ---- def test_formatting(self): + string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) # Testing Unicode formatting strings... self.assertEqual(u"%s, %s" % (u"abc", "abc"), u'abc, abc') *************** *** 642,672 **** self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57), u'abc, abc, -1, -2.000000, 3.57') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57), u'abc, abc, -1, -2.000000, 1003.57') - self.assertEqual(u"%c" % (u"a",), u'a') - self.assertEqual(u"%c" % ("a",), u'a') - self.assertEqual(u"%c" % (34,), u'"') - self.assertEqual(u"%c" % (36,), u'$') - self.assertEqual(u"%d".__mod__(10), u'10') if not sys.platform.startswith('java'): self.assertEqual(u"%r, %r" % (u"abc", "abc"), u"u'abc', 'abc'") self.assertEqual(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"}, u'abc, def') ! self.assertEqual(u"%(x)s, %(ä)s" % {'x':u"abc", u'ä':"def"}, u'abc, def') ! ! for ordinal in (-100, 0x200000): ! self.assertRaises(ValueError, u"%c".__mod__, ordinal) ! ! # float formatting ! for prec in xrange(100): ! format = u'%%.%if' % prec ! value = 0.01 ! for x in xrange(60): ! value = value * 3.141592655 / 3.0 * 10.0 ! # The formatfloat() code in stringobject.c and ! # unicodeobject.c uses a 120 byte buffer and switches from ! # 'f' formatting to 'g' at precision 50, so we expect ! # OverflowErrors for the ranges x < 50 and prec >= 67. ! if x < 50 and prec >= 67: ! self.assertRaises(OverflowError, format.__mod__, value) ! else: ! format % value # formatting jobs delegated from the string implementation: --- 355,362 ---- self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57), u'abc, abc, -1, -2.000000, 3.57') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57), u'abc, abc, -1, -2.000000, 1003.57') if not sys.platform.startswith('java'): self.assertEqual(u"%r, %r" % (u"abc", "abc"), u"u'abc', 'abc'") self.assertEqual(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"}, u'abc, def') ! self.assertEqual(u"%(x)s, %(\xfc)s" % {'x':u"abc", u'\xfc':"def"}, u'abc, def') # formatting jobs delegated from the string implementation: *************** *** 685,710 **** self.assertEqual('%*.*s' % (5,3,u'abc',), u' abc') self.assertEqual('%i %*.*s' % (10, 5,3,u'abc',), u'10 abc') ! self.assertEqual('%i%s %*.*s' % (10, 3, 5,3,u'abc',), u'103 abc') ! ! self.assertEqual(u'%3ld' % 42, u' 42') ! self.assertEqual(u'%07.2f' % 42, u'0042.00') - self.assertRaises(TypeError, u"abc".__mod__) - self.assertRaises(TypeError, u"%(foo)s".__mod__, 42) - self.assertRaises(TypeError, u"%s%s".__mod__, (42,)) - self.assertRaises(TypeError, u"%c".__mod__, (None,)) self.assertRaises(ValueError, u"%c".__mod__, (sys.maxunicode+1,)) - self.assertRaises(ValueError, u"%(foo".__mod__, {}) - self.assertRaises(TypeError, u"%(foo)s %(bar)s".__mod__, (u"foo", 42)) - - # argument names with properly nested brackets are supported - self.assertEqual(u"%((foo))s" % {u"(foo)": u"bar"}, u"bar") - - # 100 is a magic number in PyUnicode_Format, this forces a resize - self.assertEqual(u"%sx" % (103*u"a"), 103*u"a"+u"x") - - self.assertRaises(TypeError, u"%*s".__mod__, (u"foo", u"bar")) - self.assertRaises(TypeError, u"%10.*f".__mod__, (u"foo", 42.)) - self.assertRaises(ValueError, u"%10".__mod__, (42,)) def test_constructor(self): --- 375,381 ---- self.assertEqual('%*.*s' % (5,3,u'abc',), u' abc') self.assertEqual('%i %*.*s' % (10, 5,3,u'abc',), u'10 abc') ! self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, u'abc',), u'103 abc') self.assertRaises(ValueError, u"%c".__mod__, (sys.maxunicode+1,)) def test_constructor(self): *************** *** 1024,1062 **** print >>out, u'def\n' - def test_mul(self): - self.checkmethod('__mul__', u'abc', u'', -1) - self.checkmethod('__mul__', u'abc', u'', 0) - self.checkmethod('__mul__', u'abc', u'abc', 1) - self.checkmethod('__mul__', u'abc', u'abcabcabc', 3) - self.assertRaises(OverflowError, (10000*u'abc').__mul__, sys.maxint) - - def test_subscript(self): - self.checkmethod('__getitem__', u'abc', u'a', 0) - self.checkmethod('__getitem__', u'abc', u'c', -1) - self.checkmethod('__getitem__', u'abc', u'a', 0L) - self.checkmethod('__getitem__', u'abc', u'abc', slice(0, 3)) - self.checkmethod('__getitem__', u'abc', u'abc', slice(0, 1000)) - self.checkmethod('__getitem__', u'abc', u'a', slice(0, 1)) - self.checkmethod('__getitem__', u'abc', u'', slice(0, 0)) - # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice) - - self.assertRaises(TypeError, u"abc".__getitem__, "def") - - def test_slice(self): - self.checkmethod('__getslice__', u'abc', u'abc', 0, 1000) - self.checkmethod('__getslice__', u'abc', u'abc', 0, 3) - self.checkmethod('__getslice__', u'abc', u'ab', 0, 2) - self.checkmethod('__getslice__', u'abc', u'bc', 1, 3) - self.checkmethod('__getslice__', u'abc', u'b', 1, 2) - self.checkmethod('__getslice__', u'abc', u'', 2, 2) - self.checkmethod('__getslice__', u'abc', u'', 1000, 1000) - self.checkmethod('__getslice__', u'abc', u'', 2000, 1000) - self.checkmethod('__getslice__', u'abc', u'', 2, 1) - # FIXME What about negative indizes? This is handled differently by [] and __getslice__ - def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(UnicodeTest)) ! test.test_support.run_suite(suite) if __name__ == "__main__": --- 695,702 ---- print >>out, u'def\n' def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(UnicodeTest)) ! test_support.run_suite(suite) if __name__ == "__main__": Index: test_userstring.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_userstring.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** test_userstring.py 9 Aug 2002 01:37:06 -0000 1.9 --- test_userstring.py 21 Feb 2003 12:53:49 -0000 1.10 *************** *** 1,45 **** #!/usr/bin/env python - import sys - from test.test_support import verbose - from test import string_tests # UserString is a wrapper around the native builtin string type. # UserString instances should behave similar to builtin string objects. ! # The test cases were in part derived from 'test_string.py'. from UserString import UserString ! if __name__ == "__main__": ! verbose = '-v' in sys.argv ! tested_methods = {} ! def test(methodname, input, output, *args): ! global tested_methods ! tested_methods[methodname] = 1 ! if verbose: ! print '%r.%s(%s)' % (input, methodname, ", ".join(map(repr, args))), ! u = UserString(input) ! objects = [input, u, UserString(u)] ! res = [""] * 3 ! for i in range(3): ! object = objects[i] ! try: ! f = getattr(object, methodname) ! except AttributeError: ! f = None ! res[i] = AttributeError ! else: ! try: ! res[i] = apply(f, args) ! except: ! res[i] = sys.exc_type ! if res[0] == res[1] == res[2] == output: ! if verbose: ! print 'yes' ! else: ! if verbose: ! print 'no' ! print (methodname, input, output, args, res[0], res[1], res[2]) ! string_tests.run_method_tests(test) ! string_tests.run_contains_tests(test) ! string_tests.run_inplace_tests(UserString) --- 1,52 ---- #!/usr/bin/env python # UserString is a wrapper around the native builtin string type. # UserString instances should behave similar to builtin string objects. ! ! import unittest ! from test import test_support, string_tests ! from UserString import UserString ! class UserStringTest( ! string_tests.CommonTest, ! string_tests.MixinStrUnicodeUserStringTest, ! string_tests.MixinStrStringUserStringTest, ! string_tests.MixinStrUserStringTest ! ): ! type2test = UserString ! # Overwrite the three testing methods, because UserString ! # can't cope with arguments propagated to UserString ! # (and we don't test with subclasses) ! def checkequal(self, result, object, methodname, *args): ! result = self.fixtype(result) ! object = self.fixtype(object) ! # we don't fix the arguments, because UserString can't cope with it ! realresult = getattr(object, methodname)(*args) ! self.assertEqual( ! result, ! realresult ! ) ! def checkraises(self, exc, object, methodname, *args): ! object = self.fixtype(object) ! # we don't fix the arguments, because UserString can't cope with it ! self.assertRaises( ! exc, ! getattr(object, methodname), ! *args ! ) ! ! def checkcall(self, object, methodname, *args): ! object = self.fixtype(object) ! # we don't fix the arguments, because UserString can't cope with it ! getattr(object, methodname)(*args) ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(UserStringTest)) ! test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() From akuchling@users.sourceforge.net Fri Feb 21 15:24:46 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 21 Feb 2003 07:24:46 -0800 Subject: [Python-checkins] python/nondist/peps pep-0263.txt,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv1492 Modified Files: pep-0263.txt Log Message: Fix grammar nit Index: pep-0263.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0263.txt,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** pep-0263.txt 3 Sep 2002 11:56:15 -0000 1.15 --- pep-0263.txt 21 Feb 2003 15:24:41 -0000 1.16 *************** *** 52,56 **** # -*- coding: -*- ! More precise, the first or second line must match the regular expression "coding[:=]\s*([\w-_.]+)". The first group of this expression is then interpreted as encoding name. If the encoding --- 52,56 ---- # -*- coding: -*- ! More precisely, the first or second line must match the regular expression "coding[:=]\s*([\w-_.]+)". The first group of this expression is then interpreted as encoding name. If the encoding From jackjansen@users.sourceforge.net Fri Feb 21 16:31:15 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 08:31:15 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules macosmodule.c,1.63,1.64 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv28507 Modified Files: macosmodule.c Log Message: Added a method WMAvailable(). This will return True if and only if there is a window manager and we can connect to it, i.e. if it is safe to try and put up windows. As a side effect the first call will make the current process frontmost. Index: macosmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/macosmodule.c,v retrieving revision 1.63 retrieving revision 1.64 diff -C2 -d -r1.63 -r1.64 *** macosmodule.c 23 Dec 2002 23:16:20 -0000 1.63 --- macosmodule.c 21 Feb 2003 16:31:11 -0000 1.64 *************** *** 37,40 **** --- 37,41 ---- #else #include + #include #endif *************** *** 522,525 **** --- 523,567 ---- } + static char WMAvailable_doc[] = + "True if this process can interact with the display." + "Will foreground the application on the first call as a side-effect." + ; + + static PyObject * + MacOS_WMAvailable(PyObject *self, PyObject *args) + { + static PyObject *rv = NULL; + + if (!PyArg_ParseTuple(args, "")) + return NULL; + if (!rv) { + #if TARGET_API_MAC_OSX + ProcessSerialNumber psn; + + /* + ** This is a fairly innocuous call to make if we don't have a window + ** manager, or if we have no permission to talk to it. It will print + ** a message on stderr, but at least it won't abort the process. + ** It appears the function caches the result itself, and it's cheap, so + ** no need for us to cache. + */ + if (CGMainDisplayID() == 0) { + rv = Py_False; + } else { + if (GetCurrentProcess(&psn) < 0 || + SetFrontProcess(&psn) < 0) { + rv = Py_False; + } else { + rv = Py_True; + } + } + #else + rv = Py_True; + #endif + } + Py_INCREF(rv); + return rv; + } + static char GetTicks_doc[] = "Return number of ticks since bootup"; *************** *** 673,676 **** --- 715,719 ---- {"GetTicks", MacOS_GetTicks, 1, GetTicks_doc}, {"SysBeep", MacOS_SysBeep, 1, SysBeep_doc}, + {"WMAvailable", MacOS_WMAvailable, 1, WMAvailable_doc}, #if !TARGET_API_MAC_OSX {"FreeMem", MacOS_FreeMem, 1, FreeMem_doc}, From tim_one@users.sourceforge.net Fri Feb 21 16:45:43 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 21 Feb 2003 08:45:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_timeout.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2114/python/Lib/test Modified Files: test_timeout.py Log Message: Doubled TimeoutTestCase.fuzz, to slash the frequency of bogus failures on the boxes I use. Index: test_timeout.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_timeout.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** test_timeout.py 17 Feb 2003 14:51:41 -0000 1.10 --- test_timeout.py 21 Feb 2003 16:45:41 -0000 1.11 *************** *** 88,92 **** """Test case for socket.socket() timeout functions""" ! fuzz = 1.0 def setUp(self): --- 88,98 ---- """Test case for socket.socket() timeout functions""" ! # There are a number of tests here trying to make sure that an operation ! # doesn't take too much longer than expected. But competing machine ! # activity makes it inevitable that such tests will fail at times. ! # When fuzz was at 1.0, I (tim) routinely saw bogus failures on Win2K ! # and Win98SE. Boosting it to 2.0 helped a lot, but isn't a real ! # solution. ! fuzz = 2.0 def setUp(self): From doerwalter@users.sourceforge.net Fri Feb 21 18:18:52 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 21 Feb 2003 10:18:52 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9676/Modules Modified Files: _iconv_codec.c Log Message: Use 'ISO8859-1' instead of 'ASCII' when testing whether byteswapping is required for the chosen internal encoding in the init function, as this seems to have a better chance of working under Irix and Solaris. Also change the test character from '\x01' to '0'. This might fix SF bug #690309. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _iconv_codec.c 18 Feb 2003 16:11:11 -0000 1.11 --- _iconv_codec.c 21 Feb 2003 18:18:49 -0000 1.12 *************** *** 664,668 **** PyObject *m; ! char in = 1; char *inptr = ∈ size_t insize = 1; --- 664,668 ---- PyObject *m; ! char in = '0'; char *inptr = ∈ size_t insize = 1; *************** *** 672,676 **** size_t res; ! iconv_t hdl = iconv_open(UNICODE_ENCODING, "ASCII"); if (hdl == (iconv_t)-1) { --- 672,676 ---- size_t res; ! iconv_t hdl = iconv_open(UNICODE_ENCODING, "ISO8859-1"); if (hdl == (iconv_t)-1) { *************** *** 689,698 **** /* Check whether conv() returned native endianess or not for the chosen encoding */ ! if (out == 0x1) byteswap = 0; #if Py_UNICODE_SIZE == 2 ! else if (out == 0x0100) #else ! else if (out == 0x01000000) #endif byteswap = 1; --- 689,698 ---- /* Check whether conv() returned native endianess or not for the chosen encoding */ ! if (out == 0x30) byteswap = 0; #if Py_UNICODE_SIZE == 2 ! else if (out == 0x3000) #else ! else if (out == 0x30000000) #endif byteswap = 1; From nnorwitz@users.sourceforge.net Fri Feb 21 18:57:09 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 21 Feb 2003 10:57:09 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libreadline.tex,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv23148/lib Modified Files: libreadline.tex Log Message: Add some minimal doc for get_completer added for patch 676342 Index: libreadline.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libreadline.tex,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** libreadline.tex 19 Oct 2001 01:18:43 -0000 1.8 --- libreadline.tex 21 Feb 2003 18:57:05 -0000 1.9 *************** *** 81,84 **** --- 81,89 ---- \end{funcdesc} + \begin{funcdesc}{get_completer}{} + Get the completer function. + \versionadded{2.3} + \end{funcdesc} + \begin{funcdesc}{get_begidx}{} Get the beginning index of the readline tab-completion scope. From mwh@users.sourceforge.net Fri Feb 21 20:11:11 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Fri, 21 Feb 2003 12:11:11 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libreadline.tex,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21537 Modified Files: libreadline.tex Log Message: I'm am the PyPy sprint waiting for a Grand Renaming so I killed a few seconds making the doc for get_completer marginally less minimal :) Index: libreadline.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libreadline.tex,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** libreadline.tex 21 Feb 2003 18:57:05 -0000 1.9 --- libreadline.tex 21 Feb 2003 20:11:09 -0000 1.10 *************** *** 82,87 **** \begin{funcdesc}{get_completer}{} ! Get the completer function. ! \versionadded{2.3} \end{funcdesc} --- 82,87 ---- \begin{funcdesc}{get_completer}{} ! Get the completer function, or \code{None} if no completer function ! has been set. \versionadded{2.3} \end{funcdesc} From tim_one@users.sourceforge.net Fri Feb 21 20:14:37 2003 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 21 Feb 2003 12:14:37 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_cpickle.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22191/Lib/test Modified Files: test_cpickle.py Log Message: SF bug 690622: test_cpickle overflows stack on MacOS9. test_nonrecursive_deep(): Reduced nesting depth to 60. Not a bugfix candidate. 2.3 increased the number of stack frames needed to pickle a list (in order to get implement the "list batching" unpickling memory optimization new in 2.3). Index: test_cpickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_cpickle.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** test_cpickle.py 28 Jan 2003 22:26:28 -0000 1.13 --- test_cpickle.py 21 Feb 2003 20:14:35 -0000 1.14 *************** *** 82,87 **** def test_nonrecursive_deep(self): a = [] ! for i in range(100): a = [a] b = self.loads(self.dumps(a)) --- 82,91 ---- def test_nonrecursive_deep(self): + # If it's not cyclic, it should pickle OK even if the nesting + # depth exceeds PY_CPICKLE_FAST_LIMIT. That happens to be + # 50 today. Jack Jansen reported stack overflow on Mac OS 9 + # at 64. a = [] ! for i in range(60): a = [a] b = self.loads(self.dumps(a)) From jackjansen@users.sourceforge.net Fri Feb 21 21:56:58 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 13:56:58 -0800 Subject: [Python-checkins] python/dist/src/Mac/mwerks mwerks_pyexpat_config.h,NONE,1.1.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/mwerks In directory sc8-pr-cvs1:/tmp/cvs-serv2383 Added Files: Tag: r23a2-branch mwerks_pyexpat_config.h Log Message: Pyexpat needs a specific definitions file again. --- NEW FILE: mwerks_pyexpat_config.h --- /* ** Configuration file for dynamically loaded Carbon pyexpat module. */ #include "mwerks_shcarbon_config.h" #define XML_NS 1 #define XML_DTD 1 #define BYTEORDER 4321 #define XML_CONTEXT_BYTES 1024 From jackjansen@users.sourceforge.net Fri Feb 21 21:57:04 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 13:57:04 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts genpluginprojects.py,1.39,1.39.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv2425a Modified Files: Tag: r23a2-branch genpluginprojects.py Log Message: Pyexpat needs a specific definitions file again. Index: genpluginprojects.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/genpluginprojects.py,v retrieving revision 1.39 retrieving revision 1.39.2.1 diff -C2 -d -r1.39 -r1.39.2.1 *** genpluginprojects.py 8 Jan 2003 16:27:44 -0000 1.39 --- genpluginprojects.py 21 Feb 2003 21:57:02 -0000 1.39.2.1 *************** *** 102,106 **** sources=["pyexpat.c", "xmlparse.c", "xmlrole.c", "xmltok.c"], extradirs=[":::Modules:expat"], ! prefixname="mwerks_shcarbon_config.h" ) genpluginproject("carbon", "zlib", --- 102,106 ---- sources=["pyexpat.c", "xmlparse.c", "xmlrole.c", "xmltok.c"], extradirs=[":::Modules:expat"], ! prefixname="mwerks_pyexpat_config.h" ) genpluginproject("carbon", "zlib", From jackjansen@users.sourceforge.net Fri Feb 21 21:57:37 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 13:57:37 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyEdit.py,1.37,1.37.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv2722 Modified Files: Tag: r23a2-branch PyEdit.py Log Message: Save as Applet was broken under OS9. Fixed. Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.37 retrieving revision 1.37.2.1 diff -C2 -d -r1.37 -r1.37.2.1 *** PyEdit.py 16 Feb 2003 21:28:51 -0000 1.37 --- PyEdit.py 21 Feb 2003 21:57:35 -0000 1.37.2.1 *************** *** 472,476 **** pass template = buildtools.findtemplate() ! buildtools.process(template, filename, destname, rsrcname=rsrcname, progress=None) try: os.remove(filename) --- 472,476 ---- pass template = buildtools.findtemplate() ! buildtools.process(template, filename, destname, 1, rsrcname=rsrcname, progress=None) try: os.remove(filename) From jackjansen@users.sourceforge.net Fri Feb 21 21:58:48 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 13:58:48 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_cpickle.py,1.13,1.13.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3203 Modified Files: Tag: r23a2-branch test_cpickle.py Log Message: This test overflowed the stack in MacPython-OS9 under classic or on OS9. Lowered the recursion limit to 50 if platform==mac. Index: test_cpickle.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_cpickle.py,v retrieving revision 1.13 retrieving revision 1.13.2.1 diff -C2 -d -r1.13 -r1.13.2.1 *** test_cpickle.py 28 Jan 2003 22:26:28 -0000 1.13 --- test_cpickle.py 21 Feb 2003 21:58:46 -0000 1.13.2.1 *************** *** 4,8 **** --- 4,14 ---- from pickletester import AbstractPickleTests, AbstractPickleModuleTests from test import test_support + import sys + if sys.platform == 'mac': + NRECURSION=50 + else: + NRECURSION=100 + class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests): *************** *** 83,87 **** def test_nonrecursive_deep(self): a = [] ! for i in range(100): a = [a] b = self.loads(self.dumps(a)) --- 89,93 ---- def test_nonrecursive_deep(self): a = [] ! for i in range(NRECURSION): a = [a] b = self.loads(self.dumps(a)) From jackjansen@users.sourceforge.net Fri Feb 21 21:59:20 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 13:59:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.128,1.128.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3409 Modified Files: Tag: r23a2-branch regrtest.py Log Message: test-posix isn't run on MacOS. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.128 retrieving revision 1.128.2.1 diff -C2 -d -r1.128 -r1.128.2.1 *** regrtest.py 19 Feb 2003 02:35:05 -0000 1.128 --- regrtest.py 21 Feb 2003 21:59:17 -0000 1.128.2.1 *************** *** 634,637 **** --- 634,638 ---- test_popen test_popen2 + test_posix test_pty test_pwd From jackjansen@users.sourceforge.net Fri Feb 21 22:00:46 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:00:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/logging __init__.py,1.5,1.5.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/logging In directory sc8-pr-cvs1:/tmp/cvs-serv4010 Modified Files: Tag: r23a2-branch __init__.py Log Message: getpid doesn't exist on MacOS9. Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/__init__.py,v retrieving revision 1.5 retrieving revision 1.5.2.1 diff -C2 -d -r1.5 -r1.5.2.1 *** __init__.py 18 Feb 2003 14:20:06 -0000 1.5 --- __init__.py 21 Feb 2003 22:00:39 -0000 1.5.2.1 *************** *** 214,218 **** else: self.thread = None ! self.process = os.getpid() def __str__(self): --- 214,221 ---- else: self.thread = None ! if hasattr(os, 'getpid'): ! self.process = os.getpid() ! else: ! self.process = None def __str__(self): From jackjansen@users.sourceforge.net Fri Feb 21 22:01:50 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:01:50 -0800 Subject: [Python-checkins] python/dist/src/Mac ReadMe,1.46,1.46.2.1 _checkversion.py,1.12,1.12.6.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac In directory sc8-pr-cvs1:/tmp/cvs-serv4382 Modified Files: Tag: r23a2-branch ReadMe _checkversion.py Log Message: Files used for MacPython-OS9 2.3a2 distribution. Index: ReadMe =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/ReadMe,v retrieving revision 1.46 retrieving revision 1.46.2.1 diff -C2 -d -r1.46 -r1.46.2.1 *** ReadMe 8 Jan 2003 16:27:29 -0000 1.46 --- ReadMe 21 Feb 2003 22:01:44 -0000 1.46.2.1 *************** *** 1,3 **** ! How to install MacPython-OS9 2.3a1 on your Macintosh ---------------------------------------------------- --- 1,3 ---- ! How to install MacPython-OS9 2.3a2 on your Macintosh ---------------------------------------------------- *************** *** 19,23 **** only modules that are not shared with MacPython-OSX 2.3. - macfs is now a pure Python wrapper module around various modules in the ! Carbon package. For 2.3a1 only this wrapping is incomplete: fsspec.SetDates() does not work yet. If you encounter any other problems please report them. --- 19,23 ---- only modules that are not shared with MacPython-OSX 2.3. - macfs is now a pure Python wrapper module around various modules in the ! Carbon package. For 2.3a2 only this wrapping is incomplete: fsspec.SetDates() does not work yet. If you encounter any other problems please report them. *************** *** 76,83 **** Python and "import test.regrtest ; test.regrtest.main()". ! test_httplib fails with an unexpected output error, ! this problem is being investigated. ! test_socket fails, this problem is being investigated. Three tests will fail on MacOS9 with MemoryErrors: --- 76,82 ---- Python and "import test.regrtest ; test.regrtest.main()". ! test_socket and test_logging fail, this problem is being investigated. ! test_tarfile fails, this problem is being investigated. Three tests will fail on MacOS9 with MemoryErrors: *************** *** 125,129 **** Up to three items are installed in the MacOS 8 or 9 system folder: the interpreter shared library PythonCore lives in the Extensions ! folder and the "Python 2.3a1 Preferences" file in the Python subfolder in the Preferences folder. All the rest of Python lives in the folder you installed in. --- 124,128 ---- Up to three items are installed in the MacOS 8 or 9 system folder: the interpreter shared library PythonCore lives in the Extensions ! folder and the "Python 2.3a2 Preferences" file in the Python subfolder in the Preferences folder. All the rest of Python lives in the folder you installed in. *************** *** 169,175 **** are lost and you have to set them again. ! After you are satisfied that 2.3a1 works as expected you can trash anything in the system folder that has "python" in the name and not ! "2.3a1". The ConfigurePython applet will try to detect incompatible --- 168,174 ---- are lost and you have to set them again. ! After you are satisfied that 2.3a2 works as expected you can trash anything in the system folder that has "python" in the name and not ! "2.3a2". The ConfigurePython applet will try to detect incompatible Index: _checkversion.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/_checkversion.py,v retrieving revision 1.12 retrieving revision 1.12.6.1 diff -C2 -d -r1.12 -r1.12.6.1 *** _checkversion.py 27 Dec 2001 23:01:17 -0000 1.12 --- _checkversion.py 21 Feb 2003 22:01:46 -0000 1.12.6.1 *************** *** 6,10 **** _PACKAGE="MacPython" ! _VERSION="2.2" _URL="http://www.cwi.nl/~jack/macpythonversion.txt" --- 6,10 ---- _PACKAGE="MacPython" ! _VERSION="2.3a2" _URL="http://www.cwi.nl/~jack/macpythonversion.txt" From jackjansen@users.sourceforge.net Fri Feb 21 22:02:27 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:02:27 -0800 Subject: [Python-checkins] python/dist/src/Mac/Build _CG.carbon.mcp,1.6,1.6.2.1 PythonCore.mcp,1.43,1.43.2.1 PythonInterpreter.mcp,1.22,1.22.2.1 PythonStandSmall.mcp,1.49,1.49.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Build In directory sc8-pr-cvs1:/tmp/cvs-serv4470 Modified Files: Tag: r23a2-branch _CG.carbon.mcp PythonCore.mcp PythonInterpreter.mcp PythonStandSmall.mcp Log Message: Files used for MacPython-OS9 2.3a2 distribution. Index: _CG.carbon.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/_CG.carbon.mcp,v retrieving revision 1.6 retrieving revision 1.6.2.1 diff -C2 -d -r1.6 -r1.6.2.1 Binary files /tmp/cvsS6HYNk and /tmp/cvsR0q1Gl differ Index: PythonCore.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonCore.mcp,v retrieving revision 1.43 retrieving revision 1.43.2.1 diff -C2 -d -r1.43 -r1.43.2.1 Binary files /tmp/cvsHZwAcL and /tmp/cvsKFANLl differ Index: PythonInterpreter.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonInterpreter.mcp,v retrieving revision 1.22 retrieving revision 1.22.2.1 diff -C2 -d -r1.22 -r1.22.2.1 Binary files /tmp/cvsEs3OfV and /tmp/cvscDTqnI differ Index: PythonStandSmall.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonStandSmall.mcp,v retrieving revision 1.49 retrieving revision 1.49.2.1 diff -C2 -d -r1.49 -r1.49.2.1 Binary files /tmp/cvsu6RRLs and /tmp/cvse223jM differ From jackjansen@users.sourceforge.net Fri Feb 21 22:02:33 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:02:33 -0800 Subject: [Python-checkins] python/dist/src/Mac/Distributions dev.include,1.28,1.28.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Distributions In directory sc8-pr-cvs1:/tmp/cvs-serv4755 Modified Files: Tag: r23a2-branch dev.include Log Message: Files used for MacPython-OS9 2.3a2 distribution. Index: dev.include =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Distributions/dev.include,v retrieving revision 1.28 retrieving revision 1.28.2.1 diff -C2 -d -r1.28 -r1.28.2.1 *** dev.include 8 Jan 2003 16:27:38 -0000 1.28 --- dev.include 21 Feb 2003 22:02:30 -0000 1.28.2.1 *************** *** 95,98 **** --- 95,101 ---- (':Mac:Build:_AH.carbon.mcp.exp', None) (':Mac:Build:_AH.carbon.mcp.xml', None) + (':Mac:Build:_Alias.carbon.mcp', None) + (':Mac:Build:_Alias.carbon.mcp.exp', None) + (':Mac:Build:_Alias.carbon.mcp.xml', None) (':Mac:Build:_App.carbon.mcp', None) (':Mac:Build:_App.carbon.mcp.exp', None) *************** *** 140,143 **** --- 143,149 ---- (':Mac:Build:_Evt.mcp.exp', None) (':Mac:Build:_Evt.mcp.xml', None) + (':Mac:Build:_File.carbon.mcp', None) + (':Mac:Build:_File.carbon.mcp.exp', None) + (':Mac:Build:_File.carbon.mcp.xml', None) (':Mac:Build:_Fm.carbon.mcp', None) (':Mac:Build:_Fm.carbon.mcp.exp', None) *************** *** 146,149 **** --- 152,158 ---- (':Mac:Build:_Fm.mcp.exp', None) (':Mac:Build:_Fm.mcp.xml', None) + (':Mac:Build:_Folder.carbon.mcp', None) + (':Mac:Build:_Folder.carbon.mcp.exp', None) + (':Mac:Build:_Folder.carbon.mcp.xml', None) (':Mac:Build:_Help.carbon.mcp', None) (':Mac:Build:_Help.carbon.mcp.exp', None) *************** *** 270,273 **** --- 279,285 ---- (':Mac:Build:ctb.mcp.exp', None) (':Mac:Build:ctb.mcp.xml', None) + (':Mac:Build:datetime.carbon.mcp', None) + (':Mac:Build:datetime.carbon.mcp.exp', None) + (':Mac:Build:datetime.carbon.mcp.xml', None) (':Mac:Build:gdbm.carbon.mcp', None) (':Mac:Build:gdbm.carbon.mcp.exp', None) *************** *** 437,440 **** --- 449,453 ---- (':Modules:Setup.in', None) (':Modules:Setup.thread.in', None) + (':Modules:_bsddb.c', None) (':Modules:_codecsmodule.c', None) (':Modules:_curses_panel.c', None) *************** *** 442,445 **** --- 455,459 ---- (':Modules:_hotshot.c', None) (':Modules:_localemodule.c', None) + (':Modules:_randommodule.c', None) (':Modules:_sre.c', None) (':Modules:_ssl.c', None) *************** *** 454,457 **** --- 468,472 ---- (':Modules:binascii.c', None) (':Modules:bsddbmodule.c', None) + (':Modules:bz2module.c', None) (':Modules:cPickle.c', None) (':Modules:cStringIO.c', None) *************** *** 467,470 **** --- 482,486 ---- (':Modules:cstubs', None) (':Modules:cursesmodule.c', None) + (':Modules:datetimemodule.c', None) (':Modules:dbmmodule.c', None) (':Modules:dlmodule.c', None) *************** *** 501,504 **** --- 517,521 ---- (':Modules:nismodule.c', None) (':Modules:operator.c', None) + (':Modules:ossaudiodev.c', None) (':Modules:parsermodule.c', None) (':Modules:pcre-int.h', None) *************** *** 554,557 **** --- 571,575 ---- (':Modules:yuv.h', None) (':Modules:yuvconvert.c', None) + (':Modules:zipimport.c', None) (':Modules:zlibmodule.c', None) (':Modules:zlibmodule.c~0', None) *************** *** 612,631 **** (':setup.py', None) (':site-packages', None) ! (':Mac:Build:_Folder.carbon.mcp.xml', None) ! (':Mac:Build:_Folder.carbon.mcp.exp', None) ! (':Mac:Build:_Folder.carbon.mcp', None) ! (':Mac:Build:_File.carbon.mcp.xml', None) ! (':Mac:Build:_File.carbon.mcp.exp', None) ! (':Mac:Build:_File.carbon.mcp', None) ! (':Mac:Build:_Alias.carbon.mcp.xml', None) ! (':Mac:Build:_Alias.carbon.mcp.exp', None) ! (':Mac:Build:_Alias.carbon.mcp', None) ! (':Modules:zipimport.c', None) ! (':Modules:ossaudiodev.c', None) ! (':Modules:datetimemodule.c', None) ! (':Modules:bz2module.c', None) ! (':Modules:_randommodule.c', None) ! (':Modules:_bsddb.c', None) ! (':Mac:Build:datetime.carbon.mcp.xml', None) ! (':Mac:Build:datetime.carbon.mcp.exp', None) ! (':Mac:Build:datetime.carbon.mcp', None) --- 630,634 ---- (':setup.py', None) (':site-packages', None) ! (':Modules:itertoolsmodule.c', None) ! (':Modules:_iconv_codec.c', None) ! (':Mac:mwerks:mwerks_pyexpat_config.h', None) From gvanrossum@users.sourceforge.net Fri Feb 21 22:02:59 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:02:59 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.213,2.214 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv4931 Modified Files: typeobject.c Log Message: Implementing the salient parts of __reduce_ex__ in C. This still falls back to helpers in copy_reg for: - pickle protocols < 2 - calculating the list of slot names (done only once per class) - the __newobj__ function (which is used as a token but never called) Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.213 retrieving revision 2.214 diff -C2 -d -r2.213 -r2.214 *** typeobject.c 18 Feb 2003 22:05:09 -0000 2.213 --- typeobject.c 21 Feb 2003 22:02:54 -0000 2.214 *************** *** 2441,2450 **** }; static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { /* Call copy_reg._reduce_ex(self, proto) */ ! static PyObject *copy_reg_str; ! PyObject *copy_reg, *res; int proto = 0; --- 2441,2642 ---- }; + + /* Stuff to implement __reduce_ex__ for pickle protocols >= 2. + We fall back to helpers in copy_reg for: + - pickle protocols < 2 + - calculating the list of slot names (done only once per class) + - the __newobj__ function (which is used as a token but never called) + */ + + static PyObject * + import_copy_reg(void) + { + static PyObject *copy_reg_str; + + if (!copy_reg_str) { + copy_reg_str = PyString_InternFromString("copy_reg"); + if (copy_reg_str == NULL) + return NULL; + } + + return PyImport_Import(copy_reg_str); + } + + static PyObject * + slotnames(PyObject *cls) + { + PyObject *clsdict; + PyObject *copy_reg; + PyObject *slotnames; + + if (!PyType_Check(cls)) { + Py_INCREF(Py_None); + return Py_None; + } + + clsdict = ((PyTypeObject *)cls)->tp_dict; + slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); + if (slotnames != NULL) { + Py_INCREF(slotnames); + return slotnames; + } + + copy_reg = import_copy_reg(); + if (copy_reg == NULL) + return NULL; + + slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls); + Py_DECREF(copy_reg); + if (slotnames != NULL && + slotnames != Py_None && + !PyList_Check(slotnames)) + { + PyErr_SetString(PyExc_TypeError, + "copy_reg._slotnames didn't return a list or None"); + Py_DECREF(slotnames); + slotnames = NULL; + } + + return slotnames; + } + + static PyObject * + reduce_2(PyObject *obj) + { + PyObject *cls, *getnewargs; + PyObject *args = NULL, *args2 = NULL; + PyObject *getstate = NULL, *state = NULL, *names = NULL; + PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; + PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL; + int i, n; + + cls = PyObject_GetAttrString(obj, "__class__"); + if (cls == NULL) + return NULL; + + getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); + if (getnewargs != NULL) { + args = PyObject_CallObject(getnewargs, NULL); + Py_DECREF(getnewargs); + if (args != NULL && !PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "__getnewargs__ should return a tuple"); + goto end; + } + } + else { + PyErr_Clear(); + args = PyTuple_New(0); + } + if (args == NULL) + goto end; + + getstate = PyObject_GetAttrString(obj, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, NULL); + Py_DECREF(getstate); + } + else { + state = PyObject_GetAttrString(obj, "__dict__"); + if (state == NULL) { + PyErr_Clear(); + state = Py_None; + Py_INCREF(state); + } + names = slotnames(cls); + if (names == NULL) + goto end; + if (names != Py_None) { + assert(PyList_Check(names)); + slots = PyDict_New(); + if (slots == NULL) + goto end; + n = 0; + /* Can't pre-compute the list size; the list + is stored on the class so accessible to other + threads, which may be run by DECREF */ + for (i = 0; i < PyList_GET_SIZE(names); i++) { + PyObject *name, *value; + name = PyList_GET_ITEM(names, i); + value = PyObject_GetAttr(obj, name); + if (value == NULL) + PyErr_Clear(); + else { + int err = PyDict_SetItem(slots, name, + value); + Py_DECREF(value); + if (err) + goto end; + n++; + } + } + if (n) { + state = Py_BuildValue("(NO)", state, slots); + if (state == NULL) + goto end; + } + } + } + + if (!PyList_Check(obj)) { + listitems = Py_None; + Py_INCREF(listitems); + } + else { + listitems = PyObject_GetIter(obj); + if (listitems == NULL) + goto end; + } + + if (!PyDict_Check(obj)) { + dictitems = Py_None; + Py_INCREF(dictitems); + } + else { + dictitems = PyObject_CallMethod(obj, "iteritems", ""); + if (dictitems == NULL) + goto end; + } + + copy_reg = import_copy_reg(); + if (copy_reg == NULL) + goto end; + newobj = PyObject_GetAttrString(copy_reg, "__newobj__"); + if (newobj == NULL) + goto end; + + n = PyTuple_GET_SIZE(args); + args2 = PyTuple_New(n+1); + if (args2 == NULL) + goto end; + PyTuple_SET_ITEM(args2, 0, cls); + cls = NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyTuple_GET_ITEM(args, i); + Py_INCREF(v); + PyTuple_SET_ITEM(args2, i+1, v); + } + + res = Py_BuildValue("(OOOOO)", + newobj, args2, state, listitems, dictitems); + + end: + Py_XDECREF(cls); + Py_XDECREF(args); + Py_XDECREF(args2); + Py_XDECREF(state); + Py_XDECREF(names); + Py_XDECREF(listitems); + Py_XDECREF(dictitems); + Py_XDECREF(copy_reg); + Py_XDECREF(newobj); + return res; + } + static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { /* Call copy_reg._reduce_ex(self, proto) */ ! PyObject *reduce, *copy_reg, *res; int proto = 0; *************** *** 2452,2465 **** return NULL; ! if (!copy_reg_str) { ! copy_reg_str = PyString_InternFromString("copy_reg"); ! if (copy_reg_str == NULL) return NULL; } ! copy_reg = PyImport_Import(copy_reg_str); if (!copy_reg) return NULL; res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto); Py_DECREF(copy_reg); return res; } --- 2644,2687 ---- return NULL; ! reduce = PyObject_GetAttrString(self, "__reduce__"); ! if (reduce == NULL) ! PyErr_Clear(); ! else { ! PyObject *cls, *clsreduce, *objreduce; ! int override; ! cls = PyObject_GetAttrString(self, "__class__"); ! if (cls == NULL) { ! Py_DECREF(reduce); ! return NULL; ! } ! clsreduce = PyObject_GetAttrString(cls, "__reduce__"); ! Py_DECREF(cls); ! if (clsreduce == NULL) { ! Py_DECREF(reduce); return NULL; + } + objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, + "__reduce__"); + override = (clsreduce != objreduce); + Py_DECREF(clsreduce); + if (override) { + res = PyObject_CallObject(reduce, NULL); + Py_DECREF(reduce); + return res; + } + else + Py_DECREF(reduce); } ! ! if (proto >= 2) ! return reduce_2(self); ! ! copy_reg = import_copy_reg(); if (!copy_reg) return NULL; + res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto); Py_DECREF(copy_reg); + return res; } *************** *** 2472,2475 **** --- 2694,2698 ---- {0} }; + PyTypeObject PyBaseObject_Type = { From jackjansen@users.sourceforge.net Fri Feb 21 22:03:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:03:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/Distributions/(vise) Python 2.3.vct,1.5,1.5.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Distributions/(vise) In directory sc8-pr-cvs1:/tmp/cvs-serv4826 Modified Files: Tag: r23a2-branch Python 2.3.vct Log Message: Files used for MacPython-OS9 2.3a2 distribution. Index: Python 2.3.vct =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Distributions/(vise)/Python 2.3.vct,v retrieving revision 1.5 retrieving revision 1.5.2.1 diff -C2 -d -r1.5 -r1.5.2.1 Binary files /tmp/cvsN250v4 and /tmp/cvsm5VhA1 differ From jackjansen@users.sourceforge.net Fri Feb 21 22:03:19 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:03:19 -0800 Subject: [Python-checkins] python/dist/src/Mac/Include macbuildno.h,1.26,1.26.2.1 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Include In directory sc8-pr-cvs1:/tmp/cvs-serv5131 Modified Files: Tag: r23a2-branch macbuildno.h Log Message: Files used for MacPython-OS9 2.3a2 distribution. Index: macbuildno.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Include/macbuildno.h,v retrieving revision 1.26 retrieving revision 1.26.2.1 diff -C2 -d -r1.26 -r1.26.2.1 *** macbuildno.h 8 Jan 2003 16:27:40 -0000 1.26 --- macbuildno.h 21 Feb 2003 22:03:16 -0000 1.26.2.1 *************** *** 1 **** ! #define BUILD 148 --- 1 ---- ! #define BUILD 154 From jackjansen@users.sourceforge.net Fri Feb 21 22:11:48 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:11:48 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/waste wastescan.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/waste In directory sc8-pr-cvs1:/tmp/cvs-serv8570/Mac/Modules/waste Modified Files: wastescan.py Log Message: WASTEconst.py goes one level above the toolbox directory. Index: wastescan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/waste/wastescan.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** wastescan.py 18 Nov 2002 15:26:43 -0000 1.12 --- wastescan.py 21 Feb 2003 22:11:45 -0000 1.13 *************** *** 20,24 **** input = WASTEDIR + "WASTE.h" output = SHORT + "gen.py" ! defsoutput = TOOLBOXDIR + "WASTEconst.py" scanner = MyScanner(input, output, defsoutput) scanner.scan() --- 20,24 ---- input = WASTEDIR + "WASTE.h" output = SHORT + "gen.py" ! defsoutput = os.path.join(os.path.split(TOOLBOXDIR)[0], "WASTEconst.py") scanner = MyScanner(input, output, defsoutput) scanner.scan() From gvanrossum@users.sourceforge.net Fri Feb 21 22:20:35 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:20:35 -0800 Subject: [Python-checkins] python/dist/src/Lib copy_reg.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv12473 Modified Files: copy_reg.py Log Message: Remove _reduce_2, it's now implemented in C. Index: copy_reg.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy_reg.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** copy_reg.py 19 Feb 2003 01:58:53 -0000 1.23 --- copy_reg.py 21 Feb 2003 22:20:31 -0000 1.24 *************** *** 46,50 **** _HEAPTYPE = 1<<9 ! def _reduce(self): for base in self.__class__.__mro__: if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: --- 46,53 ---- _HEAPTYPE = 1<<9 ! # Python code for object.__reduce_ex__ for protocols 0 and 1 ! ! def _reduce_ex(self, proto): ! assert proto < 2 for base in self.__class__.__mro__: if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE: *************** *** 76,123 **** return _reconstructor, args ! # A better version of _reduce, used by copy and pickle protocol 2 def __newobj__(cls, *args): return cls.__new__(cls, *args) - - def _reduce_2(obj): - cls = obj.__class__ - getnewargs = getattr(obj, "__getnewargs__", None) - if getnewargs: - args = getnewargs() - else: - args = () - getstate = getattr(obj, "__getstate__", None) - if getstate: - state = getstate() - else: - state = getattr(obj, "__dict__", None) - names = _slotnames(cls) - if names: - slots = {} - nil = [] - for name in names: - value = getattr(obj, name, nil) - if value is not nil: - slots[name] = value - if slots: - state = (state, slots) - listitems = dictitems = None - if isinstance(obj, list): - listitems = iter(obj) - elif isinstance(obj, dict): - dictitems = obj.iteritems() - return __newobj__, (cls,) + args, state, listitems, dictitems - - # Extended reduce: - - def _reduce_ex(obj, proto=0): - obj_reduce = getattr(obj, "__reduce__", None) - if obj_reduce and obj.__class__.__reduce__ is not object.__reduce__: - return obj_reduce() - elif proto < 2: - return _reduce(obj) - else: - return _reduce_2(obj) def _slotnames(cls): --- 79,86 ---- return _reconstructor, args ! # Helper for __reduce_ex__ protocol 2 def __newobj__(cls, *args): return cls.__new__(cls, *args) def _slotnames(cls): From jackjansen@users.sourceforge.net Fri Feb 21 22:29:48 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:29:48 -0800 Subject: [Python-checkins] python/dist/src/Lib/logging __init__.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/logging In directory sc8-pr-cvs1:/tmp/cvs-serv15930/Lib/logging Modified Files: __init__.py Log Message: getpid doesn't exist on MacOS9. Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/__init__.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** __init__.py 18 Feb 2003 14:20:06 -0000 1.5 --- __init__.py 21 Feb 2003 22:29:45 -0000 1.6 *************** *** 214,218 **** else: self.thread = None ! self.process = os.getpid() def __str__(self): --- 214,221 ---- else: self.thread = None ! if hasattr(os, 'getpid'): ! self.process = os.getpid() ! else: ! self.process = None def __str__(self): From jackjansen@users.sourceforge.net Fri Feb 21 22:33:57 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:33:57 -0800 Subject: [Python-checkins] python/dist/src/Mac/mwerks mwerks_pyexpat_config.h,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/mwerks In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/mwerks Added Files: mwerks_pyexpat_config.h Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. From jackjansen@users.sourceforge.net Fri Feb 21 22:33:58 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:33:58 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts genpluginprojects.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/scripts Modified Files: genpluginprojects.py Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: genpluginprojects.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/genpluginprojects.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** genpluginprojects.py 8 Jan 2003 16:27:44 -0000 1.39 --- genpluginprojects.py 21 Feb 2003 22:33:55 -0000 1.40 *************** *** 102,106 **** sources=["pyexpat.c", "xmlparse.c", "xmlrole.c", "xmltok.c"], extradirs=[":::Modules:expat"], ! prefixname="mwerks_shcarbon_config.h" ) genpluginproject("carbon", "zlib", --- 102,106 ---- sources=["pyexpat.c", "xmlparse.c", "xmlrole.c", "xmltok.c"], extradirs=[":::Modules:expat"], ! prefixname="mwerks_pyexpat_config.h" ) genpluginproject("carbon", "zlib", From jackjansen@users.sourceforge.net Fri Feb 21 22:34:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.128,1.129 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Lib/test Modified Files: regrtest.py Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.128 retrieving revision 1.129 diff -C2 -d -r1.128 -r1.129 *** regrtest.py 19 Feb 2003 02:35:05 -0000 1.128 --- regrtest.py 21 Feb 2003 22:33:35 -0000 1.129 *************** *** 634,637 **** --- 634,638 ---- test_popen test_popen2 + test_posix test_pty test_pwd From jackjansen@users.sourceforge.net Fri Feb 21 22:34:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:09 -0800 Subject: [Python-checkins] python/dist/src/Mac ReadMe,1.46,1.47 _checkversion.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Mac In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac Modified Files: ReadMe _checkversion.py Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: ReadMe =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/ReadMe,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** ReadMe 8 Jan 2003 16:27:29 -0000 1.46 --- ReadMe 21 Feb 2003 22:33:37 -0000 1.47 *************** *** 1,3 **** ! How to install MacPython-OS9 2.3a1 on your Macintosh ---------------------------------------------------- --- 1,3 ---- ! How to install MacPython-OS9 2.3a2 on your Macintosh ---------------------------------------------------- *************** *** 19,23 **** only modules that are not shared with MacPython-OSX 2.3. - macfs is now a pure Python wrapper module around various modules in the ! Carbon package. For 2.3a1 only this wrapping is incomplete: fsspec.SetDates() does not work yet. If you encounter any other problems please report them. --- 19,23 ---- only modules that are not shared with MacPython-OSX 2.3. - macfs is now a pure Python wrapper module around various modules in the ! Carbon package. For 2.3a2 only this wrapping is incomplete: fsspec.SetDates() does not work yet. If you encounter any other problems please report them. *************** *** 76,83 **** Python and "import test.regrtest ; test.regrtest.main()". ! test_httplib fails with an unexpected output error, ! this problem is being investigated. ! test_socket fails, this problem is being investigated. Three tests will fail on MacOS9 with MemoryErrors: --- 76,82 ---- Python and "import test.regrtest ; test.regrtest.main()". ! test_socket and test_logging fail, this problem is being investigated. ! test_tarfile fails, this problem is being investigated. Three tests will fail on MacOS9 with MemoryErrors: *************** *** 125,129 **** Up to three items are installed in the MacOS 8 or 9 system folder: the interpreter shared library PythonCore lives in the Extensions ! folder and the "Python 2.3a1 Preferences" file in the Python subfolder in the Preferences folder. All the rest of Python lives in the folder you installed in. --- 124,128 ---- Up to three items are installed in the MacOS 8 or 9 system folder: the interpreter shared library PythonCore lives in the Extensions ! folder and the "Python 2.3a2 Preferences" file in the Python subfolder in the Preferences folder. All the rest of Python lives in the folder you installed in. *************** *** 169,175 **** are lost and you have to set them again. ! After you are satisfied that 2.3a1 works as expected you can trash anything in the system folder that has "python" in the name and not ! "2.3a1". The ConfigurePython applet will try to detect incompatible --- 168,174 ---- are lost and you have to set them again. ! After you are satisfied that 2.3a2 works as expected you can trash anything in the system folder that has "python" in the name and not ! "2.3a2". The ConfigurePython applet will try to detect incompatible Index: _checkversion.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/_checkversion.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _checkversion.py 27 Dec 2001 23:01:17 -0000 1.12 --- _checkversion.py 21 Feb 2003 22:33:37 -0000 1.13 *************** *** 6,10 **** _PACKAGE="MacPython" ! _VERSION="2.2" _URL="http://www.cwi.nl/~jack/macpythonversion.txt" --- 6,10 ---- _PACKAGE="MacPython" ! _VERSION="2.3a2" _URL="http://www.cwi.nl/~jack/macpythonversion.txt" From jackjansen@users.sourceforge.net Fri Feb 21 22:34:20 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:20 -0800 Subject: [Python-checkins] python/dist/src/Mac/Distributions dev.include,1.28,1.29 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Distributions In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/Distributions Modified Files: dev.include Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: dev.include =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Distributions/dev.include,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** dev.include 8 Jan 2003 16:27:38 -0000 1.28 --- dev.include 21 Feb 2003 22:33:47 -0000 1.29 *************** *** 95,98 **** --- 95,101 ---- (':Mac:Build:_AH.carbon.mcp.exp', None) (':Mac:Build:_AH.carbon.mcp.xml', None) + (':Mac:Build:_Alias.carbon.mcp', None) + (':Mac:Build:_Alias.carbon.mcp.exp', None) + (':Mac:Build:_Alias.carbon.mcp.xml', None) (':Mac:Build:_App.carbon.mcp', None) (':Mac:Build:_App.carbon.mcp.exp', None) *************** *** 140,143 **** --- 143,149 ---- (':Mac:Build:_Evt.mcp.exp', None) (':Mac:Build:_Evt.mcp.xml', None) + (':Mac:Build:_File.carbon.mcp', None) + (':Mac:Build:_File.carbon.mcp.exp', None) + (':Mac:Build:_File.carbon.mcp.xml', None) (':Mac:Build:_Fm.carbon.mcp', None) (':Mac:Build:_Fm.carbon.mcp.exp', None) *************** *** 146,149 **** --- 152,158 ---- (':Mac:Build:_Fm.mcp.exp', None) (':Mac:Build:_Fm.mcp.xml', None) + (':Mac:Build:_Folder.carbon.mcp', None) + (':Mac:Build:_Folder.carbon.mcp.exp', None) + (':Mac:Build:_Folder.carbon.mcp.xml', None) (':Mac:Build:_Help.carbon.mcp', None) (':Mac:Build:_Help.carbon.mcp.exp', None) *************** *** 270,273 **** --- 279,285 ---- (':Mac:Build:ctb.mcp.exp', None) (':Mac:Build:ctb.mcp.xml', None) + (':Mac:Build:datetime.carbon.mcp', None) + (':Mac:Build:datetime.carbon.mcp.exp', None) + (':Mac:Build:datetime.carbon.mcp.xml', None) (':Mac:Build:gdbm.carbon.mcp', None) (':Mac:Build:gdbm.carbon.mcp.exp', None) *************** *** 437,440 **** --- 449,453 ---- (':Modules:Setup.in', None) (':Modules:Setup.thread.in', None) + (':Modules:_bsddb.c', None) (':Modules:_codecsmodule.c', None) (':Modules:_curses_panel.c', None) *************** *** 442,445 **** --- 455,459 ---- (':Modules:_hotshot.c', None) (':Modules:_localemodule.c', None) + (':Modules:_randommodule.c', None) (':Modules:_sre.c', None) (':Modules:_ssl.c', None) *************** *** 454,457 **** --- 468,472 ---- (':Modules:binascii.c', None) (':Modules:bsddbmodule.c', None) + (':Modules:bz2module.c', None) (':Modules:cPickle.c', None) (':Modules:cStringIO.c', None) *************** *** 467,470 **** --- 482,486 ---- (':Modules:cstubs', None) (':Modules:cursesmodule.c', None) + (':Modules:datetimemodule.c', None) (':Modules:dbmmodule.c', None) (':Modules:dlmodule.c', None) *************** *** 501,504 **** --- 517,521 ---- (':Modules:nismodule.c', None) (':Modules:operator.c', None) + (':Modules:ossaudiodev.c', None) (':Modules:parsermodule.c', None) (':Modules:pcre-int.h', None) *************** *** 554,557 **** --- 571,575 ---- (':Modules:yuv.h', None) (':Modules:yuvconvert.c', None) + (':Modules:zipimport.c', None) (':Modules:zlibmodule.c', None) (':Modules:zlibmodule.c~0', None) *************** *** 612,631 **** (':setup.py', None) (':site-packages', None) ! (':Mac:Build:_Folder.carbon.mcp.xml', None) ! (':Mac:Build:_Folder.carbon.mcp.exp', None) ! (':Mac:Build:_Folder.carbon.mcp', None) ! (':Mac:Build:_File.carbon.mcp.xml', None) ! (':Mac:Build:_File.carbon.mcp.exp', None) ! (':Mac:Build:_File.carbon.mcp', None) ! (':Mac:Build:_Alias.carbon.mcp.xml', None) ! (':Mac:Build:_Alias.carbon.mcp.exp', None) ! (':Mac:Build:_Alias.carbon.mcp', None) ! (':Modules:zipimport.c', None) ! (':Modules:ossaudiodev.c', None) ! (':Modules:datetimemodule.c', None) ! (':Modules:bz2module.c', None) ! (':Modules:_randommodule.c', None) ! (':Modules:_bsddb.c', None) ! (':Mac:Build:datetime.carbon.mcp.xml', None) ! (':Mac:Build:datetime.carbon.mcp.exp', None) ! (':Mac:Build:datetime.carbon.mcp', None) --- 630,634 ---- (':setup.py', None) (':site-packages', None) ! (':Modules:itertoolsmodule.c', None) ! (':Modules:_iconv_codec.c', None) ! (':Mac:mwerks:mwerks_pyexpat_config.h', None) From jackjansen@users.sourceforge.net Fri Feb 21 22:34:21 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:21 -0800 Subject: [Python-checkins] python/dist/src/Mac/Build PythonCore.mcp,1.43,1.44 PythonInterpreter.mcp,1.22,1.23 PythonStandSmall.mcp,1.49,1.50 _CG.carbon.mcp,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Build In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/Build Modified Files: PythonCore.mcp PythonInterpreter.mcp PythonStandSmall.mcp _CG.carbon.mcp Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: PythonCore.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonCore.mcp,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 Binary files /tmp/cvs6MYTXE and /tmp/cvsOWRNob differ Index: PythonInterpreter.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonInterpreter.mcp,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 Binary files /tmp/cvscVX8lV and /tmp/cvsKmZroI differ Index: PythonStandSmall.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/PythonStandSmall.mcp,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 Binary files /tmp/cvsO701K2 and /tmp/cvscTNo8V differ Index: _CG.carbon.mcp =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Build/_CG.carbon.mcp,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 Binary files /tmp/cvsyPKeEc and /tmp/cvsUTu1fh differ From jackjansen@users.sourceforge.net Fri Feb 21 22:34:25 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:25 -0800 Subject: [Python-checkins] python/dist/src/Mac/Include macbuildno.h,1.26,1.27 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Include In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/Include Modified Files: macbuildno.h Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: macbuildno.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Include/macbuildno.h,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** macbuildno.h 8 Jan 2003 16:27:40 -0000 1.26 --- macbuildno.h 21 Feb 2003 22:33:52 -0000 1.27 *************** *** 1 **** ! #define BUILD 148 --- 1 ---- ! #define BUILD 154 From jackjansen@users.sourceforge.net Fri Feb 21 22:34:25 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:25 -0800 Subject: [Python-checkins] python/dist/src/Mac/Distributions/(vise) Python 2.3.vct,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Distributions/(vise) In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/Distributions/(vise) Modified Files: Python 2.3.vct Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: Python 2.3.vct =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Distributions/(vise)/Python 2.3.vct,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 Binary files /tmp/cvsvibDlq and /tmp/cvsUeJocM differ From jackjansen@users.sourceforge.net Fri Feb 21 22:34:25 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 14:34:25 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyEdit.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv16366/Mac/Tools/IDE Modified Files: PyEdit.py Log Message: Checking mac-specific stuff from the 2.3a2 branch in on the trunk. Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** PyEdit.py 16 Feb 2003 21:28:51 -0000 1.37 --- PyEdit.py 21 Feb 2003 22:33:52 -0000 1.38 *************** *** 472,476 **** pass template = buildtools.findtemplate() ! buildtools.process(template, filename, destname, rsrcname=rsrcname, progress=None) try: os.remove(filename) --- 472,476 ---- pass template = buildtools.findtemplate() ! buildtools.process(template, filename, destname, 1, rsrcname=rsrcname, progress=None) try: os.remove(filename) From jackjansen@users.sourceforge.net Fri Feb 21 23:14:34 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 15:14:34 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac findertools.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv3780 Modified Files: findertools.py Log Message: Get rid of macfs. Index: findertools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/findertools.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** findertools.py 21 Jan 2003 15:30:21 -0000 1.2 --- findertools.py 21 Feb 2003 23:14:30 -0000 1.3 *************** *** 20,24 **** import MacOS import sys ! import macfs import aetypes from types import * --- 20,25 ---- import MacOS import sys ! import Carbon.File ! import Carbon.Folder import aetypes from types import * *************** *** 41,45 **** """Open a file thru the finder. Specify file by name or fsspec""" finder = _getfinder() ! fss = macfs.FSSpec(file) return finder.open(fss) --- 42,46 ---- """Open a file thru the finder. Specify file by name or fsspec""" finder = _getfinder() ! fss = Carbon.File.FSSpec(file) return finder.open(fss) *************** *** 47,51 **** """Print a file thru the finder. Specify file by name or fsspec""" finder = _getfinder() ! fss = macfs.FSSpec(file) return finder._print(fss) --- 48,52 ---- """Print a file thru the finder. Specify file by name or fsspec""" finder = _getfinder() ! fss = Carbon.File.FSSpec(file) return finder._print(fss) *************** *** 56,63 **** src_fss = [] for s in src: ! src_fss.append(macfs.FSSpec(s)) else: ! src_fss = macfs.FSSpec(src) ! dst_fss = macfs.FSSpec(dstdir) return finder.duplicate(src_fss, to=dst_fss) --- 57,64 ---- src_fss = [] for s in src: ! src_fss.append(Carbon.File.FSSpec(s)) else: ! src_fss = Carbon.File.FSSpec(src) ! dst_fss = Carbon.File.FSSpec(dstdir) return finder.duplicate(src_fss, to=dst_fss) *************** *** 68,75 **** src_fss = [] for s in src: ! src_fss.append(macfs.FSSpec(s)) else: ! src_fss = macfs.FSSpec(src) ! dst_fss = macfs.FSSpec(dstdir) return finder.move(src_fss, to=dst_fss) --- 69,76 ---- src_fss = [] for s in src: ! src_fss.append(Carbon.File.FSSpec(s)) else: ! src_fss = Carbon.File.FSSpec(src) ! dst_fss = Carbon.File.FSSpec(dstdir) return finder.move(src_fss, to=dst_fss) *************** *** 95,117 **** def reveal(file): ! """Reveal a file in the finder. Specify file by name or fsspec.""" finder = _getfinder() ! fss = macfs.FSSpec(file) ! file_alias = fss.NewAlias() return finder.reveal(file_alias) def select(file): ! """select a file in the finder. Specify file by name or fsspec.""" finder = _getfinder() ! fss = macfs.FSSpec(file) ! file_alias = fss.NewAlias() return finder.select(file_alias) def update(file): """Update the display of the specified object(s) to match ! their on-disk representation. Specify file by name or fsspec.""" finder = _getfinder() ! fss = macfs.FSSpec(file) ! file_alias = fss.NewAlias() return finder.update(file_alias) --- 96,118 ---- def reveal(file): ! """Reveal a file in the finder. Specify file by name, fsref or fsspec.""" finder = _getfinder() ! fsr = Carbon.File.FSRef(file) ! file_alias = fsr.FSNewAliasMinimal() return finder.reveal(file_alias) def select(file): ! """select a file in the finder. Specify file by name, fsref or fsspec.""" finder = _getfinder() ! fsr = Carbon.File.FSRef(file) ! file_alias = fsr.FSNewAliasMinimal() return finder.select(file_alias) def update(file): """Update the display of the specified object(s) to match ! their on-disk representation. Specify file by name, fsref or fsspec.""" finder = _getfinder() ! fsr = Carbon.File.FSRef(file) ! file_alias = fsr.FSNewAliasMinimal() return finder.update(file_alias) *************** *** 123,129 **** def comment(object, comment=None): """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" ! object = macfs.FSSpec(object) ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() if comment == None: return _getcomment(object_alias) --- 124,129 ---- def comment(object, comment=None): """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" ! object = Carbon.File.FSRef(object) ! object_alias = object.FSNewAliasMonimal() if comment == None: return _getcomment(object_alias) *************** *** 261,267 **** """Open a Finder window for object, Specify object by name or fsspec.""" finder = _getfinder() ! object = macfs.FSSpec(object) ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() args = {} attrs = {} --- 261,266 ---- """Open a Finder window for object, Specify object by name or fsspec.""" finder = _getfinder() ! object = Carbon.File.FSRef(object) ! object_alias = object.FSNewAliasMinimal() args = {} attrs = {} *************** *** 277,282 **** """Close a Finder window for folder, Specify by path.""" finder = _getfinder() ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() args = {} attrs = {} --- 276,281 ---- """Close a Finder window for folder, Specify by path.""" finder = _getfinder() ! object = Carbon.File.FSRef(object) ! object_alias = object.FSNewAliasMinimal() args = {} attrs = {} *************** *** 292,297 **** """Set the position of a Finder window for folder to pos=(w, h). Specify file by name or fsspec. If pos=None, location will return the current position of the object.""" ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() if not pos: return _getlocation(object_alias) --- 291,296 ---- """Set the position of a Finder window for folder to pos=(w, h). Specify file by name or fsspec. If pos=None, location will return the current position of the object.""" ! object = Carbon.File.FSRef(object) ! object_alias = object.FSNewAliasMinimal() if not pos: return _getlocation(object_alias) *************** *** 329,334 **** def label(object, index=None): """label: set or get the label of the item. Specify file by name or fsspec.""" ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() if index == None: return _getlabel(object_alias) --- 328,333 ---- def label(object, index=None): """label: set or get the label of the item. Specify file by name or fsspec.""" ! object = Carbon.File.FSRef(object) ! object_alias = object.FSNewAliasMinimal() if index == None: return _getlabel(object_alias) *************** *** 375,380 **** 2 = by button """ ! fss = macfs.FSSpec(folder) ! folder_alias = fss.NewAlias() if view == None: return _getwindowview(folder_alias) --- 374,379 ---- 2 = by button """ ! fsr = Carbon.File.FSRef(folder) ! folder_alias = fsr.FSNewAliasMinimal() if view == None: return _getwindowview(folder_alias) *************** *** 433,439 **** Specify file by name or fsspec. """ ! fss = macfs.FSSpec(folder) ! folder_alias = fss.NewAlias() ! openwindow(fss) if not size: return _getwindowsize(folder_alias) --- 432,438 ---- Specify file by name or fsspec. """ ! fsr = Carbon.File.FSRef(folder) ! folder_alias = fsr.FSNewAliasMinimal() ! openwindow(fsr) if not size: return _getwindowsize(folder_alias) *************** *** 481,487 **** def windowposition(folder, pos=None): """Set the position of a Finder window for folder to pos=(w, h).""" ! fss = macfs.FSSpec(folder) ! folder_alias = fss.NewAlias() ! openwindow(fss) if not pos: return _getwindowposition(folder_alias) --- 480,486 ---- def windowposition(folder, pos=None): """Set the position of a Finder window for folder to pos=(w, h).""" ! fsr = Carbon.File.FSRef(folder) ! folder_alias = fsr.FSNewAliasMinimal() ! openwindow(fsr) if not pos: return _getwindowposition(folder_alias) *************** *** 533,538 **** If left untouched, this data can be used to paste the icon on another file. Development opportunity: get and set the data as PICT.""" ! fss = macfs.FSSpec(object) ! object_alias = fss.NewAlias() if icondata == None: return _geticon(object_alias) --- 532,537 ---- If left untouched, this data can be used to paste the icon on another file. Development opportunity: get and set the data as PICT.""" ! fsr = Carbon.File.FSRef(object) ! object_alias = fsr.FSNewAliasMinimal() if icondata == None: return _geticon(object_alias) *************** *** 680,685 **** def movetotrash(path): """move the object to the trash""" ! fss = macfs.FSSpec(path) ! trashfolder = macfs.FSSpec(macfs.FindFolder(fss.as_tuple()[0], 'trsh', 0) + ("",)).as_pathname() move(path, trashfolder) --- 679,684 ---- def movetotrash(path): """move the object to the trash""" ! fss = Carbon.File.FSSpec(path) ! trashfolder = Carbon.Folder.FSFindFolder(fss.as_tuple()[0], 'trsh', 0) move(path, trashfolder) *************** *** 696,704 **** def _test(): print 'Original findertools functionality test...' print 'Testing launch...' ! fss, ok = macfs.PromptGetFile('File to launch:') ! if ok: ! result = launch(fss) if result: print 'Result: ', result --- 695,704 ---- def _test(): + import EasyDialogs print 'Original findertools functionality test...' print 'Testing launch...' ! pathname = EasyDialogs.AskFileForOpen('File to launch:') ! if pathname: ! result = launch(pathname) if result: print 'Result: ', result *************** *** 706,712 **** sys.stdin.readline() print 'Testing print...' ! fss, ok = macfs.PromptGetFile('File to print:') ! if ok: ! result = Print(fss) if result: print 'Result: ', result --- 706,712 ---- sys.stdin.readline() print 'Testing print...' ! pathname = EasyDialogs.AskFileForOpen('File to print:') ! if pathname: ! result = Print(pathname) if result: print 'Result: ', result *************** *** 714,722 **** sys.stdin.readline() print 'Testing copy...' ! fss, ok = macfs.PromptGetFile('File to copy:') ! if ok: ! dfss, ok = macfs.GetDirectory() ! if ok: ! result = copy(fss, dfss) if result: print 'Result:', result --- 714,722 ---- sys.stdin.readline() print 'Testing copy...' ! pathname = EasyDialogs.AskFileForOpen('File to copy:') ! if pathname: ! destdir = EasyDialogs.AskFolder('Destination:') ! if destdir: ! result = copy(pathname, destdir) if result: print 'Result:', result *************** *** 724,737 **** sys.stdin.readline() print 'Testing move...' ! fss, ok = macfs.PromptGetFile('File to move:') ! if ok: ! dfss, ok = macfs.GetDirectory() ! if ok: ! result = move(fss, dfss) if result: print 'Result:', result print 'Press return-', sys.stdin.readline() - import EasyDialogs print 'Testing sleep...' if EasyDialogs.AskYesNoCancel('Sleep?') > 0: --- 724,736 ---- sys.stdin.readline() print 'Testing move...' ! pathname = EasyDialogs.AskFileForOpen('File to move:') ! if pathname: ! destdir = EasyDialogs.AskFolder('Destination:') ! if destdir: ! result = move(pathname, destdir) if result: print 'Result:', result print 'Press return-', sys.stdin.readline() print 'Testing sleep...' if EasyDialogs.AskYesNoCancel('Sleep?') > 0: *************** *** 773,777 **** # Finder's windows, file location, file attributes open("@findertoolstest", "w") ! f = macfs.FSSpec("@findertoolstest").as_pathname() reveal(f) # reveal this file in a Finder window select(f) # select this file --- 772,776 ---- # Finder's windows, file location, file attributes open("@findertoolstest", "w") ! f = "@findertoolstest" reveal(f) # reveal this file in a Finder window select(f) # select this file From jackjansen@users.sourceforge.net Fri Feb 21 23:18:51 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 21 Feb 2003 15:18:51 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac EasyDialogs.py,1.8,1.9 PixMapWrapper.py,1.1,1.2 ic.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv5370 Modified Files: EasyDialogs.py PixMapWrapper.py ic.py Log Message: Getting rid of macfs. Index: EasyDialogs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/EasyDialogs.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EasyDialogs.py 7 Feb 2003 15:45:40 -0000 1.8 --- EasyDialogs.py 21 Feb 2003 23:18:48 -0000 1.9 *************** *** 769,773 **** def test(): ! import time, macfs Message("Testing EasyDialogs.") --- 769,773 ---- def test(): ! import time Message("Testing EasyDialogs.") *************** *** 790,796 **** else: s = 'Anonymous' ! rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=macfs.FSSpec) Message("rv: %s"%rv) ! rv = AskFileForSave(wanted=macfs.FSSpec, savedFileName="%s.txt"%s) Message("rv.as_pathname: %s"%rv.as_pathname()) rv = AskFolder() --- 790,796 ---- else: s = 'Anonymous' ! rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=Carbon.File.FSSpec) Message("rv: %s"%rv) ! rv = AskFileForSave(wanted=Carbon.File.FSRef, savedFileName="%s.txt"%s) Message("rv.as_pathname: %s"%rv.as_pathname()) rv = AskFolder() Index: PixMapWrapper.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/PixMapWrapper.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PixMapWrapper.py 30 Dec 2002 22:04:20 -0000 1.1 --- PixMapWrapper.py 21 Feb 2003 23:18:48 -0000 1.2 *************** *** 205,213 **** def test(): import MacOS ! import macfs import Image ! fsspec, ok = macfs.PromptGetFile("Image File:") ! if not ok: return ! path = fsspec.as_pathname() pm = PixMapWrapper() pm.fromImage( Image.open(path) ) --- 205,212 ---- def test(): import MacOS ! import EasyDialogs import Image ! path = EasyDialogs.AskFileForOpen("Image File:") ! if not path: return pm = PixMapWrapper() pm.fromImage( Image.open(path) ) Index: ic.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/ic.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ic.py 5 Feb 2003 15:49:19 -0000 1.2 --- ic.py 21 Feb 2003 23:18:48 -0000 1.3 *************** *** 7,11 **** from Carbon import Res import Carbon.File - import macfs import macostools --- 7,10 ---- From mwh@users.sourceforge.net Sat Feb 22 13:07:56 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Sat, 22 Feb 2003 05:07:56 -0800 Subject: [Python-checkins] python/dist/src/Python traceback.c,2.39,2.40 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv20957a Modified Files: traceback.c Log Message: After the removal of SET_LINENO, PyCode_Addr2Line has always been called to find tb_lineno -- even if Py_OptimizeFlag is true. So don't call it again when printing the traceback. Index: traceback.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/traceback.c,v retrieving revision 2.39 retrieving revision 2.40 diff -C2 -d -r2.39 -r2.40 *** traceback.c 15 Aug 2002 14:59:02 -0000 2.39 --- traceback.c 22 Feb 2003 13:07:53 -0000 2.40 *************** *** 239,245 **** while (tb != NULL && err == 0) { if (depth <= limit) { - if (Py_OptimizeFlag) - tb->tb_lineno = PyCode_Addr2Line( - tb->tb_frame->f_code, tb->tb_lasti); err = tb_displayline(f, PyString_AsString( --- 239,242 ---- From rhettinger@users.sourceforge.net Sun Feb 23 04:40:10 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 22 Feb 2003 20:40:10 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libitertools.tex,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv23087/Doc/lib Modified Files: libitertools.tex Log Message: User requested changes to the itertools module. Subsumed times() into repeat(). Added cycle() and chain(). Index: libitertools.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libitertools.tex,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** libitertools.tex 21 Feb 2003 01:45:34 -0000 1.5 --- libitertools.tex 23 Feb 2003 04:40:07 -0000 1.6 *************** *** 34,53 **** computer equivalent of ``inventory''. ! Some tools were omitted from the module because they offered no ! advantage over their pure python counterparts or because their behavior ! was too surprising. ! ! For instance, SML provides a tool: \code{cycle(\var{seq})} which ! loops over the sequence elements and then starts again when the ! sequence is exhausted. The surprising behavior is the need for ! significant auxiliary storage (which is unusual for an iterator). ! If needed, the tool is readily constructible using pure Python. ! ! Other tools are being considered for inclusion in future versions of the ! module. For instance, the function ! \function{chain(\var{it0}, \var{it1}, ...)} would return elements from ! the first iterator until it was exhausted and then move on to each ! successive iterator. The module author welcomes suggestions for other ! basic building blocks. \begin{seealso} --- 34,39 ---- computer equivalent of ``inventory''. ! The module author welcomes suggestions for other basic building blocks ! to be added to future versions of the module. \begin{seealso} *************** *** 68,71 **** --- 54,71 ---- by functions or loops that truncate the stream. + \begin{funcdesc}{chain}{*iterables} + Make an iterator that returns elements from the first iterable until + it is exhausted, then proceeds to the next iterable, until all of the + iterables are exhausted. Used for treating consecutive sequences as + a single sequence. Equivalent to: + + \begin{verbatim} + def chain(*iterables): + for it in iterables: + for element in it: + yield element + \end{verbatim} + \end{funcdesc} + \begin{funcdesc}{count}{\optional{n}} Make an iterator that returns consecutive integers starting with \var{n}. *************** *** 86,89 **** --- 86,112 ---- \end{funcdesc} + \begin{funcdesc}{cycle}{iterable} + Make an iterator returning elements from the iterable and saving a + copy of each. When the iterable is exhausted, return elements from + the saved copy. Repeats indefinitely. Equivalent to: + + \begin{verbatim} + def cycle(iterable): + saved = [] + for element in iterable: + yield element + saved.append(element) + if len(saved) == 0: + return + while True: + for element in saved: + yield element + \end{verbatim} + + Note, this is the only member of the toolkit that may require + significant auxiliary storage (depending on the length of the + iterable. + \end{funcdesc} + \begin{funcdesc}{dropwhile}{predicate, iterable} Make an iterator that drops elements from the iterable as long as *************** *** 208,213 **** \end{funcdesc} ! \begin{funcdesc}{repeat}{object} Make an iterator that returns \var{object} over and over again. Used as argument to \function{imap()} for invariant parameters to the called function. Also used with \function{izip()} to create --- 231,237 ---- \end{funcdesc} ! \begin{funcdesc}{repeat}{object\optional{, times}} Make an iterator that returns \var{object} over and over again. + Runs indefinitely unless the \var{times} argument is specified. Used as argument to \function{imap()} for invariant parameters to the called function. Also used with \function{izip()} to create *************** *** 215,221 **** \begin{verbatim} ! def repeat(object): ! while True: ! yield object \end{verbatim} \end{funcdesc} --- 239,249 ---- \begin{verbatim} ! def repeat(object, times=None): ! if times is None: ! while True: ! yield object ! else: ! for i in xrange(times): ! yield object \end{verbatim} \end{funcdesc} *************** *** 254,271 **** \end{funcdesc} - \begin{funcdesc}{times}{n, \optional{object}} - Make an iterator that returns \var{object} \var{n} times. - \var{object} defaults to \code{None}. Used for looping a specific - number of times without creating a number object on each pass. - Equivalent to: - - \begin{verbatim} - def times(n, object=None): - if n<0 : raise ValueError - for i in xrange(n): - yield object - \end{verbatim} - \end{funcdesc} - \subsection{Examples \label{itertools-example}} --- 282,285 ---- *************** *** 275,284 **** \begin{verbatim} - >>> for i in times(3): - ... print "Hello" - ... - Hello - Hello - Hello >>> amounts = [120.15, 764.05, 823.14] --- 289,292 ---- *************** *** 343,346 **** --- 351,358 ---- ... "Returns True if pred(x) is False for every element in the iterable" ... return not nth(ifilter(pred, seq), 0) + + >>> def pairwise(seq): + ... "s -> (s0,s1), (s1,s2), (s2, s3), ..." + ... return izip(seq, islice(seq,1,len(seq))) \end{verbatim} From rhettinger@users.sourceforge.net Sun Feb 23 04:40:09 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 22 Feb 2003 20:40:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_itertools.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23087/Lib/test Modified Files: test_itertools.py Log Message: User requested changes to the itertools module. Subsumed times() into repeat(). Added cycle() and chain(). Index: test_itertools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_itertools.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_itertools.py 9 Feb 2003 06:40:58 -0000 1.4 --- test_itertools.py 23 Feb 2003 04:40:07 -0000 1.5 *************** *** 5,8 **** --- 5,11 ---- class TestBasicOps(unittest.TestCase): + def test_chain(self): + self.assertEqual(list(chain('abc', 'def')), list('abcdef')) + def test_count(self): self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) *************** *** 10,13 **** --- 13,20 ---- self.assertRaises(TypeError, count, 2, 3) + def test_cycle(self): + self.assertEqual(list(islice(cycle('abc'),10)), list('abcabcabca')) + self.assertEqual(list(cycle('')), []) + def test_ifilter(self): def isEven(x): *************** *** 36,46 **** self.assertEqual(zip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) self.assertRaises(TypeError, repeat) - def test_times(self): - self.assertEqual(list(times(3)), [None]*3) - self.assertEqual(list(times(3, True)), [True]*3) - self.assertRaises(ValueError, times, -1) - def test_imap(self): import operator --- 43,49 ---- self.assertEqual(zip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) + self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a']) self.assertRaises(TypeError, repeat) def test_imap(self): import operator *************** *** 95,104 **** libreftest = """ Doctest for examples in the library reference, libitertools.tex - >>> for i in times(3): - ... print "Hello" - ... - Hello - Hello - Hello >>> amounts = [120.15, 764.05, 823.14] --- 98,101 ---- *************** *** 154,157 **** --- 151,158 ---- ... "Returns True if pred(x) is False for every element in the iterable" ... return not nth(ifilter(pred, seq), 0) + + >>> def pairwise(seq): + ... "s -> (s0,s1), (s1,s2), (s2, s3), ..." + ... return izip(seq, islice(seq,1,len(seq))) """ From rhettinger@users.sourceforge.net Sun Feb 23 04:40:09 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 22 Feb 2003 20:40:09 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.673,1.674 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23087/Misc Modified Files: NEWS Log Message: User requested changes to the itertools module. Subsumed times() into repeat(). Added cycle() and chain(). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.673 retrieving revision 1.674 diff -C2 -d -r1.673 -r1.674 *** NEWS 20 Feb 2003 01:56:17 -0000 1.673 --- NEWS 23 Feb 2003 04:40:06 -0000 1.674 *************** *** 18,22 **** ----------------- ! TBD Library --- 18,24 ---- ----------------- ! - Made user requested changes to the itertools module. ! Subsumed the times() function into repeat(). ! Added chain() and cycle(). Library From rhettinger@users.sourceforge.net Sun Feb 23 04:40:09 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 22 Feb 2003 20:40:09 -0800 Subject: [Python-checkins] python/dist/src/Modules itertoolsmodule.c,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv23087/Modules Modified Files: itertoolsmodule.c Log Message: User requested changes to the itertools module. Subsumed times() into repeat(). Added cycle() and chain(). Index: itertoolsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/itertoolsmodule.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** itertoolsmodule.c 9 Feb 2003 17:18:42 -0000 1.5 --- itertoolsmodule.c 23 Feb 2003 04:40:07 -0000 1.6 *************** *** 8,11 **** --- 8,168 ---- */ + /* cycle object **********************************************************/ + + typedef struct { + PyObject_HEAD + PyObject *it; + PyObject *saved; + int firstpass; + } cycleobject; + + PyTypeObject cycle_type; + + static PyObject * + cycle_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *it; + PyObject *iterable; + PyObject *saved; + cycleobject *lz; + + if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + saved = PyList_New(0); + if (saved == NULL) { + Py_DECREF(it); + return NULL; + } + + /* create cycleobject structure */ + lz = (cycleobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + Py_DECREF(saved); + return NULL; + } + lz->it = it; + lz->saved = saved; + lz->firstpass = 0; + + return (PyObject *)lz; + } + + static void + cycle_dealloc(cycleobject *lz) + { + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->saved); + Py_XDECREF(lz->it); + lz->ob_type->tp_free(lz); + } + + static int + cycle_traverse(cycleobject *lz, visitproc visit, void *arg) + { + int err; + + if (lz->it) { + err = visit(lz->it, arg); + if (err) + return err; + } + if (lz->saved) { + err = visit(lz->saved, arg); + if (err) + return err; + } + return 0; + } + + static PyObject * + cycle_next(cycleobject *lz) + { + PyObject *item; + PyObject *it; + + while (1) { + item = PyIter_Next(lz->it); + if (item != NULL) { + if (!lz->firstpass) + PyList_Append(lz->saved, item); + return item; + } + if (PyList_Size(lz->saved) == 0) + return NULL; + it = PyObject_GetIter(lz->saved); + if (it == NULL) + return NULL; + Py_DECREF(lz->it); + lz->it = it; + lz->firstpass = 1; + } + } + + static PyObject * + cycle_getiter(PyObject *lz) + { + Py_INCREF(lz); + return lz; + } + + PyDoc_STRVAR(cycle_doc, + "cycle(iterable) --> cycle object\n\ + \n\ + Return elements from the iterable until it is exhausted.\n\ + Then repeat the sequence indefinitely."); + + PyTypeObject cycle_type = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "itertools.cycle", /* tp_name */ + sizeof(cycleobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cycle_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cycle_doc, /* tp_doc */ + (traverseproc)cycle_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)cycle_getiter, /* tp_iter */ + (iternextfunc)cycle_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + cycle_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ + }; + + /* dropwhile object **********************************************************/ *************** *** 827,863 **** ! /* times object ************************************************************/ typedef struct { PyObject_HEAD ! PyObject *obj; ! long cnt; ! } timesobject; ! PyTypeObject times_type; static PyObject * ! times_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! timesobject *lz; ! PyObject *obj = Py_None; ! long cnt; ! ! if (!PyArg_ParseTuple(args, "l|O:times", &cnt, &obj)) ! return NULL; ! if (cnt < 0) { ! PyErr_SetString(PyExc_ValueError, ! "count for times() cannot be negative."); return NULL; } ! /* create timesobject structure */ ! lz = (timesobject *)type->tp_alloc(type, 0); if (lz == NULL) return NULL; ! lz->cnt = cnt; ! Py_INCREF(obj); ! lz->obj = obj; return (PyObject *)lz; --- 984,1033 ---- ! /* chain object ************************************************************/ typedef struct { PyObject_HEAD ! long tuplesize; ! long iternum; /* which iterator is active */ ! PyObject *ittuple; /* tuple of iterators */ ! } chainobject; ! PyTypeObject chain_type; static PyObject * ! chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { ! chainobject *lz; ! int tuplesize = PySequence_Length(args); ! int i; ! PyObject *ittuple; ! /* obtain iterators */ ! assert(PyTuple_Check(args)); ! ittuple = PyTuple_New(tuplesize); ! if(ittuple == NULL) return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "chain argument #%d must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); } ! /* create chainobject structure */ ! lz = (chainobject *)type->tp_alloc(type, 0); if (lz == NULL) return NULL; ! ! lz->ittuple = ittuple; ! lz->iternum = 0; ! lz->tuplesize = tuplesize; return (PyObject *)lz; *************** *** 865,892 **** static void ! times_dealloc(timesobject *lz) { PyObject_GC_UnTrack(lz); ! Py_XDECREF(lz->obj); lz->ob_type->tp_free(lz); } static int ! times_traverse(timesobject *lz, visitproc visit, void *arg) { ! if (lz->obj) ! return visit(lz->obj, arg); return 0; } static PyObject * ! times_next(timesobject *lz) { ! PyObject *obj = lz->obj; ! if (lz->cnt > 0) { ! lz->cnt--; ! Py_INCREF(obj); ! return obj; } return NULL; --- 1035,1065 ---- static void ! chain_dealloc(chainobject *lz) { PyObject_GC_UnTrack(lz); ! Py_XDECREF(lz->ittuple); lz->ob_type->tp_free(lz); } static int ! chain_traverse(chainobject *lz, visitproc visit, void *arg) { ! if (lz->ittuple) ! return visit(lz->ittuple, arg); return 0; } static PyObject * ! chain_next(chainobject *lz) { ! PyObject *it; ! PyObject *item; ! while (lz->iternum < lz->tuplesize) { ! it = PyTuple_GET_ITEM(lz->ittuple, lz->iternum); ! item = PyIter_Next(it); ! if (item != NULL) ! return item; ! lz->iternum++; } return NULL; *************** *** 894,898 **** static PyObject * ! times_getiter(PyObject *lz) { Py_INCREF(lz); --- 1067,1071 ---- static PyObject * ! chain_getiter(PyObject *lz) { Py_INCREF(lz); *************** *** 900,917 **** } ! PyDoc_STRVAR(times_doc, ! "times(n [,obj]) --> times object\n\ \n\ ! Return a times object whose .next() method returns n consecutive\n\ ! instances of obj (default is None)."); ! PyTypeObject times_type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.times", /* tp_name */ ! sizeof(timesobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)times_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 1073,1091 ---- } ! PyDoc_STRVAR(chain_doc, ! "chain(*iterables) --> chain object\n\ \n\ ! Return a chain object whose .next() method returns elements from the\n\ ! first iterable until it is exhausted, then elements from the next\n\ ! iterable, until all of the iterables are exhausted."); ! PyTypeObject chain_type = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "itertools.chain", /* tp_name */ ! sizeof(chainobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ ! (destructor)chain_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ *************** *** 930,940 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! times_doc, /* tp_doc */ ! (traverseproc)times_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)times_getiter, /* tp_iter */ ! (iternextfunc)times_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ --- 1104,1114 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! chain_doc, /* tp_doc */ ! (traverseproc)chain_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ ! (getiterfunc)chain_getiter, /* tp_iter */ ! (iternextfunc)chain_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ *************** *** 947,951 **** 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! times_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; --- 1121,1125 ---- 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ ! chain_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; *************** *** 1545,1548 **** --- 1719,1723 ---- PyObject_HEAD PyObject *element; + long cnt; } repeatobject; *************** *** 1554,1559 **** repeatobject *ro; PyObject *element; ! if (!PyArg_UnpackTuple(args, "repeat", 1, 1, &element)) return NULL; --- 1729,1735 ---- repeatobject *ro; PyObject *element; + long cnt = -1; ! if (!PyArg_ParseTuple(args, "O|l:repeat", &element, &cnt)) return NULL; *************** *** 1563,1566 **** --- 1739,1743 ---- Py_INCREF(element); ro->element = element; + ro->cnt = cnt; return (PyObject *)ro; } *************** *** 1585,1588 **** --- 1762,1769 ---- repeat_next(repeatobject *ro) { + if (ro->cnt == 0) + return NULL; + if (ro->cnt > 0) + ro->cnt--; Py_INCREF(ro->element); return ro->element; *************** *** 1597,1601 **** PyDoc_STRVAR(repeat_doc, ! "repeat(element) -> create an iterator which returns the element endlessly."); PyTypeObject repeat_type = { --- 1778,1784 ---- PyDoc_STRVAR(repeat_doc, ! "repeat(element [,times]) -> create an iterator which returns the element\n\ ! for the specified number of times. If not specified, returns the element\n\ ! endlessly."); PyTypeObject repeat_type = { *************** *** 1652,1656 **** Infinite iterators:\n\ count([n]) --> n, n+1, n+2, ...\n\ ! repeat(elem) --> elem, elem, elem, ...\n\ \n\ Iterators terminating on the shortest input sequence:\n\ --- 1835,1840 ---- Infinite iterators:\n\ count([n]) --> n, n+1, n+2, ...\n\ ! cycle(p) --> p0, p1, ... plast, p0, p1, ...\n\ ! repeat(elem [,n]) --> elem, elem, elem, ... endlessly or upto n times\n\ \n\ Iterators terminating on the shortest input sequence:\n\ *************** *** 1662,1666 **** imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...\n\ starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...\n\ ! times(n, [obj]) --> obj, obj, ... for n times. obj defaults to None\n\ takewhile(pred, seq) --> seq[0], seq[1], until pred fails\n\ dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\ --- 1846,1850 ---- imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...\n\ starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...\n\ ! chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\ takewhile(pred, seq) --> seq[0], seq[1], until pred fails\n\ dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\ *************** *** 1675,1678 **** --- 1859,1863 ---- char *name; PyTypeObject *typelist[] = { + &cycle_type, &dropwhile_type, &takewhile_type, *************** *** 1680,1684 **** &starmap_type, &imap_type, ! ×_type, &ifilter_type, &ifilterfalse_type, --- 1865,1869 ---- &starmap_type, &imap_type, ! &chain_type, &ifilter_type, &ifilterfalse_type, *************** *** 1695,1700 **** return; name = strchr(typelist[i]->tp_name, '.') + 1; ! if (name == NULL) ! return; Py_INCREF(typelist[i]); PyModule_AddObject(m, name, (PyObject *)typelist[i]); --- 1880,1884 ---- return; name = strchr(typelist[i]->tp_name, '.') + 1; ! assert (name != NULL); Py_INCREF(typelist[i]); PyModule_AddObject(m, name, (PyObject *)typelist[i]); From nnorwitz@users.sourceforge.net Sun Feb 23 21:36:35 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 13:36:35 -0800 Subject: [Python-checkins] python/dist/src/Lib shutil.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv3934/Lib Modified Files: shutil.py Log Message: Fix SF bug #691276, shutil.copytree documentation bug Also use True/False instead of 1/0 for symlink flag. Index: shutil.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/shutil.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** shutil.py 24 Jan 2003 17:36:15 -0000 1.27 --- shutil.py 23 Feb 2003 21:36:32 -0000 1.28 *************** *** 84,92 **** ! def copytree(src, dst, symlinks=0): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. ! Error are reported to standard output. If the optional symlinks flag is true, symbolic links in the --- 84,92 ---- ! def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. ! If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the *************** *** 165,169 **** except OSError: if os.path.isdir(src): ! copytree(src, dst, symlinks=1) rmtree(src) else: --- 165,169 ---- except OSError: if os.path.isdir(src): ! copytree(src, dst, symlinks=True) rmtree(src) else: From nnorwitz@users.sourceforge.net Sun Feb 23 21:36:50 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 13:36:50 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libshutil.tex,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv4310/Doc/lib Modified Files: libshutil.tex Log Message: Fix SF bug #691276, shutil.copytree documentation bug Index: libshutil.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libshutil.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** libshutil.tex 24 Jan 2003 17:33:30 -0000 1.12 --- libshutil.tex 23 Feb 2003 21:36:47 -0000 1.13 *************** *** 70,77 **** the source tree are represented as symbolic links in the new tree; if false or omitted, the contents of the linked files are copied to ! the new tree. Errors are reported to standard output. The source code for this should be considered an example rather than a tool. \end{funcdesc} --- 70,80 ---- the source tree are represented as symbolic links in the new tree; if false or omitted, the contents of the linked files are copied to ! the new tree. If exception(s) occur, an Error is raised ! with a list of reasons. The source code for this should be considered an example rather than a tool. + \versionchanged[Error is raised if any exceptions occur during copying, + rather than printing a message]{2.3} \end{funcdesc} From nnorwitz@users.sourceforge.net Sun Feb 23 21:45:46 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 13:45:46 -0800 Subject: [Python-checkins] python/dist/src/Python bltinmodule.c,2.281,2.282 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv7632/Python Modified Files: bltinmodule.c Log Message: Fix SF bug #690435, apply fails to check if warning raises exception (patch provided by Greg Chapman) Index: bltinmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/bltinmodule.c,v retrieving revision 2.281 retrieving revision 2.282 diff -C2 -d -r2.281 -r2.282 *** bltinmodule.c 13 Feb 2003 22:07:58 -0000 2.281 --- bltinmodule.c 23 Feb 2003 21:45:43 -0000 2.282 *************** *** 76,82 **** PyObject *t = NULL, *retval = NULL; ! PyErr_Warn(PyExc_PendingDeprecationWarning, ! "use func(*args, **kwargs) instead of " ! "apply(func, args, kwargs)"); if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict)) return NULL; --- 76,83 ---- PyObject *t = NULL, *retval = NULL; ! if (PyErr_Warn(PyExc_PendingDeprecationWarning, ! "use func(*args, **kwargs) instead of " ! "apply(func, args, kwargs)") < 0) ! return NULL; if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict)) return NULL; From nnorwitz@users.sourceforge.net Sun Feb 23 21:47:08 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 13:47:08 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.148,1.149 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv8310 Modified Files: setup.py Log Message: ossaudiodev has been building, so remove unnecessary pass and invalid comment Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.148 retrieving revision 1.149 diff -C2 -d -r1.148 -r1.149 *** setup.py 20 Feb 2003 02:52:04 -0000 1.148 --- setup.py 23 Feb 2003 21:47:05 -0000 1.149 *************** *** 744,749 **** if platform in ('linux2', 'freebsd4'): - # ossaudiodev currently doesn't work, so don't build. - pass exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) ) --- 744,747 ---- From nnorwitz@users.sourceforge.net Sun Feb 23 22:12:27 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 14:12:27 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_posix.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv18327/Lib/test Modified Files: test_posix.py Log Message: Fix SF bug #690081, test_posix fails when run in non-interactive mode Don't bother testing os.getlogin() if we aren't running from a tty (terminal) It fails when run without a tty (e.g., when run from cron). Index: test_posix.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_posix.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_posix.py 17 Feb 2003 22:40:31 -0000 1.3 --- test_posix.py 23 Feb 2003 22:12:24 -0000 1.4 *************** *** 30,37 **** # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", ! "times", "getlogin", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] for name in NO_ARG_FUNCTIONS: posix_func = getattr(posix, name, None) --- 30,44 ---- # no side-effects which we need to cleanup (e.g., fork, wait, abort) NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname", ! "times", "getloadavg", "tmpnam", "getegid", "geteuid", "getgid", "getgroups", "getpid", "getpgrp", "getppid", "getuid", ] + # getlogin() only works when run from a tty (terminal) + try: + if os.isatty(sys.stdin.fileno()): + NO_ARG_FUNCTIONS.append("getlogin") + except: + pass + for name in NO_ARG_FUNCTIONS: posix_func = getattr(posix, name, None) From jackjansen@users.sourceforge.net Sun Feb 23 22:57:00 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 23 Feb 2003 14:57:00 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.129,1.130 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv5761 Modified Files: regrtest.py Log Message: Expect to skip test_iconv_codecs on MacOSX. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.129 retrieving revision 1.130 diff -C2 -d -r1.129 -r1.130 *** regrtest.py 21 Feb 2003 22:33:35 -0000 1.129 --- regrtest.py 23 Feb 2003 22:56:58 -0000 1.130 *************** *** 771,774 **** --- 771,775 ---- test_gdbm test_gl + test_iconv_codecs test_imgfile test_largefile From jackjansen@users.sourceforge.net Sun Feb 23 22:59:06 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 23 Feb 2003 14:59:06 -0800 Subject: [Python-checkins] python/dist/src configure.in,1.389,1.390 configure,1.378,1.379 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv5935 Modified Files: configure.in configure Log Message: Disabled -prebind again when linking the interpreter on MacOSX. It caused a serious slowdown when loading dynamic modules that depend on large shared libraries or frameworks. Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.389 retrieving revision 1.390 diff -C2 -d -r1.389 -r1.390 *** configure.in 19 Feb 2003 15:25:07 -0000 1.389 --- configure.in 23 Feb 2003 22:59:00 -0000 1.390 *************** *** 1165,1173 **** # not used by the core itself but which needs to be in the core so # that dynamically loaded extension modules have access to it. ! # -prebind causes the executable to assume dynamic libraries are at their ! # preferred address, which speeds up startup. We specify it here ! # in stead of in LDFLAGS because it does not seem to work for bundle ! # plugins (as of OSX 10.2). ! LINKFORSHARED="$extra_undefs -framework System -prebind" if test "$enable_framework" then --- 1165,1172 ---- # not used by the core itself but which needs to be in the core so # that dynamically loaded extension modules have access to it. ! # -prebind is no longer used, because it actually seems to give a ! # slowdown in stead of a speedup, maybe due to the large number of ! # dynamic loads Python does. ! LINKFORSHARED="$extra_undefs -framework System" if test "$enable_framework" then Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.378 retrieving revision 1.379 diff -C2 -d -r1.378 -r1.379 *** configure 19 Feb 2003 15:24:41 -0000 1.378 --- configure 23 Feb 2003 22:59:01 -0000 1.379 *************** *** 9444,9452 **** # not used by the core itself but which needs to be in the core so # that dynamically loaded extension modules have access to it. ! # -prebind causes the executable to assume dynamic libraries are at their ! # preferred address, which speeds up startup. We specify it here ! # in stead of in LDFLAGS because it does not seem to work for bundle ! # plugins (as of OSX 10.2). ! LINKFORSHARED="$extra_undefs -framework System -prebind" if test "$enable_framework" then --- 9444,9451 ---- # not used by the core itself but which needs to be in the core so # that dynamically loaded extension modules have access to it. ! # -prebind is no longer used, because it actually seems to give a ! # slowdown in stead of a speedup, maybe due to the large number of ! # dynamic loads Python does. ! LINKFORSHARED="$extra_undefs -framework System" if test "$enable_framework" then From nnorwitz@users.sourceforge.net Sun Feb 23 23:11:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:11:43 -0800 Subject: [Python-checkins] python/dist/src/Objects longobject.c,1.155,1.156 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv10861/Objects Modified Files: longobject.c Log Message: Fix SF bug #689659, 64-bit int and long hash keys incompatible On a 64-bit machine, a dictionary could contain duplicate int/long keys if the value was > 2**32. Index: longobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/longobject.c,v retrieving revision 1.155 retrieving revision 1.156 diff -C2 -d -r1.155 -r1.156 *** longobject.c 3 Feb 2003 15:28:19 -0000 1.155 --- longobject.c 23 Feb 2003 23:11:40 -0000 1.156 *************** *** 1491,1499 **** i = -(i); } while (--i >= 0) { ! /* Force a 32-bit circular shift */ ! x = ((x << SHIFT) & ~MASK) | ((x >> (32-SHIFT)) & MASK); x += v->ob_digit[i]; } x = x * sign; if (x == -1) --- 1491,1501 ---- i = -(i); } + #define LONG_BIT_SHIFT (8*sizeof(long) - SHIFT) while (--i >= 0) { ! /* Force a native long #-bits (32 or 64) circular shift */ ! x = ((x << SHIFT) & ~MASK) | ((x >> LONG_BIT_SHIFT) & MASK); x += v->ob_digit[i]; } + #undef LONG_BIT_SHIFT x = x * sign; if (x == -1) From nnorwitz@users.sourceforge.net Sun Feb 23 23:11:44 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:11:44 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.674,1.675 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv10861/Misc Modified Files: NEWS Log Message: Fix SF bug #689659, 64-bit int and long hash keys incompatible On a 64-bit machine, a dictionary could contain duplicate int/long keys if the value was > 2**32. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.674 retrieving revision 1.675 diff -C2 -d -r1.674 -r1.675 *** NEWS 23 Feb 2003 04:40:06 -0000 1.674 --- NEWS 23 Feb 2003 23:11:41 -0000 1.675 *************** *** 13,17 **** ----------------- ! TBD Extension modules --- 13,18 ---- ----------------- ! - On 64-bit systems, a dictionary could contain duplicate long/int keys ! if the key value was larger than 2**32. See SF bug #689659. Extension modules From nnorwitz@users.sourceforge.net Sun Feb 23 23:11:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:11:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_types.py,1.45,1.46 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv10861/Lib/test Modified Files: test_types.py Log Message: Fix SF bug #689659, 64-bit int and long hash keys incompatible On a 64-bit machine, a dictionary could contain duplicate int/long keys if the value was > 2**32. Index: test_types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** test_types.py 7 Dec 2002 09:04:29 -0000 1.45 --- test_types.py 23 Feb 2003 23:11:41 -0000 1.46 *************** *** 640,643 **** --- 640,651 ---- else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty" + # verify longs/ints get same value when key > 32 bits (for 64-bit archs) + # see SF bug #689659 + x = 4503599627370496L + y = 4503599627370496 + h = {x: 'anything', y: 'something else'} + if h[x] != h[y]: + raise TestFailed, "long/int key should match" + d[1] = 1 try: From nnorwitz@users.sourceforge.net Sun Feb 23 23:15:29 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:15:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test string_tests.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12678/Lib/test Modified Files: string_tests.py Log Message: Get test to work on alpha Index: string_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/string_tests.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** string_tests.py 21 Feb 2003 12:53:49 -0000 1.27 --- string_tests.py 23 Feb 2003 23:15:26 -0000 1.28 *************** *** 505,509 **** self.checkraises(TypeError, 'abc', '__mul__') self.checkraises(TypeError, 'abc', '__mul__', '') ! self.checkraises(OverflowError, 10000*'abc', '__mul__', sys.maxint) def test_join(self): --- 505,509 ---- self.checkraises(TypeError, 'abc', '__mul__') self.checkraises(TypeError, 'abc', '__mul__', '') ! self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000) def test_join(self): From jackjansen@users.sourceforge.net Sun Feb 23 23:23:49 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:23:49 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules macosmodule.c,1.64,1.65 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv14326 Modified Files: macosmodule.c Log Message: Added a linkmodel attribute, showing how Python was built. This is so packages can check that extension modules are built for the right type of python. Current values can be static, framework, shared and cfm (for completeness, for MacPyton-OS9). Closes bug #691889. The reporter suggests backporting this to 2.2.3 and I think I agree. Index: macosmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/macosmodule.c,v retrieving revision 1.64 retrieving revision 1.65 diff -C2 -d -r1.64 -r1.65 *** macosmodule.c 21 Feb 2003 16:31:11 -0000 1.64 --- macosmodule.c 23 Feb 2003 23:23:47 -0000 1.65 *************** *** 765,768 **** --- 765,781 ---- Py_BuildValue("s", PY_RUNTIMEMODEL)) != 0) return; + #if !TARGET_API_MAC_OSX + #define PY_LINKMODEL "cfm" + #elif defined(WITH_NEXT_FRAMEWORK) + #define PY_LINKMODEL "framework" + #elif defined(Py_ENABLE_SHARED) + #define PY_LINKMODEL "shared" + #else + #define PY_LINKMODEL "static" + #endif + if (PyDict_SetItemString(d, "linkmodel", + Py_BuildValue("s", PY_LINKMODEL)) != 0) + return; + } From nnorwitz@users.sourceforge.net Sun Feb 23 23:28:19 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:28:19 -0800 Subject: [Python-checkins] python/dist/src configure,1.379,1.380 configure.in,1.390,1.391 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv16229 Modified Files: configure configure.in Log Message: Fix SF bug #691793, Python 2.3a2 build fails on Tru64 Need to make sure that preprocessor directives start in first column. This means we can't indent code which has preprocessor directives, nor have a space between [ #include for example. Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.379 retrieving revision 1.380 diff -C2 -d -r1.379 -r1.380 *** configure 23 Feb 2003 22:59:01 -0000 1.379 --- configure 23 Feb 2003 23:28:08 -0000 1.380 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.389 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.390 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 4747,4751 **** #line $LINENO "configure" #include "confdefs.h" ! #include #ifdef F77_DUMMY_MAIN # ifdef __cplusplus --- 4747,4751 ---- #line $LINENO "configure" #include "confdefs.h" ! #include #ifdef F77_DUMMY_MAIN # ifdef __cplusplus *************** *** 4787,4792 **** #include "confdefs.h" ! #define _OSF_SOURCE 1 ! #include #ifdef F77_DUMMY_MAIN --- 4787,4792 ---- #include "confdefs.h" ! #define _OSF_SOURCE 1 ! #include #ifdef F77_DUMMY_MAIN *************** *** 9160,9164 **** #include "confdefs.h" #include ! #include main() { --- 9160,9164 ---- #include "confdefs.h" #include ! #include main() { *************** *** 10129,10136 **** #line $LINENO "configure" #include "confdefs.h" #include ! #ifdef _POSIX_THREADS ! yes ! #endif _ACEOF --- 10129,10137 ---- #line $LINENO "configure" #include "confdefs.h" + #include ! #ifdef _POSIX_THREADS ! yes ! #endif _ACEOF *************** *** 13190,13200 **** #include "confdefs.h" ! #if defined(MAJOR_IN_MKDEV) ! #include ! #elif defined(MAJOR_IN_SYSMACROS) ! #include ! #else ! #include ! #endif #ifdef F77_DUMMY_MAIN --- 13191,13201 ---- #include "confdefs.h" ! #if defined(MAJOR_IN_MKDEV) ! #include ! #elif defined(MAJOR_IN_SYSMACROS) ! #include ! #else ! #include ! #endif #ifdef F77_DUMMY_MAIN Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.390 retrieving revision 1.391 diff -C2 -d -r1.390 -r1.391 *** configure.in 23 Feb 2003 22:59:00 -0000 1.390 --- configure.in 23 Feb 2003 23:28:15 -0000 1.391 *************** *** 764,768 **** # Check whether using makedev requires defining _OSF_SOURCE AC_MSG_CHECKING(for makedev) ! AC_TRY_LINK([ #include ], [ makedev(0, 0) ], ac_cv_has_makedev=yes, --- 764,768 ---- # Check whether using makedev requires defining _OSF_SOURCE AC_MSG_CHECKING(for makedev) ! AC_TRY_LINK([#include ], [ makedev(0, 0) ], ac_cv_has_makedev=yes, *************** *** 771,776 **** # we didn't link, try if _OSF_SOURCE will allow us to link AC_TRY_LINK([ ! #define _OSF_SOURCE 1 ! #include ], [ makedev(0, 0) ], --- 771,776 ---- # we didn't link, try if _OSF_SOURCE will allow us to link AC_TRY_LINK([ ! #define _OSF_SOURCE 1 ! #include ], [ makedev(0, 0) ], *************** *** 930,934 **** AC_CACHE_VAL(ac_cv_sizeof_pthread_t, [AC_TRY_RUN([#include ! #include main() { --- 930,934 ---- AC_CACHE_VAL(ac_cv_sizeof_pthread_t, [AC_TRY_RUN([#include ! #include main() { *************** *** 1358,1365 **** AC_MSG_CHECKING(for _POSIX_THREADS in unistd.h) AC_EGREP_CPP(yes, ! [#include ! #ifdef _POSIX_THREADS ! yes ! #endif ], unistd_defines_pthreads=yes, unistd_defines_pthreads=no) AC_MSG_RESULT($unistd_defines_pthreads) --- 1358,1366 ---- AC_MSG_CHECKING(for _POSIX_THREADS in unistd.h) AC_EGREP_CPP(yes, ! [ ! #include ! #ifdef _POSIX_THREADS ! yes ! #endif ], unistd_defines_pthreads=yes, unistd_defines_pthreads=no) AC_MSG_RESULT($unistd_defines_pthreads) *************** *** 1928,1938 **** AC_MSG_CHECKING(for major, minor, and makedev) AC_TRY_LINK([ ! #if defined(MAJOR_IN_MKDEV) ! #include ! #elif defined(MAJOR_IN_SYSMACROS) ! #include ! #else ! #include ! #endif ],[ makedev(major(0),minor(0)); --- 1929,1939 ---- AC_MSG_CHECKING(for major, minor, and makedev) AC_TRY_LINK([ ! #if defined(MAJOR_IN_MKDEV) ! #include ! #elif defined(MAJOR_IN_SYSMACROS) ! #include ! #else ! #include ! #endif ],[ makedev(major(0),minor(0)); From nnorwitz@users.sourceforge.net Sun Feb 23 23:34:40 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:34:40 -0800 Subject: [Python-checkins] python/dist/src configure,1.279.6.17,1.279.6.18 configure.in,1.288.6.17,1.288.6.18 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv19433 Modified Files: Tag: release22-maint configure configure.in Log Message: Backport relevant portions of: Fix SF bug #691793, Python 2.3a2 build fails on Tru64 Need to make sure that preprocessor directives start in first column. This means we can't indent code which has preprocessor directives, nor have a space between [ #include for example. Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.279.6.17 retrieving revision 1.279.6.18 diff -C2 -d -r1.279.6.17 -r1.279.6.18 *** configure 7 Feb 2003 15:54:27 -0000 1.279.6.17 --- configure 23 Feb 2003 23:34:32 -0000 1.279.6.18 *************** *** 1,5 **** #! /bin/sh ! # From configure.in Revision: 1.288.6.15 # Guess values for system-dependent variables and create Makefiles. --- 1,5 ---- #! /bin/sh ! # From configure.in Revision: 1.288.6.17 # Guess values for system-dependent variables and create Makefiles. *************** *** 2452,2461 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(int)); ! exit(0); } EOF --- 2452,2461 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(int)); ! return(0); } EOF *************** *** 2491,2500 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(long)); ! exit(0); } EOF --- 2491,2500 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(long)); ! return(0); } EOF *************** *** 2530,2539 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(void *)); ! exit(0); } EOF --- 2530,2539 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(void *)); ! return(0); } EOF *************** *** 2569,2578 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(char)); ! exit(0); } EOF --- 2569,2578 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(char)); ! return(0); } EOF *************** *** 2608,2617 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(short)); ! exit(0); } EOF --- 2608,2617 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(short)); ! return(0); } EOF *************** *** 2647,2656 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(float)); ! exit(0); } EOF --- 2647,2656 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(float)); ! return(0); } EOF *************** *** 2686,2695 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(double)); ! exit(0); } EOF --- 2686,2695 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(double)); ! return(0); } EOF *************** *** 2725,2734 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(fpos_t)); ! exit(0); } EOF --- 2725,2734 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(fpos_t)); ! return(0); } EOF *************** *** 2789,2798 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(long long)); ! exit(0); } EOF --- 2789,2798 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(long long)); ! return(0); } EOF *************** *** 2854,2863 **** #include "confdefs.h" #include ! main() { FILE *f=fopen("conftestval", "w"); ! if (!f) exit(1); fprintf(f, "%d\n", sizeof(uintptr_t)); ! exit(0); } EOF --- 2854,2863 ---- #include "confdefs.h" #include ! int main() { FILE *f=fopen("conftestval", "w"); ! if (!f) return(1); fprintf(f, "%d\n", sizeof(uintptr_t)); ! return(0); } EOF *************** *** 3023,3027 **** #include "confdefs.h" #include ! #include main() { --- 3023,3027 ---- #include "confdefs.h" #include ! #include main() { *************** *** 3715,3721 **** #include "confdefs.h" #include ! #ifdef _POSIX_THREADS ! yes ! #endif EOF --- 3715,3721 ---- #include "confdefs.h" #include ! #ifdef _POSIX_THREADS ! yes ! #endif EOF Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.288.6.17 retrieving revision 1.288.6.18 diff -C2 -d -r1.288.6.17 -r1.288.6.18 *** configure.in 7 Feb 2003 15:54:52 -0000 1.288.6.17 --- configure.in 23 Feb 2003 23:34:37 -0000 1.288.6.18 *************** *** 670,674 **** AC_CACHE_VAL(ac_cv_sizeof_pthread_t, [AC_TRY_RUN([#include ! #include main() { --- 670,674 ---- AC_CACHE_VAL(ac_cv_sizeof_pthread_t, [AC_TRY_RUN([#include ! #include main() { *************** *** 1060,1066 **** AC_EGREP_CPP(yes, [#include ! #ifdef _POSIX_THREADS ! yes ! #endif ], unistd_defines_pthreads=yes, unistd_defines_pthreads=no) AC_MSG_RESULT($unistd_defines_pthreads) --- 1060,1066 ---- AC_EGREP_CPP(yes, [#include ! #ifdef _POSIX_THREADS ! yes ! #endif ], unistd_defines_pthreads=yes, unistd_defines_pthreads=no) AC_MSG_RESULT($unistd_defines_pthreads) From nnorwitz@users.sourceforge.net Sun Feb 23 23:45:19 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:45:19 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.337.2.4.2.62,1.337.2.4.2.63 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23521/Misc Modified Files: Tag: release22-maint NEWS Log Message: Fix SF bug #691793, Python 2.3a2 build fails on Tru64 Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.337.2.4.2.62 retrieving revision 1.337.2.4.2.63 diff -C2 -d -r1.337.2.4.2.62 -r1.337.2.4.2.63 *** NEWS 19 Feb 2003 03:52:47 -0000 1.337.2.4.2.62 --- NEWS 23 Feb 2003 23:45:16 -0000 1.337.2.4.2.63 *************** *** 3,6 **** --- 3,9 ---- ============================ + - Fix problem building on OSF1 because the compiler only accepted + preprocessor directives that start in column 1. (SF bug #691793.) + - Fixed two places in PyObject_Generic{Get,Set}Attr() where the tp_descr_{get,set} slot of a descriptor's type was accessed without From nnorwitz@users.sourceforge.net Sun Feb 23 23:45:37 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 15:45:37 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.675,1.676 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv23596/Misc Modified Files: NEWS Log Message: Fix SF bug #691793, Python 2.3a2 build fails on Tru64 Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.675 retrieving revision 1.676 diff -C2 -d -r1.675 -r1.676 *** NEWS 23 Feb 2003 23:11:41 -0000 1.675 --- NEWS 23 Feb 2003 23:45:35 -0000 1.676 *************** *** 36,40 **** ----- ! TBD C API --- 36,41 ---- ----- ! - Fix problem building on OSF1 because the compiler only accepted ! preprocessor directives that start in column 1. (SF bug #691793.) C API From gvanrossum@users.sourceforge.net Mon Feb 24 01:09:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:09:56 -0800 Subject: [Python-checkins] python/dist/src/Misc/RPM python-2.3.spec,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Misc/RPM In directory sc8-pr-cvs1:/tmp/cvs-serv20471 Added Files: python-2.3.spec Log Message: RPM spec file for 2.3a2, contributed by Sean Reifschneider. --- NEW FILE: python-2.3.spec --- ########################## # User-modifiable configs ########################## # Is the resulting package and the installed binary named "python" or # "python2"? #WARNING: Commenting out doesn't work. Last line is what's used. %define config_binsuffix none %define config_binsuffix 2.3 # Build tkinter? "auto" enables it if /usr/bin/wish exists. #WARNING: Commenting out doesn't work. Last line is what's used. %define config_tkinter no %define config_tkinter yes %define config_tkinter auto # Use pymalloc? The last line (commented or not) determines wether # pymalloc is used. #WARNING: Commenting out doesn't work. Last line is what's used. %define config_pymalloc no %define config_pymalloc yes # Enable IPV6? #WARNING: Commenting out doesn't work. Last line is what's used. %define config_ipv6 yes %define config_ipv6 no ################################# # End of user-modifiable configs ################################# %define name python %define version 2.3a2 %define libvers 2.3 %define release 2 %define __prefix /usr # kludge to get around rpm define weirdness %define ipv6 %(if [ "%{config_ipv6}" = yes ]; then echo --enable-ipv6; else echo --disable-ipv6; fi) %define pymalloc %(if [ "%{config_pymalloc}" = yes ]; then echo --with-pymalloc; else echo --without-pymalloc; fi) %define binsuffix %(if [ "%{config_binsuffix}" = none ]; then echo ; else echo "%{config_binsuffix}"; fi) %define include_tkinter %(if [ \\( "%{config_tkinter}" = auto -a -f /usr/bin/wish \\) -o "%{config_tkinter}" = yes ]; then echo 1; else echo 0; fi) Summary: An interpreted, interactive, object-oriented programming language. Name: %{name}%{binsuffix} Version: %{version} Release: %{release} Copyright: Modified CNRI Open Source License Group: Development/Languages Source: Python-%{version}.tgz Source1: html-%{version}.tar.bz2 Patch0: Python-2.1-pythonpath.patch #Patch1: Python-2.1-expat.patch BuildRoot: /var/tmp/%{name}-%{version}-root BuildPrereq: expat-devel BuildPrereq: db4-devel BuildPrereq: gdbm-devel Prefix: %{__prefix} Packager: Sean Reifschneider %description Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many brands of UNIX, on PCs under Windows, MS-DOS, and OS/2, and on the Mac. %package devel Summary: The libraries and header files needed for Python extension development. Prereq: python%{binsuffix} = %{PACKAGE_VERSION} Group: Development/Libraries %description devel The Python programming language's interpreter can be extended with dynamically loaded extensions and can be embedded in other programs. This package contains the header files and libraries needed to do these types of tasks. Install python-devel if you want to develop Python extensions. The python package will also need to be installed. You'll probably also want to install the python-docs package, which contains Python documentation. %if %{include_tkinter} %package tkinter Summary: A graphical user interface for the Python scripting language. Group: Development/Languages Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} %description tkinter The Tkinter (Tk interface) program is an graphical user interface for the Python scripting language. You should install the tkinter package if you'd like to use a graphical user interface for Python programming. %endif %package tools Summary: A collection of development tools included with Python. Group: Development/Tools Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release} %description tools The Python package includes several development tools that are used to build python programs. This package contains a selection of those tools, including the IDLE Python IDE. Install python-tools if you want to use these tools to develop Python programs. You will also need to install the python and tkinter packages. %package docs Summary: Python-related documentation. Group: Development/Documentation %description docs Documentation relating to the Python programming language in HTML and info formats. %changelog * Mon Feb 17 2003 Sean Reifschneider [2.3a1-1] - Updating to 2.3 release. * Sun Dec 23 2001 Sean Reifschneider [Release 2.2-2] - Added -docs package. - Added "auto" config_tkinter setting which only enables tk if /usr/bin/wish exists. * Sat Dec 22 2001 Sean Reifschneider [Release 2.2-1] - Updated to 2.2. - Changed the extension to "2" from "2.2". * Tue Nov 18 2001 Sean Reifschneider [Release 2.2c1-1] - Updated to 2.2c1. * Thu Nov 1 2001 Sean Reifschneider [Release 2.2b1-3] - Changed the way the sed for fixing the #! in pydoc works. * Wed Oct 24 2001 Sean Reifschneider [Release 2.2b1-2] - Fixed missing "email" package, thanks to anonymous report on sourceforge. - Fixed missing "compiler" package. * Mon Oct 22 2001 Sean Reifschneider [Release 2.2b1-1] - Updated to 2.2b1. * Mon Oct 9 2001 Sean Reifschneider [Release 2.2a4-4] - otto@balinor.mat.unimi.it mentioned that the license file is missing. * Sun Sep 30 2001 Sean Reifschneider [Release 2.2a4-3] - Ignacio Vazquez-Abrams pointed out that I had a spruious double-quote in the spec files. Thanks. * Wed Jul 25 2001 Sean Reifschneider [Release 2.2a1-1] - Updated to 2.2a1 release. - Changed idle and pydoc to use binsuffix macro ####### # PREP ####### %prep %setup -n Python-%{version} %patch0 -p1 #%patch1 ######## # BUILD ######## %build ./configure %{ipv6} %{pymalloc} --prefix=%{__prefix} make ########## # INSTALL ########## %install # set the install path echo '[install_scripts]' >setup.cfg echo 'install_dir='"${RPM_BUILD_ROOT}/usr/bin" >>setup.cfg [ -d "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT mkdir -p $RPM_BUILD_ROOT%{__prefix}/lib/python%{libvers}/lib-dynload make prefix=$RPM_BUILD_ROOT%{__prefix} install # REPLACE PATH IN PYDOC if [ ! -z "%{binsuffix}" ] then ( cd $RPM_BUILD_ROOT%{__prefix}/bin mv pydoc pydoc.old sed 's|#!.*|#!/usr/bin/env python'%{binsuffix}'|' \ pydoc.old >pydoc chmod 755 pydoc rm -f pydoc.old ) fi # add the binsuffix if [ ! -z "%{binsuffix}" ] then ( cd $RPM_BUILD_ROOT%{__prefix}/bin; rm -f python[0-9a-zA-Z]*; mv -f python python"%{binsuffix}" ) ( cd $RPM_BUILD_ROOT%{__prefix}/man/man1; mv python.1 python%{binsuffix}.1 ) ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f pydoc pydoc"%{binsuffix}" ) ( cd $RPM_BUILD_ROOT%{__prefix}/bin; mv -f idle idle"%{binsuffix}" ) fi ######## # Tools echo '#!/bin/bash' >${RPM_BUILD_ROOT}%{_bindir}/idle%{binsuffix} echo 'exec %{_prefix}/bin/python%{binsuffix} /usr/lib/python%{libvers}/Tools/idle/idle.py' >>$RPM_BUILD_ROOT%{_bindir}/idle%{binsuffix} chmod 755 $RPM_BUILD_ROOT%{_bindir}/idle%{binsuffix} cp -a Tools $RPM_BUILD_ROOT%{_prefix}/lib/python%{libvers} # MAKE FILE LISTS rm -f mainpkg.files find "$RPM_BUILD_ROOT""%{__prefix}"/lib/python%{libvers}/lib-dynload -type f | sed "s|^${RPM_BUILD_ROOT}|/|" | grep -v -e '_tkinter.so$' >mainpkg.files find "$RPM_BUILD_ROOT""%{__prefix}"/bin -type f | sed "s|^${RPM_BUILD_ROOT}|/|" | grep -v -e '/bin/idle%{binsuffix}$' >>mainpkg.files rm -f tools.files find "$RPM_BUILD_ROOT""%{__prefix}"/lib/python%{libvers}/Tools -type f | sed "s|^${RPM_BUILD_ROOT}|/|" >tools.files echo "%{__prefix}"/bin/idle%{binsuffix} >>tools.files ###### # Docs mkdir -p "$RPM_BUILD_ROOT"/var/www/html/python ( cd "$RPM_BUILD_ROOT"/var/www/html/python bunzip2 < %{SOURCE1} | tar x ) ######## # CLEAN ######## %clean rm -fr $RPM_BUILD_ROOT rm -f mainpkg.files tools.files ######## # FILES ######## %files -f mainpkg.files %defattr(-,root,root) %doc Misc/README Misc/cheatsheet Misc/Porting %doc LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS %{__prefix}/man/man1/python%{binsuffix}.1.gz %dir %{__prefix}/include/python%{libvers} %dir %{__prefix}/lib/python%{libvers}/ %{__prefix}/lib/python%{libvers}/*.txt %{__prefix}/lib/python%{libvers}/*.py* %{__prefix}/lib/python%{libvers}/pdb.doc %{__prefix}/lib/python%{libvers}/profile.doc %{__prefix}/lib/python%{libvers}/curses %{__prefix}/lib/python%{libvers}/distutils %{__prefix}/lib/python%{libvers}/encodings %dir %{__prefix}/lib/python%{libvers}/lib-old %{__prefix}/lib/python%{libvers}/plat-linux2 %{__prefix}/lib/python%{libvers}/site-packages %{__prefix}/lib/python%{libvers}/test %{__prefix}/lib/python%{libvers}/xml %{__prefix}/lib/python%{libvers}/email %{__prefix}/lib/python%{libvers}/compiler %{__prefix}/lib/python%{libvers}/bsddb %{__prefix}/lib/python%{libvers}/hotshot %{__prefix}/lib/python%{libvers}/logging %{__prefix}/lib/python%{libvers}/lib-old %files devel %defattr(-,root,root) %{__prefix}/include/python%{libvers}/*.h %{__prefix}/lib/python%{libvers}/config %files -f tools.files tools %defattr(-,root,root) %if %{include_tkinter} %files tkinter %defattr(-,root,root) %{__prefix}/lib/python%{libvers}/lib-tk %{__prefix}/lib/python%{libvers}/lib-dynload/_tkinter.so* %endif %files docs %defattr(-,root,root) /var/www/html/python/* From gvanrossum@users.sourceforge.net Mon Feb 24 01:12:56 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:12:56 -0800 Subject: [Python-checkins] python/dist/src/Misc/RPM python-2.2.spec,1.1,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Misc/RPM In directory sc8-pr-cvs1:/tmp/cvs-serv21821 Removed Files: python-2.2.spec Log Message: Deleting the 2.2 spec. --- python-2.2.spec DELETED --- From gvanrossum@users.sourceforge.net Mon Feb 24 01:18:37 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:18:37 -0800 Subject: [Python-checkins] python/dist/src/Lib sre_compile.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv23246 Modified Files: sre_compile.py Log Message: Fix from SF patch #633359 by Greg Chapman for SF bug #610299: The problem is in sre_compile.py: the call to _compile_charset near the end of _compile_info forgets to pass in the flags, so that the info charset is not compiled with re.U. (The info charset is used when searching to find the first character at which a match could start; it is not generated for patterns beginning with a repeat like '\w{1}'.) Index: sre_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sre_compile.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** sre_compile.py 26 Sep 2002 16:39:20 -0000 1.44 --- sre_compile.py 24 Feb 2003 01:18:35 -0000 1.45 *************** *** 400,404 **** code.extend(table[1:]) # don't store first entry elif charset: ! _compile_charset(charset, 0, code) code[skip] = len(code) - skip --- 400,404 ---- code.extend(table[1:]) # don't store first entry elif charset: ! _compile_charset(charset, flags, code) code[skip] = len(code) - skip From gvanrossum@users.sourceforge.net Mon Feb 24 01:18:37 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:18:37 -0800 Subject: [Python-checkins] python/dist/src/Lib/test re_tests.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23246/test Modified Files: re_tests.py Log Message: Fix from SF patch #633359 by Greg Chapman for SF bug #610299: The problem is in sre_compile.py: the call to _compile_charset near the end of _compile_info forgets to pass in the flags, so that the info charset is not compiled with re.U. (The info charset is used when searching to find the first character at which a match could start; it is not generated for patterns beginning with a repeat like '\w{1}'.) Index: re_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/re_tests.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** re_tests.py 19 Feb 2003 02:35:04 -0000 1.33 --- re_tests.py 24 Feb 2003 01:18:35 -0000 1.34 *************** *** 667,669 **** --- 667,670 ---- (r'\b.\b', 'a', SUCCEED, 'found', 'a'), (r'(?u)\b.\b', u, SUCCEED, 'found', u), + (r'(?u)\w', u, SUCCEED, 'found', u), ]) From gvanrossum@users.sourceforge.net Mon Feb 24 01:23:05 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:23:05 -0800 Subject: [Python-checkins] python/dist/src/Lib sre_compile.py,1.41.14.2,1.41.14.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv25159 Modified Files: Tag: release22-maint sre_compile.py Log Message: Backport: Fix from SF patch #633359 by Greg Chapman for SF bug #610299: The problem is in sre_compile.py: the call to _compile_charset near the end of _compile_info forgets to pass in the flags, so that the info charset is not compiled with re.U. (The info charset is used when searching to find the first character at which a match could start; it is not generated for patterns beginning with a repeat like '\w{1}'.) Index: sre_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sre_compile.py,v retrieving revision 1.41.14.2 retrieving revision 1.41.14.3 diff -C2 -d -r1.41.14.2 -r1.41.14.3 *** sre_compile.py 26 Sep 2002 16:41:10 -0000 1.41.14.2 --- sre_compile.py 24 Feb 2003 01:23:02 -0000 1.41.14.3 *************** *** 400,404 **** code.extend(table[1:]) # don't store first entry elif charset: ! _compile_charset(charset, 0, code) code[skip] = len(code) - skip --- 400,404 ---- code.extend(table[1:]) # don't store first entry elif charset: ! _compile_charset(charset, flags, code) code[skip] = len(code) - skip From gvanrossum@users.sourceforge.net Mon Feb 24 01:23:05 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 23 Feb 2003 17:23:05 -0800 Subject: [Python-checkins] python/dist/src/Lib/test re_tests.py,1.30,1.30.6.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25159/test Modified Files: Tag: release22-maint re_tests.py Log Message: Backport: Fix from SF patch #633359 by Greg Chapman for SF bug #610299: The problem is in sre_compile.py: the call to _compile_charset near the end of _compile_info forgets to pass in the flags, so that the info charset is not compiled with re.U. (The info charset is used when searching to find the first character at which a match could start; it is not generated for patterns beginning with a repeat like '\w{1}'.) Index: re_tests.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/re_tests.py,v retrieving revision 1.30 retrieving revision 1.30.6.1 diff -C2 -d -r1.30 -r1.30.6.1 *** re_tests.py 9 Dec 2001 16:13:15 -0000 1.30 --- re_tests.py 24 Feb 2003 01:23:03 -0000 1.30.6.1 *************** *** 658,660 **** --- 658,661 ---- (r'\b.\b', 'a', SUCCEED, 'found', 'a'), (r'(?u)\b.\b', u, SUCCEED, 'found', u), + (r'(?u)\w', u, SUCCEED, 'found', u), ]) From nnorwitz@users.sourceforge.net Mon Feb 24 02:08:45 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 23 Feb 2003 18:08:45 -0800 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.83,2.84 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv6249/Modules Modified Files: arraymodule.c Log Message: SF patch #687598, array.append is sloooow This improves speed by about 5.6% for me. Index: arraymodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/arraymodule.c,v retrieving revision 2.83 retrieving revision 2.84 diff -C2 -d -r2.83 -r2.84 *** arraymodule.c 10 Feb 2003 20:45:47 -0000 2.83 --- arraymodule.c 24 Feb 2003 02:08:42 -0000 2.84 *************** *** 14,17 **** --- 14,63 ---- #endif /* !STDC_HEADERS */ + /* Shamelessy stolen from listobject.c */ + static int + roundupsize(int n) + { + unsigned int nbits = 0; + unsigned int n2 = (unsigned int)n >> 5; + + /* Round up: + * If n < 256, to a multiple of 8. + * If n < 2048, to a multiple of 64. + * If n < 16384, to a multiple of 512. + * If n < 131072, to a multiple of 4096. + * If n < 1048576, to a multiple of 32768. + * If n < 8388608, to a multiple of 262144. + * If n < 67108864, to a multiple of 2097152. + * If n < 536870912, to a multiple of 16777216. + * ... + * If n < 2**(5+3*i), to a multiple of 2**(3*i). + * + * This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc() (which is a reality, e.g., across all flavors + * of Windows, with Win9x behavior being particularly bad -- and + * we've still got address space fragmentation problems on Win9x + * even with this scheme, although it requires much longer lists to + * provoke them than it used to). + */ + do { + n2 >>= 3; + nbits += 3; + } while (n2); + return ((n >> nbits) + 1) << nbits; + } + + #define NRESIZE(var, type, nitems) \ + do { \ + size_t _new_size = roundupsize(nitems); \ + if (_new_size <= ((~(size_t)0) / sizeof(type))) \ + PyMem_RESIZE(var, type, _new_size); \ + else \ + var = NULL; \ + } while (0) + /* END SHAMELESSLY STOLEN CODE */ + struct arrayobject; /* Forward */ *************** *** 420,425 **** return -1; items = self->ob_item; ! PyMem_RESIZE(items, char, ! (self->ob_size+1) * self->ob_descr->itemsize); if (items == NULL) { PyErr_NoMemory(); --- 466,470 ---- return -1; items = self->ob_item; ! NRESIZE(items, char, (self->ob_size+1) * self->ob_descr->itemsize); if (items == NULL) { PyErr_NoMemory(); From jackjansen@users.sourceforge.net Mon Feb 24 11:02:43 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 03:02:43 -0800 Subject: [Python-checkins] python/dist/src/Doc/mac libmacos.tex,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/mac In directory sc8-pr-cvs1:/tmp/cvs-serv25221 Modified Files: libmacos.tex Log Message: Documented linkmodel and WMAvailable(). Index: libmacos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/mac/libmacos.tex,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** libmacos.tex 12 Feb 2003 09:58:33 -0000 1.19 --- libmacos.tex 24 Feb 2003 11:02:36 -0000 1.20 *************** *** 15,22 **** \begin{datadesc}{runtimemodel} ! Either \code{'ppc'}, \code{'carbon'} or \code{'macho'}. This ! signifies whether this Python uses the classic (InterfaceLib style) ! runtime model, the Mac OS X compatible CarbonLib style or the Mac OS ! X-only Mach-O style. \end{datadesc} --- 15,32 ---- \begin{datadesc}{runtimemodel} ! Either\code{'carbon'} or \code{'macho'}. This ! signifies whether this Python uses the Mac OS X and Mac OS 9 compatible ! CarbonLib style or the Mac OS ! X-only Mach-O style. In earlier versions of Python the value could ! also be \code{'ppc'} for the classic Mac OS 8 runtime model. ! \end{datadesc} ! ! \begin{datadesc}{linkmodel} ! The way the interpreter has been linked. As extension modules may be ! incompatible between linking models, packages could use this information to give ! more decent error messages. The value is one of \code{'static'} for a ! statically linked Python, \code{'framework'} for Python in a Mac OS X framework, ! \code{'shared'} for Python in a standard unix shared library and ! \code{'cfm'} for the Mac OS 9-compatible Python. \end{datadesc} *************** *** 136,138 **** --- 146,160 ---- semantics, but it is not a Python file object, so there may be subtle differences. + \end{funcdesc} + + \begin{funcdesc}{WMAvailable}{} + Checks wether the current process has access to the window manager. + The method will return \code{False} if the window manager is not available, + for instance when running on Mac OS X Server or when logged in via ssh, + or when the current interpreter is not running from a fullblown application + bundle. A script runs from an application bundle either when it has been + started with \program{pythonw} in stead of \program{python} or when running + as an applet. + + On Mac OS 9 the method always returns \code{True}. \end{funcdesc} From jackjansen@users.sourceforge.net Mon Feb 24 11:04:21 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 03:04:21 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.676,1.677 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv25802 Modified Files: NEWS Log Message: Added a note about MacOS.WMAvailable(). Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.676 retrieving revision 1.677 diff -C2 -d -r1.676 -r1.677 *** NEWS 23 Feb 2003 23:45:35 -0000 1.676 --- NEWS 24 Feb 2003 11:04:17 -0000 1.677 *************** *** 62,66 **** --- ! TBD --- 62,67 ---- --- ! - A new method MacOS.WMAvailable() returns true if it is safe to access ! the window manager, false otherwise. From guido@python.org Mon Feb 24 12:38:01 2003 From: guido@python.org (Guido van Rossum) Date: Mon, 24 Feb 2003 07:38:01 -0500 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.83,2.84 In-Reply-To: "Your message of Sun, 23 Feb 2003 18:08:45 PST." References: Message-ID: <200302241238.h1OCc1112862@pcp02138704pcs.reston01.va.comcast.net> > This improves speed by about 5.6% for me. I don't understand this comment. If the fix works, it should change quadratic time to something vaguely N-log-N-ish, which cannot be expressed as a percentage without knowing N. --Guido van Rossum (home page: http://www.python.org/~guido/) From jackjansen@users.sourceforge.net Mon Feb 24 12:49:02 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 04:49:02 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.149,1.150 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv30748 Modified Files: setup.py Log Message: The test for iconv_incs tested explicitly for None, but [] is returned if the include files cannot be found. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.149 retrieving revision 1.150 diff -C2 -d -r1.149 -r1.150 *** setup.py 23 Feb 2003 21:47:05 -0000 1.149 --- setup.py 24 Feb 2003 12:48:58 -0000 1.150 *************** *** 623,628 **** ['/usr/local/lib', '/usr/pkg/lib']) ! if (iconv_incs is not None): ! if iconv_libs is not None: iconv_libraries = ['iconv'] else: --- 623,628 ---- ['/usr/local/lib', '/usr/pkg/lib']) ! if iconv_incs: ! if iconv_libs: iconv_libraries = ['iconv'] else: From jackjansen@users.sourceforge.net Mon Feb 24 12:56:39 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 04:56:39 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.150,1.151 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv912 Modified Files: setup.py Log Message: That fix was bogus, undone. The problem is that the iconv include file is found if you are running fink, but the module doesn't work. For now I disabled building iconv_codec on darwin. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.150 retrieving revision 1.151 diff -C2 -d -r1.150 -r1.151 *** setup.py 24 Feb 2003 12:48:58 -0000 1.150 --- setup.py 24 Feb 2003 12:56:36 -0000 1.151 *************** *** 622,628 **** iconv_libs = find_library_file(self.compiler, 'iconv', lib_dirs, ['/usr/local/lib', '/usr/pkg/lib']) ! ! if iconv_incs: ! if iconv_libs: iconv_libraries = ['iconv'] else: --- 622,628 ---- iconv_libs = find_library_file(self.compiler, 'iconv', lib_dirs, ['/usr/local/lib', '/usr/pkg/lib']) ! ! if platform not in ['darwin'] and iconv_incs is not None: ! if iconv_libs is not None: iconv_libraries = ['iconv'] else: From neal@metaslash.com Mon Feb 24 13:56:08 2003 From: neal@metaslash.com (Neal Norwitz) Date: Mon, 24 Feb 2003 08:56:08 -0500 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.83,2.84 In-Reply-To: <200302241238.h1OCc1112862@pcp02138704pcs.reston01.va.comcast.net> References: <200302241238.h1OCc1112862@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <20030224135608.GA2041@epoch.metaslash.com> On Mon, Feb 24, 2003 at 07:38:01AM -0500, Guido van Rossum wrote: > > This improves speed by about 5.6% for me. ["This" refers to adding roundupsize() to bump up the size of an array by increasing large multiples (same as a list).] > I don't understand this comment. If the fix works, it should change > quadratic time to something vaguely N-log-N-ish, which cannot be > expressed as a percentage without knowing N. By adding roundupsize(), the difference was calling PyMem_RESIZE() fewer times and also doing a memmove less. I was surprised at how little benefit there was, that was why I added the comment. I would like to know if this affects other platforms more. I noticed the original problem was on windows. With 10,000,000 elements, I tested before and after the patch: before= 42.5821830034 seconds after= 40.1672360897 seconds I'm not sure what the deal is. The code looks like it is the same as in listobject, except that array uses a memmove while list uses a for loop. Can someone test on windows to see if the timing is drastically improved? Maybe it's just a realloc issue? Neal From jackjansen@users.sourceforge.net Mon Feb 24 15:26:42 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 07:26:42 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_atexit.py,1.9,1.10 test_popen.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv4678 Modified Files: test_atexit.py test_popen.py Log Message: sys.executable can contain spaces, cater for this when passing it to os.popen(). Fixes #692222. Index: test_atexit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_atexit.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** test_atexit.py 6 Nov 2002 11:37:57 -0000 1.9 --- test_atexit.py 24 Feb 2003 15:26:39 -0000 1.10 *************** *** 28,32 **** f.close() ! p = popen("%s %s" % (executable, fname)) output = p.read() p.close() --- 28,32 ---- f.close() ! p = popen('"%s" %s' % (executable, fname)) output = p.read() p.close() *************** *** 56,60 **** f.close() ! p = popen("%s %s" % (executable, fname)) output = p.read() p.close() --- 56,60 ---- f.close() ! p = popen('"%s" %s' % (executable, fname)) output = p.read() p.close() Index: test_popen.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_popen.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** test_popen.py 23 Jul 2002 19:03:58 -0000 1.3 --- test_popen.py 24 Feb 2003 15:26:39 -0000 1.4 *************** *** 16,20 **** # We can then eval() the result of this, and see what each argv was. def _do_test_commandline(cmdline, expected): ! cmd = '%s -c "import sys;print sys.argv" %s' % (sys.executable, cmdline) data = popen(cmd).read() got = eval(data)[1:] # strip off argv[0] --- 16,20 ---- # We can then eval() the result of this, and see what each argv was. def _do_test_commandline(cmdline, expected): ! cmd = '"%s" -c "import sys;print sys.argv" %s' % (sys.executable, cmdline) data = popen(cmd).read() got = eval(data)[1:] # strip off argv[0] From doerwalter@users.sourceforge.net Mon Feb 24 15:33:35 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 24 Feb 2003 07:33:35 -0800 Subject: [Python-checkins] python/dist/src/Python exceptions.c,1.43,1.44 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv7765/Python Modified Files: exceptions.c Log Message: Remove unused variables. Index: exceptions.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/exceptions.c,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** exceptions.c 31 Jan 2003 18:33:18 -0000 1.43 --- exceptions.c 24 Feb 2003 15:33:31 -0000 1.44 *************** *** 1228,1232 **** PyObject *encodingObj = NULL; PyObject *objectObj = NULL; - int length; int start; int end; --- 1228,1231 ---- *************** *** 1243,1248 **** goto error; - length = PyUnicode_GET_SIZE(objectObj); - if (PyUnicodeEncodeError_GetStart(self, &start)) goto error; --- 1242,1245 ---- *************** *** 1308,1312 **** PyObject *encodingObj = NULL; PyObject *objectObj = NULL; - int length; int start; int end; --- 1305,1308 ---- *************** *** 1323,1328 **** goto error; - length = PyString_GET_SIZE(objectObj); - if (PyUnicodeDecodeError_GetStart(self, &start)) goto error; --- 1319,1322 ---- *************** *** 1424,1428 **** { PyObject *objectObj = NULL; - int length; int start; int end; --- 1418,1421 ---- *************** *** 1435,1440 **** if (!(objectObj = PyUnicodeTranslateError_GetObject(self))) goto error; - - length = PyUnicode_GET_SIZE(objectObj); if (PyUnicodeTranslateError_GetStart(self, &start)) --- 1428,1431 ---- From jackjansen@users.sourceforge.net Mon Feb 24 16:26:32 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 08:26:32 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac buildtools.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv30137 Modified Files: buildtools.py Log Message: Added a -c (--copyfile) option with argument src:dst which copies file src into dst in the bundle. The Python API already had this functionality Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** buildtools.py 18 Feb 2003 23:30:27 -0000 1.6 --- buildtools.py 24 Feb 2003 16:26:25 -0000 1.7 *************** *** 302,306 **** builder.resources.append(rsrcname) for o in others: ! builder.resources.append(o) if plistname: import plistlib --- 302,309 ---- builder.resources.append(rsrcname) for o in others: ! if type(o) == str: ! builder.resources.append(o) ! else: ! builder.files.append(o) if plistname: import plistlib From jackjansen@users.sourceforge.net Mon Feb 24 16:27:13 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 08:27:13 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv30806 Modified Files: bundlebuilder.py Log Message: Added a -c (--copyfile) option with argument src:dst which copies file src into dst in the bundle. The Python API already had this functionality Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** bundlebuilder.py 18 Feb 2003 23:29:46 -0000 1.10 --- bundlebuilder.py 24 Feb 2003 16:27:08 -0000 1.11 *************** *** 649,652 **** --- 649,653 ---- -n, --name=NAME application name -r, --resource=FILE extra file or folder to be copied to Resources + -f, --copyfile=SRC:DST extra file or folder to be copied into the bundle -e, --executable=FILE the executable to be used -m, --mainprogram=FILE the Python main program *************** *** 680,685 **** builder = AppBuilder(verbosity=1) ! shortopts = "b:n:r:e:m:c:p:lx:i:hvqa" ! longopts = ("builddir=", "name=", "resource=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", --- 681,686 ---- builder = AppBuilder(verbosity=1) ! shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" ! longopts = ("builddir=", "name=", "resource=", "copyfile=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", *************** *** 698,701 **** --- 699,707 ---- elif opt in ('-r', '--resource'): builder.resources.append(arg) + elif opt in ('-f', '--copyfile'): + srcdst = arg.split(':') + if len(srcdst) != 2: + usage() + builder.files.append(srcdst) elif opt in ('-e', '--executable'): builder.executable = arg From jackjansen@users.sourceforge.net Mon Feb 24 16:28:40 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 08:28:40 -0800 Subject: [Python-checkins] python/dist/src/Mac/scripts BuildApplet.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv31229 Modified Files: BuildApplet.py Log Message: Allow specifiying the destination for --extra files (default: same filename as the source, but in Contents/Resources in the app bundle). Index: BuildApplet.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/scripts/BuildApplet.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** BuildApplet.py 26 Jan 2003 20:35:47 -0000 1.18 --- BuildApplet.py 24 Feb 2003 16:28:37 -0000 1.19 *************** *** 76,79 **** --- 76,81 ---- raw = 1 elif opt in ('-e', '--extra'): + if ':' in arg: + arg = arg.split(':') extras.append(arg) elif opt in ('-v', '--verbose'): *************** *** 100,109 **** print " BuildApplet [options] src.py non-interactive single file" print "Options:" ! print " --output o Output file; default based on source filename, short -o" ! print " --resource r Resource file; default based on source filename, short -r" ! print " --noargv Build applet without drag-and-drop sys.argv emulation, short -n, OSX only" ! print " --extra f Extra file to put in .app bundle, short -e, OSX only" ! print " --verbose Verbose, short -v" ! print " --help This message, short -?" sys.exit(1) --- 102,111 ---- print " BuildApplet [options] src.py non-interactive single file" print "Options:" ! print " --output o Output file; default based on source filename, short -o" ! print " --resource r Resource file; default based on source filename, short -r" ! print " --noargv Build applet without drag-and-drop sys.argv emulation, short -n, OSX only" ! print " --extra src[:dst] Extra file to put in .app bundle, short -e, OSX only" ! print " --verbose Verbose, short -v" ! print " --help This message, short -?" sys.exit(1) From jackjansen@users.sourceforge.net Mon Feb 24 16:30:29 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Mon, 24 Feb 2003 08:30:29 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX Makefile,1.35,1.36 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv32315 Modified Files: Makefile Log Message: Fix building of Idle applet. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/Makefile,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** Makefile 18 Feb 2003 23:33:39 -0000 1.35 --- Makefile 24 Feb 2003 16:30:24 -0000 1.36 *************** *** 143,152 **** $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ --output $(PYTHONAPPSDIR)/IDLE.app \ ! --extra $(srcdir)/Tools/idle \ $(srcdir)/Tools/idle/idle ; \ - echo mv $(PYTHONAPPSDIR)/IDLE.app/Contents/Resources/idle \ - $(PYTHONAPPSDIR)/IDLE.app/Contents/Resources/idlelib; \ - mv $(PYTHONAPPSDIR)/IDLE.app/Contents/Resources/idle \ - $(PYTHONAPPSDIR)/IDLE.app/Contents/Resources/idlelib; \ fi --- 143,148 ---- $(INSTALLED_PYTHONW) $(srcdir)/Mac/scripts/BuildApplet.py \ --output $(PYTHONAPPSDIR)/IDLE.app \ ! --extra $(srcdir)/Tools/idle:Contents/Resources/idlelib \ $(srcdir)/Tools/idle/idle ; \ fi From gvanrossum@users.sourceforge.net Mon Feb 24 17:55:42 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 24 Feb 2003 09:55:42 -0800 Subject: [Python-checkins] python/dist/src/Misc/RPM python-2.3.spec,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Misc/RPM In directory sc8-pr-cvs1:/tmp/cvs-serv5769 Modified Files: python-2.3.spec Log Message: 2.3b1 patches Index: python-2.3.spec =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/RPM/python-2.3.spec,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** python-2.3.spec 24 Feb 2003 01:09:53 -0000 1.1 --- python-2.3.spec 24 Feb 2003 17:55:37 -0000 1.2 *************** *** 31,37 **** %define name python ! %define version 2.3a2 %define libvers 2.3 ! %define release 2 %define __prefix /usr --- 31,37 ---- %define name python ! %define version 2.3b1 %define libvers 2.3 ! %define release 1pydotorg %define __prefix /usr *************** *** 123,126 **** --- 123,129 ---- %changelog + * Mon Feb 24 2003 Sean Reifschneider [2.3b1-1pydotorg] + - Updating to 2.3b1 release. + * Mon Feb 17 2003 Sean Reifschneider [2.3a1-1] - Updating to 2.3 release. From tim.one@comcast.net Mon Feb 24 18:13:08 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon, 24 Feb 2003 13:13:08 -0500 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.83,2.84 In-Reply-To: <20030224135608.GA2041@epoch.metaslash.com> Message-ID: [Neal Norwitz] > ... > With 10,000,000 elements, I tested before and after the patch: > > before= 42.5821830034 seconds > after= 40.1672360897 seconds > > I'm not sure what the deal is. The code looks like it is the same as > in listobject, except that array uses a memmove while list uses a for > loop. Can someone test on windows to see if the timing is drastically > improved? Maybe it's just a realloc issue? Code: """ import sys import array from time import clock as now print sys.version for exponent in range(7): n = 10**exponent a = array.array('i') start = now() for i in xrange(n): a.append(i) finish = now() print "%8d %.2f" % (n, finish - start) """ Timings on Win2K under MSVC6: 2.3a2+ (#39, Feb 24 2003, 09:34:58) [MSC v.1200 32 bit (Intel)] 1 0.00 10 0.00 100 0.00 1000 0.00 10000 0.02 100000 0.27 1000000 2.90 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] 1 0.00 10 0.00 100 0.00 1000 0.00 10000 0.03 100000 0.30 1000000 35.56 I don't have time to try 10 million under 2.2.2. "Before" timings are undoubtedly much worse under Win9x (because they were for list appends before adding mildly exponential over-allocation for list growth). From doerwalter@users.sourceforge.net Mon Feb 24 20:17:38 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Mon, 24 Feb 2003 12:17:38 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv8639/Modules Modified Files: _iconv_codec.c Log Message: Change the test encoding from "ISO8859-1" to "ISO-8859-1" (see SF bug #690309) and raise ImportErrors instead of RuntimeErrors, so building Python continues even if importing iconv_codecs fails. This is a temporary fix until we get proper configure support for "broken" iconv implementations. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _iconv_codec.c 21 Feb 2003 18:18:49 -0000 1.12 --- _iconv_codec.c 24 Feb 2003 20:17:32 -0000 1.13 *************** *** 672,679 **** size_t res; ! iconv_t hdl = iconv_open(UNICODE_ENCODING, "ISO8859-1"); if (hdl == (iconv_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: iconv_open() failed"); return; --- 672,679 ---- size_t res; ! iconv_t hdl = iconv_open(UNICODE_ENCODING, "ISO-8859-1"); if (hdl == (iconv_t)-1) { ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: iconv_open() failed"); return; *************** *** 682,686 **** res = iconv(hdl, &inptr, &insize, &outptr, &outsize); if (res == (size_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: iconv() failed"); return; --- 682,686 ---- res = iconv(hdl, &inptr, &insize, &outptr, &outsize); if (res == (size_t)-1) { ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: iconv() failed"); return; *************** *** 699,703 **** else { iconv_close(hdl); ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: mixed endianess"); return; --- 699,703 ---- else { iconv_close(hdl); ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: mixed endianess"); return; From tim.one@comcast.net Tue Feb 25 03:12:24 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon, 24 Feb 2003 22:12:24 -0500 Subject: [Python-checkins] python/dist/src/Modules arraymodule.c,2.83,2.84 In-Reply-To: Message-ID: [Tim] > Code: > > """ > import sys > import array > from time import clock as now > > print sys.version > > for exponent in range(7): > n = 10**exponent > a = array.array('i') > > start = now() > for i in xrange(n): > a.append(i) > finish = now() > > print "%8d %.2f" % (n, finish - start) > """ > > Timings on Win2K under MSVC6: > > 2.3a2+ (#39, Feb 24 2003, 09:34:58) [MSC v.1200 32 bit (Intel)] > 1 0.00 > 10 0.00 > 100 0.00 > 1000 0.00 > 10000 0.02 > 100000 0.27 > 1000000 2.90 > > 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] > 1 0.00 > 10 0.00 > 100 0.00 > 1000 0.00 > 10000 0.03 > 100000 0.30 > 1000000 35.56 > > I don't have time to try 10 million under 2.2.2. "Before" timings are > undoubtedly much worse under Win9x (because they were for list appends > before adding mildly exponential over-allocation for list growth). Heh. They're actually better under Win98SE: 2.3a2+ (#39, Feb 21 2003, 21:38:18) [MSC v.1200 32 bit ( 1 0.00 10 0.00 100 0.00 1000 0.00 10000 0.03 100000 0.26 1000000 2.61 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] 1 0.00 10 0.00 100 0.00 1000 0.00 10000 0.06 100000 0.72 1000000 3.71 However, boosting it 10,000,000 elements on Win98SE, 2.3a2+ shows the hoped-for linear-time growth, but 2.2.2 dies with a MemoryError. As the comments in listobject.c imply, on Win9x fatal address-space fragmentation is a much worse problem with many repeated reallocs than is quadratic-time degeneration. The situation on Win2K is entirely different. Linux is generally well-behaved with repeated realloc, but not all flavors of Unix are (or, at least, weren't, when I was trying to improve list allocation). From jackjansen@users.sourceforge.net Tue Feb 25 12:41:12 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 04:41:12 -0800 Subject: [Python-checkins] python/dist/src Makefile.pre.in,1.113,1.114 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv12464 Modified Files: Makefile.pre.in Log Message: In Mac OS X framework builds don't assume that the executable will be called python.exe but actually pass it from the main Makefile to Mac/OSX/Makefile. This makes framework builds work again on case sensitive filesystems. Fixes bug #677753. Index: Makefile.pre.in =================================================================== RCS file: /cvsroot/python/python/dist/src/Makefile.pre.in,v retrieving revision 1.113 retrieving revision 1.114 diff -C2 -d -r1.113 -r1.114 *** Makefile.pre.in 21 Jan 2003 15:05:02 -0000 1.113 --- Makefile.pre.in 25 Feb 2003 12:41:08 -0000 1.114 *************** *** 834,837 **** --- 834,838 ---- frameworkinstallmaclib: $(MAKE) -f $(srcdir)/Mac/OSX/Makefile installmacsubtree \ + BUILDPYTHON=./$(BUILDPYTHON) \ srcdir=$(srcdir) builddir=. prefix=$(prefix) LIBDEST=$(LIBDEST) *************** *** 839,842 **** --- 840,844 ---- frameworkinstallapps: $(MAKE) -f $(srcdir)/Mac/OSX/Makefile installapps \ + BUILDPYTHON=./$(BUILDPYTHON) \ srcdir=$(srcdir) builddir=. dstroot=$(PYTHONFRAMEWORKPREFIX)/../.. From jackjansen@users.sourceforge.net Tue Feb 25 12:41:12 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 04:41:12 -0800 Subject: [Python-checkins] python/dist/src/Mac/OSX Makefile,1.36,1.37 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/OSX In directory sc8-pr-cvs1:/tmp/cvs-serv12464/Mac/OSX Modified Files: Makefile Log Message: In Mac OS X framework builds don't assume that the executable will be called python.exe but actually pass it from the main Makefile to Mac/OSX/Makefile. This makes framework builds work again on case sensitive filesystems. Fixes bug #677753. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/OSX/Makefile,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** Makefile 24 Feb 2003 16:30:24 -0000 1.36 --- Makefile 25 Feb 2003 12:41:10 -0000 1.37 *************** *** 9,12 **** --- 9,13 ---- prefix=$(dstroot)/Library/Frameworks/Python.framework/Versions/$(VERSION) LIBDEST=$(prefix)/lib/python$(VERSION) + BUILDPYTHON=$(builddir)/python.exe # These are normally glimpsed from the previous set *************** *** 42,46 **** CPMAC=/Developer/Tools/CpMac - PYTHON=$(builddir)/python.exe APPTEMPLATE=$(srcdir)/Mac/OSXResources/app APPSUBDIRS=MacOS Resources Resources/English.lproj --- 43,46 ---- *************** *** 57,61 **** DSTROOT=$(dstroot) INSTALL_PATH=$(PYTHONAPPSPATH) install ! install_Python: $(PYTHON) @for i in $(PYTHONAPPSDIR) $(APPINSTALLDIR) $(APPINSTALLDIR)/Contents; do \ if test ! -d $$i; then \ --- 57,61 ---- DSTROOT=$(dstroot) INSTALL_PATH=$(PYTHONAPPSPATH) install ! install_Python: @for i in $(PYTHONAPPSDIR) $(APPINSTALLDIR) $(APPINSTALLDIR)/Contents; do \ if test ! -d $$i; then \ *************** *** 95,99 **** done; \ done ! $(INSTALL_PROGRAM) $(STRIPFLAG) $(PYTHON) $(APPINSTALLDIR)/Contents/MacOS/python # Finally create the documentation symlink $(LN) -fsn ../../../../English.lproj/Documentation $(APPINSTALLDIR)/Contents/Resources/English.lproj/Documentation --- 95,99 ---- done; \ done ! $(INSTALL_PROGRAM) $(STRIPFLAG) $(BUILDPYTHON) $(APPINSTALLDIR)/Contents/MacOS/python # Finally create the documentation symlink $(LN) -fsn ../../../../English.lproj/Documentation $(APPINSTALLDIR)/Contents/Resources/English.lproj/Documentation *************** *** 208,214 **** $(INSTALL_DATA) $(PTHFILE) $(LIBDEST)/site-packages/ ! $(PYTHON) $(CACHERSRC) -v $(MACLIBDEST) $(MACTOOLSDEST) ! $(PYTHON) -Wi -tt $(compileall) -x badsyntax $(MACTOOLSDEST) ! $(PYTHON) -O -Wi -tt $(compileall) -x badsyntax $(MACTOOLSDEST) # --- 208,214 ---- $(INSTALL_DATA) $(PTHFILE) $(LIBDEST)/site-packages/ ! $(BUILDPYTHON) $(CACHERSRC) -v $(MACLIBDEST) $(MACTOOLSDEST) ! $(BUILDPYTHON) -Wi -tt $(compileall) -x badsyntax $(MACTOOLSDEST) ! $(BUILDPYTHON) -O -Wi -tt $(compileall) -x badsyntax $(MACTOOLSDEST) # From jackjansen@users.sourceforge.net Tue Feb 25 12:59:01 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 04:59:01 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_plistlib.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19809 Added Files: test_plistlib.py Log Message: Test suite for the plistlib module. --- NEW FILE: test_plistlib.py --- # Copyright (C) 2003 Python Software Foundation import unittest import plistlib import os from test import test_support class TestPlistlib(unittest.TestCase): def tearDown(self): try: os.unlink(test_support.TESTFN) except: pass def _create(self): pl = plistlib.Plist( aString="Doodah", aList=["A", "B", 12, 32.1, [1, 2, 3]], aFloat = 0.1, anInt = 728, aDict=plistlib.Dict( anotherString="", aUnicodeValue=u'M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, ), someData = plistlib.Data(""), someMoreData = plistlib.Data("" * 10), ) pl['anotherInt'] = 42 try: from xml.utils.iso8601 import parse import time except ImportError: pass else: pl['aDate'] = plistlib.Date(time.mktime(time.gmtime())) return pl def test_create(self): pl = self._create() self.assertEqual(pl["aString"], "Doodah") self.assertEqual(pl["aDict"]["aFalseValue"], False) def test_io(self): pl = self._create() pl.write(test_support.TESTFN) pl2 = plistlib.Plist.fromFile(test_support.TESTFN) self.assertEqual(dict(pl), dict(pl2)) def test_main(): test_support.run_unittest(TestPlistlib) if __name__ == '__main__': test_main() From jackjansen@users.sourceforge.net Tue Feb 25 13:15:43 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 05:15:43 -0800 Subject: [Python-checkins] python/dist/src configure.in,1.391,1.392 configure,1.380,1.381 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv26934 Modified Files: configure.in configure Log Message: Refer to the Mac OS X bundle_loader by the altbininstall name, so that building distutils extension modules also works if you've only done an altinstall. Fixes bug #677293. Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.391 retrieving revision 1.392 diff -C2 -d -r1.391 -r1.392 *** configure.in 23 Feb 2003 23:28:15 -0000 1.391 --- configure.in 25 Feb 2003 13:14:42 -0000 1.392 *************** *** 1082,1086 **** # No framework, use the Python app as bundle-loader BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' ! LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/$(PYTHON)' fi ;; Linux*|GNU*) LDSHARED='$(CC) -shared';; --- 1082,1086 ---- # No framework, use the Python app as bundle-loader BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' ! LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' fi ;; Linux*|GNU*) LDSHARED='$(CC) -shared';; Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.380 retrieving revision 1.381 diff -C2 -d -r1.380 -r1.381 *** configure 23 Feb 2003 23:28:08 -0000 1.380 --- configure 25 Feb 2003 13:14:43 -0000 1.381 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.390 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.391 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 9357,9361 **** # No framework, use the Python app as bundle-loader BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' ! LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/$(PYTHON)' fi ;; Linux*|GNU*) LDSHARED='$(CC) -shared';; --- 9357,9361 ---- # No framework, use the Python app as bundle-loader BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' ! LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' fi ;; Linux*|GNU*) LDSHARED='$(CC) -shared';; From jackjansen@users.sourceforge.net Tue Feb 25 13:34:25 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 05:34:25 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac ic.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv3875 Modified Files: ic.py Log Message: Workaround for bug #644243 (which is actually an Apple bug, I think): URLs of the form file:/path/to/file don't work whereas file:///path/to/file works fine. We convert the former to the latter. Index: ic.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/ic.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ic.py 21 Feb 2003 23:18:48 -0000 1.3 --- ic.py 25 Feb 2003 13:34:22 -0000 1.4 *************** *** 196,199 **** --- 196,203 ---- def launchurl(self, url, hint=""): + # Work around a bug in ICLaunchURL: file:/foo does + # not work but file:///foo does. + if url[:6] == 'file:/' and url[6] != '/': + url = 'file:///' + url[6:] self.ic.ICLaunchURL(hint, url, 0, len(url)) From jackjansen@users.sourceforge.net Tue Feb 25 14:19:13 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 06:19:13 -0800 Subject: [Python-checkins] python/dist/src/Mac/Python macmain.c,1.72.8.2,1.72.8.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Python In directory sc8-pr-cvs1:/tmp/cvs-serv24788 Modified Files: Tag: release22-maint macmain.c Log Message: Removed debug output. Fixes #635570 Index: macmain.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macmain.c,v retrieving revision 1.72.8.2 retrieving revision 1.72.8.3 diff -C2 -d -r1.72.8.2 -r1.72.8.3 *** macmain.c 29 Oct 2002 22:03:45 -0000 1.72.8.2 --- macmain.c 25 Feb 2003 14:19:07 -0000 1.72.8.3 *************** *** 559,569 **** script = scriptpath; - printf("original argc=%d\n", argc); - for(i=0; i Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv25398 Modified Files: Tag: release22-maint dynload_next.c Log Message: Partial backport of 2.11: better error messages on import failures. Fixes #652590. Index: dynload_next.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/dynload_next.c,v retrieving revision 2.10 retrieving revision 2.10.6.1 diff -C2 -d -r2.10 -r2.10.6.1 *** dynload_next.c 6 Dec 2001 22:58:56 -0000 2.10 --- dynload_next.c 25 Feb 2003 14:20:44 -0000 2.10.6.1 *************** *** 121,124 **** --- 121,125 ---- NSSymbol theSym; const char *errString; + char errBuf[512]; if (NSIsSymbolNameDefined(funcname)) { *************** *** 151,156 **** newModule = NSLinkModule(image, pathname, NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR); ! if (!newModule) ! errString = "Failure linking new module"; } if (errString != NULL) { --- 152,164 ---- newModule = NSLinkModule(image, pathname, NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR); ! if (newModule == NULL) { ! int errNo; ! char *fileName, *moreErrorStr; ! NSLinkEditErrors c; ! NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); ! PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", ! fileName, moreErrorStr); ! errString = errBuf; ! } } if (errString != NULL) { From jackjansen@users.sourceforge.net Tue Feb 25 15:08:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 07:08:09 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyEdit.py,1.38,1.39 PythonIDEMain.py,1.28,1.29 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv15512 Modified Files: PyEdit.py PythonIDEMain.py Log Message: Added an "Open Recent" command. Fixes 607810. Index: PyEdit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyEdit.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** PyEdit.py 21 Feb 2003 22:33:52 -0000 1.38 --- PyEdit.py 25 Feb 2003 15:08:01 -0000 1.39 *************** *** 64,67 **** --- 64,68 ---- f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) + self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path *************** *** 400,403 **** --- 401,405 ---- import macostools macostools.touched(self.path) + self.addrecentfile(self.path) def can_save(self, menuitem): *************** *** 781,784 **** --- 783,790 ---- def selectline(self, lineno, charoffset = 0): self.editgroup.editor.selectline(lineno - 1, charoffset) + + def addrecentfile(self, filename): + app = W.getapplication() + app.addrecentfile(filename) class _saveoptions: Index: PythonIDEMain.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PythonIDEMain.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** PythonIDEMain.py 12 Feb 2003 12:47:56 -0000 1.28 --- PythonIDEMain.py 25 Feb 2003 15:08:02 -0000 1.29 *************** *** 77,80 **** --- 77,82 ---- openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELIPSES, "D", 'openbyname') + self.openrecentmenu = FrameWork.SubMenu(m, "Open Recent") + self.makeopenrecentmenu() FrameWork.Separator(m) closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') *************** *** 279,286 **** --- 281,326 ---- self.checkopenwindowsmenu() + def makeopenrecentmenu(self): + for i in range(len(self.openrecentmenu.items)): + self.openrecentmenu.menu.DeleteMenuItem(1) + self.openrecentmenu.items = [] + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + self.openrecentmenu.enable(0) + return + self.openrecentmenu.enable(1) + for filename in filelist: + item = FrameWork.MenuItem(self.openrecentmenu, filename, None, callback = self.domenu_openrecent) + + def addrecentfile(self, file): + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + filelist = [] + + if file in filelist: + if file == filelist[0]: + return + filelist.remove(file) + filelist.insert(0, file) + filelist = filelist[:10] + prefs.recentfiles = filelist + prefs.save() + self.makeopenrecentmenu() + def domenu_openwindows(self, id, item, window, event): w = self._openwindows[item] w.ShowWindow() w.SelectWindow() + + def domenu_openrecent(self, id, item, window, event): + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + filelist = [] + item = item - 1 + filename = filelist[item] + self.openscript(filename) def domenu_quit(self): From montanaro@users.sourceforge.net Tue Feb 25 17:46:31 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 25 Feb 2003 09:46:31 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.677,1.678 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv3899 Modified Files: NEWS Log Message: note the demise of the dospath module (was actually in 2.3a2) Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.677 retrieving revision 1.678 diff -C2 -d -r1.677 -r1.678 *** NEWS 24 Feb 2003 11:04:17 -0000 1.677 --- NEWS 25 Feb 2003 17:46:20 -0000 1.678 *************** *** 364,367 **** --- 364,370 ---- See SF patch #642974. + - The dospath module was deleted. Use the ntpath module when manipulating + DOS paths from other platforms. + Tools/Demos ----------- From montanaro@users.sourceforge.net Tue Feb 25 17:48:21 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Tue, 25 Feb 2003 09:48:21 -0800 Subject: [Python-checkins] python/dist/src/Lib httplib.py,1.70,1.71 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv4881 Modified Files: httplib.py Log Message: typo Index: httplib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/httplib.py,v retrieving revision 1.70 retrieving revision 1.71 diff -C2 -d -r1.70 -r1.71 *** httplib.py 24 Nov 2002 02:35:33 -0000 1.70 --- httplib.py 25 Feb 2003 17:48:15 -0000 1.71 *************** *** 1141,1145 **** # called when the last byte is read from the line. After the # call, all read methods are delegated to the underlying file ! # obhect. self._line_consumed = 1 self.read = self._file.read --- 1141,1145 ---- # called when the last byte is read from the line. After the # call, all read methods are delegated to the underlying file ! # object. self._line_consumed = 1 self.read = self._file.read From jvr@users.sourceforge.net Tue Feb 25 20:15:44 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 12:15:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv3248 Modified Files: bundlebuilder.py Log Message: Resolving parts of #688907: - Replaced bootstrap shell script with Python script. This means standalone apps built with bundlebuilder will not work on MacOS < 10.1, since we depend (again) on an installed Python. - Add a hack to set sys.executable; the bootstrap script does os.execve() with an argv[0] that's different from the actual Python executable (it has to match the CFBundleExecutable entry in the Info.plist to make the app work both from the Finder and the command line, and it has to be the bootstrap script), yet a proper sys.executable is needed to spawn auxiliary processes. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** bundlebuilder.py 24 Feb 2003 16:27:08 -0000 1.11 --- bundlebuilder.py 25 Feb 2003 20:15:40 -0000 1.12 *************** *** 231,235 **** --- 231,245 ---- return path, MAGIC + '\0\0\0\0' + marshal.dumps(code) + SITECUSTOMIZE_PY = """\ + import sys, os + executable = os.getenv("PYTHONEXECUTABLE") + if executable is not None: + sys.executable = executable + """ + + SITE_PY += SITECUSTOMIZE_PY SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec") + SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec") + EXT_LOADER = """\ *************** *** 256,268 **** BOOTSTRAP_SCRIPT = """\ ! #!/bin/sh ! execdir=$(dirname "${0}") ! executable="${execdir}/%(executable)s" ! resdir=$(dirname "${execdir}")/Resources ! main="${resdir}/%(mainprogram)s" ! PYTHONPATH="$resdir" ! export PYTHONPATH ! exec "${executable}" "${main}" "$@" """ --- 266,281 ---- BOOTSTRAP_SCRIPT = """\ ! #!/usr/bin/env python ! import sys, os ! execdir = os.path.dirname(sys.argv[0]) ! executable = os.path.join(execdir, "%(executable)s") ! resdir = os.path.join(os.path.dirname(execdir), "Resources") ! mainprogram = os.path.join(resdir, "%(mainprogram)s") ! ! sys.argv.insert(1, mainprogram) ! os.environ["PYTHONPATH"] = resdir ! os.environ["PYTHONEXECUTABLE"] = executable ! os.execve(executable, sys.argv, os.environ) """ *************** *** 416,419 **** --- 429,436 ---- if self.standalone: self.addPythonModules() + else: + sitecustomizepath = pathjoin(self.bundlepath, "Contents", "Resources", + "sitecustomize" + PYC_EXT) + writePyc(SITECUSTOMIZE_CO, sitecustomizepath) if self.strip and not self.symlink: self.stripBinaries() *************** *** 487,490 **** --- 504,510 ---- site.__code__ = SITE_CO mf.scan_code(SITE_CO, site) + + # warnings.py gets imported implicitly from C + mf.import_hook("warnings") includeModules = self.includeModules[:] From jvr@users.sourceforge.net Tue Feb 25 20:25:18 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 12:25:18 -0800 Subject: [Python-checkins] python/dist/src/Python pythonrun.c,2.178,2.179 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv14679/Python Modified Files: pythonrun.c Log Message: Addendum to #683658: import warnings.py _after_ site.py has run. This ensures that site.py is again the first .py to be imported, giving it back full control over sys.path. Index: pythonrun.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/pythonrun.c,v retrieving revision 2.178 retrieving revision 2.179 diff -C2 -d -r2.178 -r2.179 *** pythonrun.c 19 Feb 2003 00:33:33 -0000 2.178 --- pythonrun.c 25 Feb 2003 20:25:12 -0000 2.179 *************** *** 175,180 **** _PyImportHooks_Init(); - PyModule_WarningsModule = PyImport_ImportModule("warnings"); - initsigs(); /* Signal handling stuff, including initintr() */ --- 175,178 ---- *************** *** 182,185 **** --- 180,185 ---- if (!Py_NoSiteFlag) initsite(); /* Module site */ + + PyModule_WarningsModule = PyImport_ImportModule("warnings"); } From jvr@users.sourceforge.net Tue Feb 25 20:53:15 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 12:53:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv27833 Modified Files: bundlebuilder.py Log Message: added some comments, minor tweaks Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** bundlebuilder.py 25 Feb 2003 20:15:40 -0000 1.12 --- bundlebuilder.py 25 Feb 2003 20:53:12 -0000 1.13 *************** *** 231,234 **** --- 231,246 ---- return path, MAGIC + '\0\0\0\0' + marshal.dumps(code) + # + # The following snippet gets added as sitecustomize.py[co] to + # non-standalone apps and appended to our custom site.py for + # standalone apps. The bootstrap scripts calls os.execve() with + # an argv[0] that's different from the actual executable: argv[0] + # is the bootstrap script itself and matches the CFBundleExecutable + # value in the Info.plist. This is needed to keep the Finder happy + # and have the app work from the command line as well. However, + # this causes sys.executable to also be that value, so we correct + # that from the PYTHONEXECUTABLE environment variable that the + # bootstrap script sets. + # SITECUSTOMIZE_PY = """\ import sys, os *************** *** 242,246 **** SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec") ! EXT_LOADER = """\ def __load(): --- 254,261 ---- SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec") ! # ! # Extension modules can't be in the modules zip archive, so a placeholder ! # is added instead, that loads the extension from a specified location. ! # EXT_LOADER = """\ def __load(): *************** *** 265,268 **** --- 280,294 ---- STRIP_EXEC = "/usr/bin/strip" + # + # We're using a stock interpreter to run the app, yet we need + # a way to pass the Python main program to the interpreter. The + # bootstrapping script fires up the interpreter with the right + # arguments. os.execve() is used as OSX doesn't like us to + # start a real new process. Also, the executable name must match + # the CFBundleExecutable value in the Info.plist, so we lie + # deliberately with argv[0]. The actual Python executable is + # passed in an environment variable so we can "repair" + # sys.executable later. + # BOOTSTRAP_SCRIPT = """\ #!/usr/bin/env python *************** *** 280,284 **** """ ! ARGVEMULATOR="""\ import argvemulator, os --- 306,314 ---- """ ! ! # ! # Optional wrapper that converts "dropped files" into sys.argv values. ! # ! ARGV_EMULATOR = """\ import argvemulator, os *************** *** 287,290 **** --- 317,321 ---- """ + class AppBuilder(BundleBuilder): *************** *** 402,406 **** mainprogrampath = pathjoin(resdirpath, mainprogram) makedirs(resdirpath) ! open(mainprogrampath, "w").write(ARGVEMULATOR % locals()) if self.standalone: self.includeModules.append("argvemulator") --- 433,437 ---- mainprogrampath = pathjoin(resdirpath, mainprogram) makedirs(resdirpath) ! open(mainprogrampath, "w").write(ARGV_EMULATOR % locals()) if self.standalone: self.includeModules.append("argvemulator") From jvr@users.sourceforge.net Tue Feb 25 21:01:01 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 13:01:01 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv30840 Modified Files: bundlebuilder.py Log Message: - renamed the --copyfile option to --file. - tweaked the help text a little. (Jack: up to you to change your client code.) Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** bundlebuilder.py 25 Feb 2003 20:53:12 -0000 1.13 --- bundlebuilder.py 25 Feb 2003 21:00:55 -0000 1.14 *************** *** 700,704 **** -n, --name=NAME application name -r, --resource=FILE extra file or folder to be copied to Resources ! -f, --copyfile=SRC:DST extra file or folder to be copied into the bundle -e, --executable=FILE the executable to be used -m, --mainprogram=FILE the Python main program --- 700,705 ---- -n, --name=NAME application name -r, --resource=FILE extra file or folder to be copied to Resources ! -f, --file=SRC:DST extra file or folder to be copied into the bundle; ! DST must be a path relative to the bundle root -e, --executable=FILE the executable to be used -m, --mainprogram=FILE the Python main program *************** *** 733,737 **** shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" ! longopts = ("builddir=", "name=", "resource=", "copyfile=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", --- 734,738 ---- shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" ! longopts = ("builddir=", "name=", "resource=", "file=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", *************** *** 750,757 **** elif opt in ('-r', '--resource'): builder.resources.append(arg) ! elif opt in ('-f', '--copyfile'): srcdst = arg.split(':') if len(srcdst) != 2: ! usage() builder.files.append(srcdst) elif opt in ('-e', '--executable'): --- 751,759 ---- elif opt in ('-r', '--resource'): builder.resources.append(arg) ! elif opt in ('-f', '--file'): srcdst = arg.split(':') if len(srcdst) != 2: ! usage("-f or --file argument must be an absolute path and " ! "a relative path, separated by a colon") builder.files.append(srcdst) elif opt in ('-e', '--executable'): From jvr@users.sourceforge.net Tue Feb 25 21:08:18 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 13:08:18 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv2014 Modified Files: bundlebuilder.py Log Message: tweak error message Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** bundlebuilder.py 25 Feb 2003 21:00:55 -0000 1.14 --- bundlebuilder.py 25 Feb 2003 21:08:12 -0000 1.15 *************** *** 754,759 **** srcdst = arg.split(':') if len(srcdst) != 2: ! usage("-f or --file argument must be an absolute path and " ! "a relative path, separated by a colon") builder.files.append(srcdst) elif opt in ('-e', '--executable'): --- 754,759 ---- srcdst = arg.split(':') if len(srcdst) != 2: ! usage("-f or --file argument must be two paths, " ! "separated by a colon") builder.files.append(srcdst) elif opt in ('-e', '--executable'): From jvr@users.sourceforge.net Tue Feb 25 21:42:18 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 13:42:18 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.678,1.679 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv16063/Misc Modified Files: NEWS Log Message: Patch #683592: unicode support for os.listdir() os.listdir() may now return unicode strings on platforms that set Py_FileSystemDefaultEncoding. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.678 retrieving revision 1.679 diff -C2 -d -r1.678 -r1.679 *** NEWS 25 Feb 2003 17:46:20 -0000 1.678 --- NEWS 25 Feb 2003 21:41:59 -0000 1.679 *************** *** 26,30 **** ------- ! TBD Tools/Demos --- 26,34 ---- ------- ! - os.listdir() now returns Unicode strings on platforms that set ! Py_FileSystemDefaultEncoding, for file names that are not representable ! in ASCII. (This currently only affects MacOS X; on Windows versions ! with wide file name support os.listdir() already returned Unicode ! strings.) Tools/Demos *************** *** 61,64 **** --- 65,71 ---- Mac --- + + - os.listdir() now may return Unicode strings on MacOS X. See the general + news item under "Library". - A new method MacOS.WMAvailable() returns true if it is safe to access From jvr@users.sourceforge.net Tue Feb 25 21:42:19 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Tue, 25 Feb 2003 13:42:19 -0800 Subject: [Python-checkins] python/dist/src/Modules posixmodule.c,2.286,2.287 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv16063/Modules Modified Files: posixmodule.c Log Message: Patch #683592: unicode support for os.listdir() os.listdir() may now return unicode strings on platforms that set Py_FileSystemDefaultEncoding. Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.286 retrieving revision 2.287 diff -C2 -d -r2.286 -r2.287 *** posixmodule.c 19 Feb 2003 04:08:27 -0000 2.286 --- posixmodule.c 25 Feb 2003 21:42:15 -0000 2.287 *************** *** 1796,1799 **** --- 1796,1823 ---- break; } + #ifdef Py_USING_UNICODE + if (Py_FileSystemDefaultEncoding != NULL) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + Py_DECREF(v); + v = w; + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + /* attempt to convert to ASCII */ + w = PyUnicode_AsASCIIString(v); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else + PyErr_Clear(); + } + #endif if (PyList_Append(d, v) != 0) { Py_DECREF(v); From jackjansen@users.sourceforge.net Tue Feb 25 22:58:37 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 14:58:37 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv15466 Modified Files: bundlebuilder.py Log Message: Reverted the rev. 1.8 change: the magic for decoding resourcefiles is now in buildtools. Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** bundlebuilder.py 25 Feb 2003 21:08:12 -0000 1.15 --- bundlebuilder.py 25 Feb 2003 22:58:33 -0000 1.16 *************** *** 37,42 **** from plistlib import Plist from types import FunctionType as function - import macresource - class BundleBuilderError(Exception): pass --- 37,40 ---- *************** *** 190,195 **** if self.symlink: symlink(src, dst, mkdirs=1) - elif os.path.splitext(src)[1] == '.rsrc': - macresource.install(src, dst, mkdirs=1) else: copy(src, dst, mkdirs=1) --- 188,191 ---- From jackjansen@users.sourceforge.net Tue Feb 25 23:02:13 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 15:02:13 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac buildtools.py,1.7,1.8 macresource.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv15813 Modified Files: buildtools.py macresource.py Log Message: If a resource file cannot be decoded because the directory is readonly create a temporary file. This fixes #688011. Got rid of the install() method in macresource, and replaced it with a resource_filename() method which will optionally decode a given resourcefile (which may be applesingle-encoded) and return the real resourcefile. Use this new method in buildtools to copy the correct resource file to the bundle. This fixes #688007. Index: buildtools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/buildtools.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** buildtools.py 24 Feb 2003 16:26:25 -0000 1.7 --- buildtools.py 25 Feb 2003 23:02:03 -0000 1.8 *************** *** 300,304 **** builder.name = shortname if rsrcname: ! builder.resources.append(rsrcname) for o in others: if type(o) == str: --- 300,306 ---- builder.name = shortname if rsrcname: ! realrsrcname = macresource.resource_pathname(rsrcname) ! builder.files.append((realrsrcname, ! os.path.join('Contents/Resources', os.path.basename(rsrcname)))) for o in others: if type(o) == str: Index: macresource.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/macresource.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** macresource.py 17 Feb 2003 16:47:12 -0000 1.3 --- macresource.py 25 Feb 2003 23:02:03 -0000 1.4 *************** *** 97,100 **** --- 97,126 ---- return refno + def resource_pathname(pathname, verbose=0): + """Return the pathname for a resource file (either DF or RF based). + If the pathname given already refers to such a file simply return it, + otherwise first decode it.""" + try: + refno = Res.FSpOpenResFile(pathname, 1) + Res.CloseResFile(refno) + except Res.Error, arg: + if arg[0] in (-37, -39): + # No resource fork. We may be on OSX, and this may be either + # a data-fork based resource file or a AppleSingle file + # from the CVS repository. + try: + refno = Res.FSOpenResourceFile(pathname, u'', 1) + except Res.Error, arg: + if arg[0] != -199: + # -199 is "bad resource map" + raise + else: + return refno + # Finally try decoding an AppleSingle file + pathname = _decode(pathname, verbose=verbose) + else: + raise + return pathname + def open_error_resource(): """Open the resource file containing the error code to error message *************** *** 102,151 **** need('Estr', 1, filename="errors.rsrc", modname=__name__) ! def _decode(pathname, verbose=0, newpathname=None): # Decode an AppleSingle resource file, return the new pathname. ! if not newpathname: ! newpathname = pathname + '.df.rsrc' ! if os.path.exists(newpathname) and \ ! os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime: ! return newpathname if verbose: ! print 'Decoding', pathname import applesingle applesingle.decode(pathname, newpathname, resonly=1) return newpathname - - def install(src, dst, mkdirs=0): - """Copy a resource file. The result will always be a datafork-based - resource file, whether the source is datafork-based, resource-fork - based or AppleSingle-encoded.""" - if mkdirs: - macostools.mkdirs(os.path.split(dst)[0]) - try: - refno = Res.FSOpenResourceFile(src, u'', 1) - except Res.Error, arg: - if arg[0] != -199: - # -199 is "bad resource map" - raise - else: - # Resource-fork based. Simply copy. - Res.CloseResFile(refno) - macostools.copy(src, dst) - - try: - refno = Res.FSpOpenResFile(src, 1) - except Res.Error, arg: - if not arg[0] in (-37, -39): - raise - else: - Res.CloseResFile(refno) - BUFSIZ=0x80000 # Copy in 0.5Mb chunks - ifp = MacOS.openrf(src, '*rb') - ofp = open(dst, 'wb') - d = ifp.read(BUFSIZ) - while d: - ofp.write(d) - d = ifp.read(BUFSIZ) - ifp.close() - ofp.close() - - _decode(src, newpathname=dst) --- 128,146 ---- need('Estr', 1, filename="errors.rsrc", modname=__name__) ! def _decode(pathname, verbose=0): # Decode an AppleSingle resource file, return the new pathname. ! newpathname = pathname + '.df.rsrc' ! if os.path.exists(newpathname) and \ ! os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime: ! return newpathname ! if hasattr(os, 'access') and not \ ! os.access(os.path.dirname(pathname), os.W_OK|os.X_OK): ! # The destination directory isn't writeable. Create the file in ! # a temporary directory ! import tempfile ! fd, newpathname = tempfile.mkstemp(".rsrc") if verbose: ! print 'Decoding', pathname, 'to', newpathname import applesingle applesingle.decode(pathname, newpathname, resonly=1) return newpathname From jackjansen@users.sourceforge.net Tue Feb 25 23:35:09 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 25 Feb 2003 15:35:09 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac dialogs.rsrc,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv32109 Modified Files: dialogs.rsrc Log Message: Let's try making the dialogs at least Movable Modal. Index: dialogs.rsrc =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/dialogs.rsrc,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 Binary files /tmp/cvsX3gVOS and /tmp/cvsK53fmB differ From jvr@users.sourceforge.net Wed Feb 26 11:08:01 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Wed, 26 Feb 2003 03:08:01 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv19718/Lib/plat-mac Modified Files: bundlebuilder.py Log Message: remove sitecustomize hack, will be solved elsewhere Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** bundlebuilder.py 25 Feb 2003 22:58:33 -0000 1.16 --- bundlebuilder.py 26 Feb 2003 11:07:59 -0000 1.17 *************** *** 227,252 **** return path, MAGIC + '\0\0\0\0' + marshal.dumps(code) - # - # The following snippet gets added as sitecustomize.py[co] to - # non-standalone apps and appended to our custom site.py for - # standalone apps. The bootstrap scripts calls os.execve() with - # an argv[0] that's different from the actual executable: argv[0] - # is the bootstrap script itself and matches the CFBundleExecutable - # value in the Info.plist. This is needed to keep the Finder happy - # and have the app work from the command line as well. However, - # this causes sys.executable to also be that value, so we correct - # that from the PYTHONEXECUTABLE environment variable that the - # bootstrap script sets. - # - SITECUSTOMIZE_PY = """\ - import sys, os - executable = os.getenv("PYTHONEXECUTABLE") - if executable is not None: - sys.executable = executable - """ - - SITE_PY += SITECUSTOMIZE_PY SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec") - SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec") # --- 227,231 ---- *************** *** 456,463 **** if self.standalone: self.addPythonModules() - else: - sitecustomizepath = pathjoin(self.bundlepath, "Contents", "Resources", - "sitecustomize" + PYC_EXT) - writePyc(SITECUSTOMIZE_CO, sitecustomizepath) if self.strip and not self.symlink: self.stripBinaries() --- 435,438 ---- From jvr@users.sourceforge.net Wed Feb 26 11:27:59 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Wed, 26 Feb 2003 03:27:59 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac bundlebuilder.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv26822/Lib/plat-mac Modified Files: bundlebuilder.py Log Message: use the same Python for running the bootstrap script and the main program Index: bundlebuilder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/bundlebuilder.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** bundlebuilder.py 26 Feb 2003 11:07:59 -0000 1.17 --- bundlebuilder.py 26 Feb 2003 11:27:56 -0000 1.18 *************** *** 267,271 **** # BOOTSTRAP_SCRIPT = """\ ! #!/usr/bin/env python import sys, os --- 267,271 ---- # BOOTSTRAP_SCRIPT = """\ ! #!%(hashbang)s import sys, os *************** *** 424,427 **** --- 424,435 ---- bootstrappath = pathjoin(execdir, self.name) makedirs(execdir) + if self.standalone: + # XXX we're screwed when the end user has deleted + # /usr/bin/python + hashbang = "/usr/bin/python" + else: + hashbang = sys.executable + while os.path.islink(hashbang): + hashbang = os.readlink(hashbang) open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals()) os.chmod(bootstrappath, 0775) From doerwalter@users.sourceforge.net Wed Feb 26 14:49:44 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Wed, 26 Feb 2003 06:49:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/test/output test_ucn,1.5,NONE test_unicodedata,1.7,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test/output In directory sc8-pr-cvs1:/tmp/cvs-serv19053/Lib/test/output Removed Files: test_ucn test_unicodedata Log Message: Port test_ucn and test_unicodedata to PyUnit. Add a few tests for error cases increasing coverage in unicodedata.c from 87% to 95% (when the normalization tests are run). From SF patch #662807. --- test_ucn DELETED --- --- test_unicodedata DELETED --- From doerwalter@users.sourceforge.net Wed Feb 26 14:50:14 2003 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Wed, 26 Feb 2003 06:50:14 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_ucn.py,1.11,1.12 test_unicodedata.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19053/Lib/test Modified Files: test_ucn.py test_unicodedata.py Log Message: Port test_ucn and test_unicodedata to PyUnit. Add a few tests for error cases increasing coverage in unicodedata.c from 87% to 95% (when the normalization tests are run). From SF patch #662807. Index: test_ucn.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_ucn.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_ucn.py 23 Nov 2002 18:01:30 -0000 1.11 --- test_ucn.py 26 Feb 2003 14:49:38 -0000 1.12 *************** *** 7,149 **** """#" - from test.test_support import verify, verbose ! print 'Testing General Unicode Character Name, and case insensitivity...', ! # General and case insensitivity test: ! try: ! # put all \N escapes inside exec'd raw strings, to make sure this ! # script runs even if the compiler chokes on \N escapes ! exec r""" ! s = u"\N{LATIN CAPITAL LETTER T}" \ ! u"\N{LATIN SMALL LETTER H}" \ ! u"\N{LATIN SMALL LETTER E}" \ ! u"\N{SPACE}" \ ! u"\N{LATIN SMALL LETTER R}" \ ! u"\N{LATIN CAPITAL LETTER E}" \ ! u"\N{LATIN SMALL LETTER D}" \ ! u"\N{SPACE}" \ ! u"\N{LATIN SMALL LETTER f}" \ ! u"\N{LATIN CAPITAL LeTtEr o}" \ ! u"\N{LATIN SMaLl LETTER x}" \ ! u"\N{SPACE}" \ ! u"\N{LATIN SMALL LETTER A}" \ ! u"\N{LATIN SMALL LETTER T}" \ ! u"\N{LATIN SMALL LETTER E}" \ ! u"\N{SPACE}" \ ! u"\N{LATIN SMALL LETTER T}" \ ! u"\N{LATIN SMALL LETTER H}" \ ! u"\N{LATIN SMALL LETTER E}" \ ! u"\N{SpAcE}" \ ! u"\N{LATIN SMALL LETTER S}" \ ! u"\N{LATIN SMALL LETTER H}" \ ! u"\N{LATIN SMALL LETTER E}" \ ! u"\N{LATIN SMALL LETTER E}" \ ! u"\N{LATIN SMALL LETTER P}" \ ! u"\N{FULL STOP}" ! verify(s == u"The rEd fOx ate the sheep.", s) ! """ ! except UnicodeError, v: ! print v ! print "done." ! import unicodedata ! print "Testing name to code mapping....", ! for char in "SPAM": ! name = "LATIN SMALL LETTER %s" % char ! code = unicodedata.lookup(name) ! verify(unicodedata.name(code) == name) ! print "done." ! print "Testing hangul syllable names....", ! exec r""" ! verify(u"\N{HANGUL SYLLABLE GA}" == u"\uac00") ! verify(u"\N{HANGUL SYLLABLE GGWEOSS}" == u"\uafe8") ! verify(u"\N{HANGUL SYLLABLE DOLS}" == u"\ub3d0") ! verify(u"\N{HANGUL SYLLABLE RYAN}" == u"\ub7b8") ! verify(u"\N{HANGUL SYLLABLE MWIK}" == u"\ubba0") ! verify(u"\N{HANGUL SYLLABLE BBWAEM}" == u"\ubf88") ! verify(u"\N{HANGUL SYLLABLE SSEOL}" == u"\uc370") ! verify(u"\N{HANGUL SYLLABLE YI}" == u"\uc758") ! verify(u"\N{HANGUL SYLLABLE JJYOSS}" == u"\ucb40") ! verify(u"\N{HANGUL SYLLABLE KYEOLS}" == u"\ucf28") ! verify(u"\N{HANGUL SYLLABLE PAN}" == u"\ud310") ! verify(u"\N{HANGUL SYLLABLE HWEOK}" == u"\ud6f8") ! verify(u"\N{HANGUL SYLLABLE HIH}" == u"\ud7a3") ! """ ! try: ! unicodedata.name(u"\ud7a4") ! except ValueError: ! pass ! else: ! raise AssertionError, "Found name for U+D7A4" ! print "done." ! print "Testing names of CJK unified ideographs....", ! exec r""" ! verify(u"\N{CJK UNIFIED IDEOGRAPH-3400}" == u"\u3400") ! verify(u"\N{CJK UNIFIED IDEOGRAPH-4DB5}" == u"\u4db5") ! verify(u"\N{CJK UNIFIED IDEOGRAPH-4E00}" == u"\u4e00") ! verify(u"\N{CJK UNIFIED IDEOGRAPH-9FA5}" == u"\u9fa5") ! verify(u"\N{CJK UNIFIED IDEOGRAPH-20000}" == u"\U00020000") ! verify(u"\N{CJK UNIFIED IDEOGRAPH-2A6D6}" == u"\U0002a6d6") ! """ ! print "done." ! print "Testing code to name mapping for all BMP characters....", ! count = 0 ! for code in range(0x10000): ! try: ! char = unichr(code) ! name = unicodedata.name(char) ! except (KeyError, ValueError): ! pass ! else: ! verify(unicodedata.lookup(name) == char) ! count += 1 ! print "done." ! print "Found", count, "characters in the unicode name database" ! # misc. symbol testing ! print "Testing misc. symbols for unicode character name expansion....", ! exec r""" ! verify(u"\N{PILCROW SIGN}" == u"\u00b6") ! verify(u"\N{REPLACEMENT CHARACTER}" == u"\uFFFD") ! verify(u"\N{HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK}" == u"\uFF9F") ! verify(u"\N{FULLWIDTH LATIN SMALL LETTER A}" == u"\uFF41") ! """ ! print "done." ! # strict error testing: ! print "Testing unicode character name expansion strict error handling....", ! try: ! unicode("\N{blah}", 'unicode-escape', 'strict') ! except UnicodeError: ! pass ! else: ! raise AssertionError, "failed to raise an exception when given a bogus character name" ! try: ! unicode("\N{" + "x" * 100000 + "}", 'unicode-escape', 'strict') ! except UnicodeError: ! pass ! else: ! raise AssertionError, "failed to raise an exception when given a very " \ ! "long bogus character name" ! try: ! unicode("\N{SPACE", 'unicode-escape', 'strict') ! except UnicodeError: ! pass ! else: ! raise AssertionError, "failed to raise an exception for a missing closing brace." ! try: ! unicode("\NSPACE", 'unicode-escape', 'strict') ! except UnicodeError: ! pass ! else: ! raise AssertionError, "failed to raise an exception for a missing opening brace." ! print "done." --- 7,146 ---- """#" ! import unittest ! from test import test_support ! class UnicodeNamesTest(unittest.TestCase): ! def checkletter(self, name, code): ! # Helper that put all \N escapes inside eval'd raw strings, ! # to make sure this script runs even if the compiler ! # chokes on \N escapes ! res = eval(ur'u"\N{%s}"' % name) ! self.assertEqual(res, code) ! return res ! def test_general(self): ! # General and case insensitivity test: ! chars = [ ! "LATIN CAPITAL LETTER T", ! "LATIN SMALL LETTER H", ! "LATIN SMALL LETTER E", ! "SPACE", ! "LATIN SMALL LETTER R", ! "LATIN CAPITAL LETTER E", ! "LATIN SMALL LETTER D", ! "SPACE", ! "LATIN SMALL LETTER f", ! "LATIN CAPITAL LeTtEr o", ! "LATIN SMaLl LETTER x", ! "SPACE", ! "LATIN SMALL LETTER A", ! "LATIN SMALL LETTER T", ! "LATIN SMALL LETTER E", ! "SPACE", ! "LATIN SMALL LETTER T", ! "LATIN SMALL LETTER H", ! "LATIN SMALL LETTER E", ! "SpAcE", ! "LATIN SMALL LETTER S", ! "LATIN SMALL LETTER H", ! "LATIN small LETTER e", ! "LATIN small LETTER e", ! "LATIN SMALL LETTER P", ! "FULL STOP" ! ] ! string = u"The rEd fOx ate the sheep." ! self.assertEqual( ! u"".join([self.checkletter(*args) for args in zip(chars, string)]), ! string ! ) ! def test_ascii_letters(self): ! import unicodedata ! for char in "".join(map(chr, xrange(ord("a"), ord("z")))): ! name = "LATIN SMALL LETTER %s" % char.upper() ! code = unicodedata.lookup(name) ! self.assertEqual(unicodedata.name(code), name) ! def test_hangul_syllables(self): ! self.checkletter("HANGUL SYLLABLE GA", u"\uac00") ! self.checkletter("HANGUL SYLLABLE GGWEOSS", u"\uafe8") ! self.checkletter("HANGUL SYLLABLE DOLS", u"\ub3d0") ! self.checkletter("HANGUL SYLLABLE RYAN", u"\ub7b8") ! self.checkletter("HANGUL SYLLABLE MWIK", u"\ubba0") ! self.checkletter("HANGUL SYLLABLE BBWAEM", u"\ubf88") ! self.checkletter("HANGUL SYLLABLE SSEOL", u"\uc370") ! self.checkletter("HANGUL SYLLABLE YI", u"\uc758") ! self.checkletter("HANGUL SYLLABLE JJYOSS", u"\ucb40") ! self.checkletter("HANGUL SYLLABLE KYEOLS", u"\ucf28") ! self.checkletter("HANGUL SYLLABLE PAN", u"\ud310") ! self.checkletter("HANGUL SYLLABLE HWEOK", u"\ud6f8") ! self.checkletter("HANGUL SYLLABLE HIH", u"\ud7a3") ! import unicodedata ! self.assertRaises(ValueError, unicodedata.name, u"\ud7a4") ! def test_cjk_unified_ideographs(self): ! self.checkletter("CJK UNIFIED IDEOGRAPH-3400", u"\u3400") ! self.checkletter("CJK UNIFIED IDEOGRAPH-4DB5", u"\u4db5") ! self.checkletter("CJK UNIFIED IDEOGRAPH-4E00", u"\u4e00") ! self.checkletter("CJK UNIFIED IDEOGRAPH-9FA5", u"\u9fa5") ! self.checkletter("CJK UNIFIED IDEOGRAPH-20000", u"\U00020000") ! self.checkletter("CJK UNIFIED IDEOGRAPH-2A6D6", u"\U0002a6d6") ! def test_bmp_characters(self): ! import unicodedata ! count = 0 ! for code in xrange(0x10000): ! char = unichr(code) ! name = unicodedata.name(char, None) ! if name is not None: ! self.assertEqual(unicodedata.lookup(name), char) ! count += 1 ! def test_misc_symbols(self): ! self.checkletter("PILCROW SIGN", u"\u00b6") ! self.checkletter("REPLACEMENT CHARACTER", u"\uFFFD") ! self.checkletter("HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK", u"\uFF9F") ! self.checkletter("FULLWIDTH LATIN SMALL LETTER A", u"\uFF41") ! ! def test_errors(self): ! import unicodedata ! self.assertRaises(TypeError, unicodedata.name) ! self.assertRaises(TypeError, unicodedata.name, u'xx') ! self.assertRaises(TypeError, unicodedata.lookup) ! self.assertRaises(KeyError, unicodedata.lookup, u'unknown') ! ! def test_strict_eror_handling(self): ! # bogus character name ! self.assertRaises( ! UnicodeError, ! unicode, "\\N{blah}", 'unicode-escape', 'strict' ! ) ! # long bogus character name ! self.assertRaises( ! UnicodeError, ! unicode, "\\N{%s}" % ("x" * 100000), 'unicode-escape', 'strict' ! ) ! # missing closing brace ! self.assertRaises( ! UnicodeError, ! unicode, "\\N{SPACE", 'unicode-escape', 'strict' ! ) ! # missing opening brace ! self.assertRaises( ! UnicodeError, ! unicode, "\\NSPACE", 'unicode-escape', 'strict' ! ) ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(UnicodeNamesTest)) ! test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() Index: test_unicodedata.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_unicodedata.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_unicodedata.py 23 Jul 2002 19:04:08 -0000 1.6 --- test_unicodedata.py 26 Feb 2003 14:49:39 -0000 1.7 *************** *** 6,125 **** """#" ! from test.test_support import verify, verbose import sha encoding = 'utf-8' - def test_methods(): ! h = sha.sha() ! for i in range(65536): ! char = unichr(i) ! data = [ ! # Predicates (single char) ! char.isalnum() and u'1' or u'0', ! char.isalpha() and u'1' or u'0', ! char.isdecimal() and u'1' or u'0', ! char.isdigit() and u'1' or u'0', ! char.islower() and u'1' or u'0', ! char.isnumeric() and u'1' or u'0', ! char.isspace() and u'1' or u'0', ! char.istitle() and u'1' or u'0', ! char.isupper() and u'1' or u'0', ! # Predicates (multiple chars) ! (char + u'abc').isalnum() and u'1' or u'0', ! (char + u'abc').isalpha() and u'1' or u'0', ! (char + u'123').isdecimal() and u'1' or u'0', ! (char + u'123').isdigit() and u'1' or u'0', ! (char + u'abc').islower() and u'1' or u'0', ! (char + u'123').isnumeric() and u'1' or u'0', ! (char + u' \t').isspace() and u'1' or u'0', ! (char + u'abc').istitle() and u'1' or u'0', ! (char + u'ABC').isupper() and u'1' or u'0', ! # Mappings (single char) ! char.lower(), ! char.upper(), ! char.title(), ! # Mappings (multiple chars) ! (char + u'abc').lower(), ! (char + u'ABC').upper(), ! (char + u'abc').title(), ! (char + u'ABC').title(), ! ] ! h.update(u''.join(data).encode(encoding)) ! return h.hexdigest() ! def test_unicodedata(): ! h = sha.sha() ! for i in range(65536): ! char = unichr(i) ! data = [ ! # Properties ! str(unicodedata.digit(char, -1)), ! str(unicodedata.numeric(char, -1)), ! str(unicodedata.decimal(char, -1)), ! unicodedata.category(char), ! unicodedata.bidirectional(char), ! unicodedata.decomposition(char), ! str(unicodedata.mirrored(char)), ! str(unicodedata.combining(char)), ] ! h.update(''.join(data)) ! return h.hexdigest() ! ### Run tests ! print 'Testing Unicode Database...' ! print 'Methods:', ! print test_methods() ! # In case unicodedata is not available, this will raise an ImportError, ! # but still test the above cases... ! import unicodedata ! print 'Functions:', ! print test_unicodedata() ! # Some additional checks of the API: ! print 'API:', ! verify(unicodedata.digit(u'A',None) is None) ! verify(unicodedata.digit(u'9') == 9) ! verify(unicodedata.digit(u'\u215b',None) is None) ! verify(unicodedata.digit(u'\u2468') == 9) ! verify(unicodedata.numeric(u'A',None) is None) ! verify(unicodedata.numeric(u'9') == 9) ! verify(unicodedata.numeric(u'\u215b') == 0.125) ! verify(unicodedata.numeric(u'\u2468') == 9.0) ! verify(unicodedata.decimal(u'A',None) is None) ! verify(unicodedata.decimal(u'9') == 9) ! verify(unicodedata.decimal(u'\u215b',None) is None) ! verify(unicodedata.decimal(u'\u2468',None) is None) ! verify(unicodedata.category(u'\uFFFE') == 'Cn') ! verify(unicodedata.category(u'a') == 'Ll') ! verify(unicodedata.category(u'A') == 'Lu') ! verify(unicodedata.bidirectional(u'\uFFFE') == '') ! verify(unicodedata.bidirectional(u' ') == 'WS') ! verify(unicodedata.bidirectional(u'A') == 'L') ! verify(unicodedata.decomposition(u'\uFFFE') == '') ! verify(unicodedata.decomposition(u'\u00bc') == ' 0031 2044 0034') ! verify(unicodedata.mirrored(u'\uFFFE') == 0) ! verify(unicodedata.mirrored(u'a') == 0) ! verify(unicodedata.mirrored(u'\u2201') == 1) ! verify(unicodedata.combining(u'\uFFFE') == 0) ! verify(unicodedata.combining(u'a') == 0) ! verify(unicodedata.combining(u'\u20e1') == 230) ! print 'ok' --- 6,213 ---- """#" ! import unittest, test.test_support import sha encoding = 'utf-8' ! ### Run tests ! class UnicodeMethodsTest(unittest.TestCase): ! # update this, if the database changes ! expectedchecksum = 'a37276dc2c158bef6dfd908ad34525c97180fad9' ! def test_method_checksum(self): ! h = sha.sha() ! for i in range(65536): ! char = unichr(i) ! data = [ ! # Predicates (single char) ! u"01"[char.isalnum()], ! u"01"[char.isalpha()], ! u"01"[char.isdecimal()], ! u"01"[char.isdigit()], ! u"01"[char.islower()], ! u"01"[char.isnumeric()], ! u"01"[char.isspace()], ! u"01"[char.istitle()], ! u"01"[char.isupper()], ! # Predicates (multiple chars) ! u"01"[(char + u'abc').isalnum()], ! u"01"[(char + u'abc').isalpha()], ! u"01"[(char + u'123').isdecimal()], ! u"01"[(char + u'123').isdigit()], ! u"01"[(char + u'abc').islower()], ! u"01"[(char + u'123').isnumeric()], ! u"01"[(char + u' \t').isspace()], ! u"01"[(char + u'abc').istitle()], ! u"01"[(char + u'ABC').isupper()], ! # Mappings (single char) ! char.lower(), ! char.upper(), ! char.title(), ! # Mappings (multiple chars) ! (char + u'abc').lower(), ! (char + u'ABC').upper(), ! (char + u'abc').title(), ! (char + u'ABC').title(), ! ] ! h.update(u''.join(data).encode(encoding)) ! result = h.hexdigest() ! self.assertEqual(result, self.expectedchecksum) ! ! class UnicodeDatabaseTest(unittest.TestCase): ! ! def setUp(self): ! # In case unicodedata is not available, this will raise an ImportError, ! # but the other test cases will still be run ! import unicodedata ! self.db = unicodedata ! ! def tearDown(self): ! del self.db ! ! class UnicodeFunctionsTest(UnicodeDatabaseTest): ! ! # update this, if the database changes ! expectedchecksum = 'cfe20a967a450ebc82ca68c3e4eed344164e11af' ! ! def test_function_checksum(self): ! data = [] ! h = sha.sha() ! ! for i in range(0x10000): ! char = unichr(i) ! data = [ ! # Properties ! str(self.db.digit(char, -1)), ! str(self.db.numeric(char, -1)), ! str(self.db.decimal(char, -1)), ! self.db.category(char), ! self.db.bidirectional(char), ! self.db.decomposition(char), ! str(self.db.mirrored(char)), ! str(self.db.combining(char)), ] ! h.update(''.join(data)) ! result = h.hexdigest() ! self.assertEqual(result, self.expectedchecksum) ! def test_digit(self): ! self.assertEqual(self.db.digit(u'A', None), None) ! self.assertEqual(self.db.digit(u'9'), 9) ! self.assertEqual(self.db.digit(u'\u215b', None), None) ! self.assertEqual(self.db.digit(u'\u2468'), 9) ! self.assertRaises(TypeError, self.db.digit) ! self.assertRaises(TypeError, self.db.digit, u'xx') ! self.assertRaises(ValueError, self.db.digit, u'x') ! def test_numeric(self): ! self.assertEqual(self.db.numeric(u'A',None), None) ! self.assertEqual(self.db.numeric(u'9'), 9) ! self.assertEqual(self.db.numeric(u'\u215b'), 0.125) ! self.assertEqual(self.db.numeric(u'\u2468'), 9.0) ! self.assertRaises(TypeError, self.db.numeric) ! self.assertRaises(TypeError, self.db.numeric, u'xx') ! self.assertRaises(ValueError, self.db.numeric, u'x') ! def test_decimal(self): ! self.assertEqual(self.db.decimal(u'A',None), None) ! self.assertEqual(self.db.decimal(u'9'), 9) ! self.assertEqual(self.db.decimal(u'\u215b', None), None) ! self.assertEqual(self.db.decimal(u'\u2468', None), None) ! self.assertRaises(TypeError, self.db.decimal) ! self.assertRaises(TypeError, self.db.decimal, u'xx') ! self.assertRaises(ValueError, self.db.decimal, u'x') ! def test_category(self): ! self.assertEqual(self.db.category(u'\uFFFE'), 'Cn') ! self.assertEqual(self.db.category(u'a'), 'Ll') ! self.assertEqual(self.db.category(u'A'), 'Lu') ! self.assertRaises(TypeError, self.db.category) ! self.assertRaises(TypeError, self.db.category, u'xx') ! def test_bidirectional(self): ! self.assertEqual(self.db.bidirectional(u'\uFFFE'), '') ! self.assertEqual(self.db.bidirectional(u' '), 'WS') ! self.assertEqual(self.db.bidirectional(u'A'), 'L') ! self.assertRaises(TypeError, self.db.bidirectional) ! self.assertRaises(TypeError, self.db.bidirectional, u'xx') ! def test_decomposition(self): ! self.assertEqual(self.db.decomposition(u'\uFFFE'),'') ! self.assertEqual(self.db.decomposition(u'\u00bc'), ' 0031 2044 0034') ! self.assertRaises(TypeError, self.db.decomposition) ! self.assertRaises(TypeError, self.db.decomposition, u'xx') ! def test_mirrored(self): ! self.assertEqual(self.db.mirrored(u'\uFFFE'), 0) ! self.assertEqual(self.db.mirrored(u'a'), 0) ! self.assertEqual(self.db.mirrored(u'\u2201'), 1) ! ! self.assertRaises(TypeError, self.db.mirrored) ! self.assertRaises(TypeError, self.db.mirrored, u'xx') ! ! def test_combining(self): ! self.assertEqual(self.db.combining(u'\uFFFE'), 0) ! self.assertEqual(self.db.combining(u'a'), 0) ! self.assertEqual(self.db.combining(u'\u20e1'), 230) ! ! self.assertRaises(TypeError, self.db.combining) ! self.assertRaises(TypeError, self.db.combining, u'xx') ! ! def test_normalize(self): ! self.assertRaises(TypeError, self.db.normalize) ! self.assertRaises(ValueError, self.db.normalize, 'unknown', u'xx') ! # The rest can be found in test_normalization.py ! # which requires an external file. ! ! ! class UnicodeMiscTest(UnicodeDatabaseTest): ! ! def test_decimal_numeric_consistent(self): ! # Test that decimal and numeric are consistent, ! # i.e. if a character has a decimal value, ! # it's numeric value should be the same. ! count = 0 ! for i in xrange(0x10000): ! c = unichr(i) ! dec = self.db.decimal(c, -1) ! if dec != -1: ! self.assertEqual(dec, self.db.numeric(c)) ! count += 1 ! self.assert_(count >= 10) # should have tested at least the ASCII digits ! ! def test_digit_numeric_consistent(self): ! # Test that digit and numeric are consistent, ! # i.e. if a character has a digit value, ! # it's numeric value should be the same. ! count = 0 ! for i in xrange(0x10000): ! c = unichr(i) ! dec = self.db.digit(c, -1) ! if dec != -1: ! self.assertEqual(dec, self.db.numeric(c)) ! count += 1 ! self.assert_(count >= 10) # should have tested at least the ASCII digits ! ! def test_main(): ! suite = unittest.TestSuite() ! suite.addTest(unittest.makeSuite(UnicodeMiscTest)) ! suite.addTest(unittest.makeSuite(UnicodeMethodsTest)) ! suite.addTest(unittest.makeSuite(UnicodeFunctionsTest)) ! test.test_support.run_suite(suite) ! ! if __name__ == "__main__": ! test_main() From gvanrossum@users.sourceforge.net Wed Feb 26 14:58:15 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Wed, 26 Feb 2003 06:58:15 -0800 Subject: [Python-checkins] python/nondist/peps pep-0283.txt,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/peps In directory sc8-pr-cvs1:/tmp/cvs-serv22792 Modified Files: pep-0283.txt Log Message: Add some hopeful PEPS. Index: pep-0283.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0283.txt,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** pep-0283.txt 19 Feb 2003 19:36:27 -0000 1.31 --- pep-0283.txt 26 Feb 2003 14:58:11 -0000 1.32 *************** *** 162,166 **** longer certain this is easy or even right.) ! - The import lock could use some redesign. (SF 683658.) --- 162,175 ---- longer certain this is easy or even right.) ! - The import lock could use some redesign. (SF 683658.) ! ! - PEP 311 (Simplified GIL Acquisition for Extensions, by Mark ! Hammond) may be ready in time to get it in. ! ! - PEP 305 (CSV File API, by Skip Montanaro et al.) might go in; I ! don't know what the authors' plans are. ! ! - PEP 304 (Controlling Generation of Bytecode Files by Montanaro) ! might go in; I've lost track of the status. From jvr@users.sourceforge.net Wed Feb 26 15:28:20 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Wed, 26 Feb 2003 07:28:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac aetools.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv3375/Lib/plat-mac Modified Files: aetools.py Log Message: use bare raise so you get the original tb Index: aetools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/aetools.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** aetools.py 30 Dec 2002 22:04:20 -0000 1.1 --- aetools.py 26 Feb 2003 15:28:17 -0000 1.2 *************** *** 84,88 **** except (AE.Error, MacOS.Error), msg: if msg[0] != -1701 and msg[0] != -1704: ! raise sys.exc_type, sys.exc_value continue attributes[key] = unpack(desc, formodulename) --- 84,88 ---- except (AE.Error, MacOS.Error), msg: if msg[0] != -1701 and msg[0] != -1704: ! raise continue attributes[key] = unpack(desc, formodulename) From rhettinger@users.sourceforge.net Wed Feb 26 18:11:56 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Wed, 26 Feb 2003 10:11:56 -0800 Subject: [Python-checkins] python/dist/src/Python ceval.c,2.350,2.351 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv2864 Modified Files: ceval.c Log Message: Micro-optimizations. * List/Tuple checkexact is faster for the common case. * Testing for Py_True and Py_False can be inlined for faster looping. Index: ceval.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/ceval.c,v retrieving revision 2.350 retrieving revision 2.351 diff -C2 -d -r2.350 -r2.351 *** ceval.c 19 Feb 2003 15:53:16 -0000 2.350 --- ceval.c 26 Feb 2003 18:11:50 -0000 2.351 *************** *** 1656,1660 **** case UNPACK_SEQUENCE: v = POP(); ! if (PyTuple_Check(v)) { if (PyTuple_Size(v) != oparg) { PyErr_SetString(PyExc_ValueError, --- 1656,1660 ---- case UNPACK_SEQUENCE: v = POP(); ! if (PyTuple_CheckExact(v)) { if (PyTuple_Size(v) != oparg) { PyErr_SetString(PyExc_ValueError, *************** *** 1670,1674 **** } } ! else if (PyList_Check(v)) { if (PyList_Size(v) != oparg) { PyErr_SetString(PyExc_ValueError, --- 1670,1674 ---- } } ! else if (PyList_CheckExact(v)) { if (PyList_Size(v) != oparg) { PyErr_SetString(PyExc_ValueError, *************** *** 1976,1980 **** case JUMP_IF_FALSE: ! err = PyObject_IsTrue(TOP()); if (err > 0) err = 0; --- 1976,1987 ---- case JUMP_IF_FALSE: ! w = TOP(); ! if (w == Py_True) ! continue; ! if (w == Py_False) { ! JUMPBY(oparg); ! continue; ! } ! err = PyObject_IsTrue(w); if (err > 0) err = 0; *************** *** 1986,1990 **** case JUMP_IF_TRUE: ! err = PyObject_IsTrue(TOP()); if (err > 0) { err = 0; --- 1993,2004 ---- case JUMP_IF_TRUE: ! w = TOP(); ! if (w == Py_False) ! continue; ! if (w == Py_True) { ! JUMPBY(oparg); ! continue; ! } ! err = PyObject_IsTrue(w); if (err > 0) { err = 0; From akuchling@users.sourceforge.net Wed Feb 26 18:52:14 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 26 Feb 2003 10:52:14 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils ccompiler.py,1.55,1.56 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv28481 Modified Files: ccompiler.py Log Message: [Bug #668662] Patch from Pearu Pearson: if a C source file is specified with an absolute path, the object file is also written to an absolute path. The patch drops the drive and leading '/' from the source path, so a path like /path/to/foo.c results in an object file like build/temp.i686linux/path/to/foo.o. Index: ccompiler.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/ccompiler.py,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** ccompiler.py 29 Dec 2002 17:00:57 -0000 1.55 --- ccompiler.py 26 Feb 2003 18:52:07 -0000 1.56 *************** *** 933,936 **** --- 933,938 ---- for src_name in source_filenames: base, ext = os.path.splitext(src_name) + base = os.path.splitdrive(base)[1] # Chop off the drive + base = base[os.path.isabs(base):] # If abs, chop off leading / if ext not in self.src_extensions: raise UnknownFileError, \ From akuchling@users.sourceforge.net Wed Feb 26 18:58:49 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 26 Feb 2003 10:58:49 -0800 Subject: [Python-checkins] python/dist/src/Doc/dist dist.tex,1.49,1.50 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/dist In directory sc8-pr-cvs1:/tmp/cvs-serv1966 Modified Files: dist.tex Log Message: [Bug #693474, reported by Stuart Bishop] Fix errors in the list of setup() arguments Index: dist.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/dist/dist.tex,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** dist.tex 21 Feb 2003 02:47:09 -0000 1.49 --- dist.tex 26 Feb 2003 18:58:46 -0000 1.50 *************** *** 696,706 **** \lineiii{maintainer}{package maintainer's name}{(2)} \lineiii{maintainer_email}{email address of the package maintainer}{(2)} ! \lineiii{home_page}{url}{(1)} \lineiii{license}{the terms the package is released under}{} \lineiii{description}{a short, summary description of the package}{} \lineiii{long_description}{a longer description of the package}{} \lineiii{keywords}{some keywords appropriate to the package}{} ! \lineiii{platform}{a list of the target platforms}{} ! \lineiii{classifiers}{a list of Trove classifiers}{(3)} \end{tableiii} --- 696,708 ---- \lineiii{maintainer}{package maintainer's name}{(2)} \lineiii{maintainer_email}{email address of the package maintainer}{(2)} ! \lineiii{url}{URL of the package's home page}{(1)} \lineiii{license}{the terms the package is released under}{} \lineiii{description}{a short, summary description of the package}{} \lineiii{long_description}{a longer description of the package}{} \lineiii{keywords}{some keywords appropriate to the package}{} ! \lineiii{platforms}{a list of the target platforms}{} ! \lineiii{classifiers}{a list of Trove classifiers}{(3),(4)} ! \lineiii{download_url}{a single URL containing the download location ! for this version of the package}{(3)} \end{tableiii} *************** *** 710,715 **** \item[(2)] either the author or the maintainer must be nominated \item[(3)] should not be used if your package is to be compatible with ! Python versions prior to 2.2.3 or 2.3. The list is available from the ! PyPI website. \end{description} --- 712,718 ---- \item[(2)] either the author or the maintainer must be nominated \item[(3)] should not be used if your package is to be compatible with ! Python versions prior to 2.2.3 or 2.3. ! \item[(4)] The list of classifiers is available from the ! PyPI website (\url{http://www.python.org/pypi}). \end{description} From akuchling@users.sourceforge.net Wed Feb 26 19:00:59 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 26 Feb 2003 11:00:59 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.124,1.125 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv4035 Modified Files: whatsnew23.tex Log Message: Update PyPI link Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.124 retrieving revision 1.125 diff -C2 -d -r1.124 -r1.125 *** whatsnew23.tex 19 Feb 2003 16:08:08 -0000 1.124 --- whatsnew23.tex 26 Feb 2003 19:00:52 -0000 1.125 *************** *** 717,725 **** Running \code{python setup.py register} will collect the metadata describing a package, such as its name, version, maintainer, ! description, \&c., and send it to a central catalog server. ! Currently the catalog can be browsed at ! \url{http://www.amk.ca/cgi-bin/pypi.cgi}, but it will move to ! some hostname in the \code{python.org} domain before the final version ! of 2.3 is released. To make the catalog a bit more useful, a new optional --- 717,722 ---- Running \code{python setup.py register} will collect the metadata describing a package, such as its name, version, maintainer, ! description, \&c., and send it to a central catalog server. The ! catalog is available from \url{http://www.python.org/pypi}. To make the catalog a bit more useful, a new optional From fdrake@users.sourceforge.net Wed Feb 26 19:02:44 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Wed, 26 Feb 2003 11:02:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv5478 Modified Files: libcsv.tex Log Message: - general markup review - moved "See also" section to a better spot Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** libcsv.tex 14 Feb 2003 06:25:44 -0000 1.8 --- libcsv.tex 26 Feb 2003 19:02:42 -0000 1.9 *************** *** 27,58 **** The \module{csv} module's \class{reader} and \class{writer} objects read and write sequences. Programmers can also read and write data in dictionary ! form using the \class{DictReader} and {}\class{DictWriter} classes. \note{The first version of the \module{csv} module doesn't support Unicode ! input. Also, there are currently some issues regarding ASCII NUL ! characters. Accordingly, all input should generally be plain ASCII to be safe. These restrictions will be removed in the future.} \subsection{Module Contents} ! The \module{csv} module defines the following functions. ! \begin{funcdesc}{reader}{iterable\optional{, dialect="excel"} ! \optional{, fmtparam}} Return a reader object which will iterate over lines in the given ! {}\var{csvfile}. An optional \var{dialect} parameter can be given which is ! used to define a set of parameters specific to a particular CSV dialect. ! The other optional \var{fmtparam} keyword arguments can be given to override ! individual formatting parameters in the current dialect. For more ! information about the dialect and formatting parameters, see section ! {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of ! these parameters. All data read are returned as strings. \end{funcdesc} ! \begin{funcdesc}{writer}{fileobj\optional{, dialect="excel"} ! \optional{, fmtparam}} ! Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. An optional \var{dialect} --- 27,65 ---- The \module{csv} module's \class{reader} and \class{writer} objects read and write sequences. Programmers can also read and write data in dictionary ! form using the \class{DictReader} and \class{DictWriter} classes. \note{The first version of the \module{csv} module doesn't support Unicode ! input. Also, there are currently some issues regarding \ASCII{} NUL ! characters. Accordingly, all input should generally be plain \ASCII{} to be safe. These restrictions will be removed in the future.} + \begin{seealso} + % \seemodule{array}{Arrays of uniformly types numeric values.} + \seepep{305}{CSV File API} + {The Python Enhancement Proposal which proposed this addition + to Python.} + \end{seealso} + \subsection{Module Contents} ! The \module{csv} module defines the following functions: ! \begin{funcdesc}{reader}{iterable\optional{, ! dialect=\code{'excel'}\optional{, fmtparam}}} Return a reader object which will iterate over lines in the given ! \var{csvfile}. An optional \var{dialect} parameter can be given ! which is used to define a set of parameters specific to a particular ! CSV dialect. The other optional \var{fmtparam} keyword arguments can ! be given to override individual formatting parameters in the current ! dialect. For more information about the dialect and formatting ! parameters, see section~\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. All data read are ! returned as strings. \end{funcdesc} ! \begin{funcdesc}{writer}{fileobj\optional{, ! dialect=\code{'excel'}\optional{, fmtparam}}} Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. An optional \var{dialect} *************** *** 61,72 **** arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting ! parameters, see section {}\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. To make it as easy as possible to interface with modules which implement the DB API, the value ! {}\constant{None} is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a ! {}\code{cursor.fetch*()} call. All other non-string data are stringified ! with \function{str} before being written. \end{funcdesc} --- 68,79 ---- arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting ! parameters, see section~\ref{fmt-params}, ``Dialects and Formatting Parameters'' for details of these parameters. To make it as easy as possible to interface with modules which implement the DB API, the value ! \constant{None} is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a ! \code{cursor.fetch*()} call. All other non-string data are stringified ! with \function{str()} before being written. \end{funcdesc} *************** *** 92,104 **** ! The \module{csv} module defines the following classes. ! \begin{classdesc}{DictReader}{fileobj, fieldnames ! \optional{, restkey=None} ! \optional{, restval=None} ! \optional{, dialect="excel"} ! \optional{, fmtparam}} Create an object which operates like a regular reader but maps the ! information read into a dict whose keys are given by the {}\var{fieldnames} parameter. If the row read has fewer fields than the fieldnames sequence, the value of \var{restval} will be used as the default value. If the row --- 99,109 ---- ! The \module{csv} module defines the following classes: ! \begin{classdesc}{DictReader}{fileobj, fieldnames\optional{, ! restkey\optional{, restval\optional{, ! dialect=\code{'excel'}\optional{, fmtparam}}}}} Create an object which operates like a regular reader but maps the ! information read into a dict whose keys are given by the \var{fieldnames} parameter. If the row read has fewer fields than the fieldnames sequence, the value of \var{restval} will be used as the default value. If the row *************** *** 111,138 **** ! \begin{classdesc}{DictWriter}{fileobj, fieldnames ! \optional{, restval=""} ! \optional{, extrasaction="raise"} ! \optional{, dialect="excel"} ! \optional{, fmtparam}} Create an object which operates like a regular writer but maps dictionaries onto output rows. The \var{fieldnames} parameter identifies the order in ! which values in the dictionary passed to the \method{writerow} method are written to the \var{fileobj}. The optional \var{restval} parameter specifies the value to be written if the dictionary is missing a key in ! {}\var{fieldnames}. If the dictionary passed to the \method{writerow} ! method contains a key not found in {}\var{fieldnames}, the optional ! {}\var{extrasaction} parameter indicates what action to take. If it is set ! to \code{"raise"} a {}\exception{ValueError} is raised. If it is set to ! {}\code{"ignore"}, extra values in the dictionary are ignored. All other parameters are interpreted as for regular writers. \end{classdesc} ! \begin{classdesc}{Dialect}{} The \class{Dialect} class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific \class{reader} or \class{writer} instance. ! \end{classdesc} \begin{memberdesc}[string]{delimiter} --- 116,142 ---- ! \begin{classdesc}{DictWriter}{fileobj, fieldnames\optional{, ! restval=""\optional{, ! extrasaction=\code{'raise'}\optional{, ! dialect=\code{'excel'}\optional{, fmtparam}}}}} Create an object which operates like a regular writer but maps dictionaries onto output rows. The \var{fieldnames} parameter identifies the order in ! which values in the dictionary passed to the \method{writerow()} method are written to the \var{fileobj}. The optional \var{restval} parameter specifies the value to be written if the dictionary is missing a key in ! \var{fieldnames}. If the dictionary passed to the \method{writerow()} ! method contains a key not found in \var{fieldnames}, the optional ! \var{extrasaction} parameter indicates what action to take. If it is set ! to \code{'raise'} a \exception{ValueError} is raised. If it is set to ! \code{'ignore'}, extra values in the dictionary are ignored. All other parameters are interpreted as for regular writers. \end{classdesc} ! \begin{classdesc*}{Dialect}{} The \class{Dialect} class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific \class{reader} or \class{writer} instance. ! \end{classdesc*} \begin{memberdesc}[string]{delimiter} *************** *** 175,179 **** ! The \module{csv} module defines the following constants. \begin{datadesc}{QUOTE_ALWAYS} --- 179,183 ---- ! The \module{csv} module defines the following constants: \begin{datadesc}{QUOTE_ALWAYS} *************** *** 192,197 **** \begin{datadesc}{QUOTE_NONE} Instructs \class{writer} objects to never quote fields. When the current ! {}\var{delimiter} occurs in output data it is preceded by the current ! {}\var{escapechar} character. When \constant{QUOTE_NONE} is in effect, it is an error not to have a single-character \var{escapechar} defined, even if no data to be written contains the \var{delimiter} character. --- 196,201 ---- \begin{datadesc}{QUOTE_NONE} Instructs \class{writer} objects to never quote fields. When the current ! \var{delimiter} occurs in output data it is preceded by the current ! \var{escapechar} character. When \constant{QUOTE_NONE} is in effect, it is an error not to have a single-character \var{escapechar} defined, even if no data to be written contains the \var{delimiter} character. *************** *** 199,203 **** ! The \module{csv} module defines the following exception. \begin{excdesc}{Error} --- 203,207 ---- ! The \module{csv} module defines the following exception: \begin{excdesc}{Error} *************** *** 211,215 **** specific formatting parameters are grouped together into dialects. A dialect is a subclass of the \class{Dialect} class having a set of specific ! methods and a single \method{validate} method. When creating \class{reader} or \class{writer} objects, the programmer can specify a string or a subclass of the \class{Dialect} class as the dialect parameter. In addition to, or --- 215,219 ---- specific formatting parameters are grouped together into dialects. A dialect is a subclass of the \class{Dialect} class having a set of specific ! methods and a single \method{validate()} method. When creating \class{reader} or \class{writer} objects, the programmer can specify a string or a subclass of the \class{Dialect} class as the dialect parameter. In addition to, or *************** *** 222,226 **** \class{DictReader} and \var{reader} objects have the following public ! methods. \begin{methoddesc}{next}{} --- 226,230 ---- \class{DictReader} and \var{reader} objects have the following public ! methods: \begin{methoddesc}{next}{} *************** *** 233,237 **** \class{DictWriter} and \var{writer} objects have the following public ! methods. \begin{methoddesc}{writerow}{row} --- 237,241 ---- \class{DictWriter} and \var{writer} objects have the following public ! methods: \begin{methoddesc}{writerow}{row} *************** *** 248,252 **** \subsection{Examples} ! The \code{"hello world"} of csv reading is \begin{verbatim} --- 252,256 ---- \subsection{Examples} ! The ``Hello, world'' of csv reading is \begin{verbatim} *************** *** 263,269 **** writer.writerow(row) \end{verbatim} - - \begin{seealso} - % \seemodule{array}{Arrays of uniformly types numeric values.} - % \seepep{305}{CSV File API} - \end{seealso} --- 267,268 ---- From fdrake@users.sourceforge.net Wed Feb 26 19:25:22 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Wed, 26 Feb 2003 11:25:22 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv20420 Modified Files: libcsv.tex Log Message: Oops, need to add versioning information. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** libcsv.tex 26 Feb 2003 19:02:42 -0000 1.9 --- libcsv.tex 26 Feb 2003 19:25:16 -0000 1.10 *************** *** 4,7 **** --- 4,8 ---- \modulesynopsis{Write and read tabular data to and from delimited files.} + \versionadded{2.3} \index{csv} \indexii{data}{tabular} From fdrake@users.sourceforge.net Wed Feb 26 19:51:29 2003 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Wed, 26 Feb 2003 11:51:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.130,1.131 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6011 Modified Files: regrtest.py Log Message: The macfs, macostools, and plistlib should not be expected to run beyond Mac OS and Darwin. I'm not even sure they should be run on Darwin, but I'll let someone more knowledgable on that tell us. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.130 retrieving revision 1.131 diff -C2 -d -r1.130 -r1.131 *** regrtest.py 23 Feb 2003 22:56:58 -0000 1.130 --- regrtest.py 26 Feb 2003 19:51:23 -0000 1.131 *************** *** 567,570 **** --- 567,572 ---- test_largefile test_linuxaudiodev + test_macfs + test_macostools test_mhlib test_mpz *************** *** 572,575 **** --- 574,578 ---- test_openpty test_ossaudiodev + test_plistlib test_poll test_posix *************** *** 594,600 **** --- 597,606 ---- test_largefile test_linuxaudiodev + test_macfs + test_macostools test_nis test_ntpath test_ossaudiodev + test_plistlib test_socketserver test_sunaudiodev *************** *** 656,663 **** --- 662,672 ---- test_largefile test_linuxaudiodev + test_macfs + test_macostools test_minidom test_nis test_ntpath test_openpty + test_plistlib test_pyexpat test_sax *************** *** 678,685 **** --- 687,697 ---- test_largefile test_linuxaudiodev + test_macfs + test_macostools test_minidom test_nis test_ntpath test_openpty + test_plistlib test_pyexpat test_sax *************** *** 704,711 **** --- 716,726 ---- test_linuxaudiodev test_locale + test_macfs + test_macostools test_minidom test_nis test_ntpath test_openpty + test_plistlib test_pyexpat test_queue *************** *** 740,747 **** --- 755,765 ---- test_linuxaudiodev test_locale + test_macfs + test_macostools test_mmap test_nis test_ntpath test_openpty + test_plistlib test_poll test_popen2 *************** *** 800,805 **** --- 818,826 ---- test_imgfile test_linuxaudiodev + test_macfs + test_macostools test_mpz test_openpty + test_plistlib test_socketserver test_zipfile *************** *** 821,828 **** --- 842,852 ---- test_linuxaudiodev test_locale + test_macfs + test_macostools test_minidom test_nis test_ntpath test_openpty + test_plistlib test_pyexpat test_sax *************** *** 847,854 **** --- 871,881 ---- test_linuxaudiodev test_locale + test_macfs + test_macostools test_mhlib test_mmap test_mpz test_nis + test_plistlib test_poll test_popen2 *************** *** 872,878 **** --- 899,908 ---- test_linuxaudiodev test_locale + test_macfs + test_macostools test_mpz test_nis test_ossaudiodev + test_plistlib test_socketserver test_sunaudiodev *************** *** 895,898 **** --- 925,930 ---- test_largefile test_linuxaudiodev + test_macfs + test_macostools test_mhlib test_mmap *************** *** 900,903 **** --- 932,936 ---- test_openpty test_ossaudiodev + test_plistlib test_pty test_resource From montanaro@users.sourceforge.net Wed Feb 26 20:15:47 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 12:15:47 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv23815 Modified Files: libcsv.tex Log Message: make references to the input or output file-like object uniform Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** libcsv.tex 26 Feb 2003 19:25:16 -0000 1.10 --- libcsv.tex 26 Feb 2003 20:15:39 -0000 1.11 *************** *** 48,65 **** The \module{csv} module defines the following functions: ! \begin{funcdesc}{reader}{iterable\optional{, dialect=\code{'excel'}\optional{, fmtparam}}} Return a reader object which will iterate over lines in the given ! \var{csvfile}. An optional \var{dialect} parameter can be given ! which is used to define a set of parameters specific to a particular ! CSV dialect. The other optional \var{fmtparam} keyword arguments can ! be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting parameters, see section~\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. All data read are ! returned as strings. \end{funcdesc} ! \begin{funcdesc}{writer}{fileobj\optional{, dialect=\code{'excel'}\optional{, fmtparam}}} Return a writer object responsible for converting the user's data into --- 48,69 ---- The \module{csv} module defines the following functions: ! \begin{funcdesc}{reader}{csvfile\optional{, dialect=\code{'excel'}\optional{, fmtparam}}} Return a reader object which will iterate over lines in the given ! {}\var{csvfile}. \var{csvfile} can be any object which supports the ! iterator protocol and returns a string each time its \method{next} ! method is called. An optional \var{dialect} parameter can be given ! which is used to define a set of parameters specific to a particular CSV ! dialect. The other optional {}\var{fmtparam} keyword arguments can be ! given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting parameters, see section~\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. ! ! All data read are returned as strings. No automatic data type ! conversion is performed. \end{funcdesc} ! \begin{funcdesc}{writer}{csvfile\optional{, dialect=\code{'excel'}\optional{, fmtparam}}} Return a writer object responsible for converting the user's data into *************** *** 102,108 **** The \module{csv} module defines the following classes: ! \begin{classdesc}{DictReader}{fileobj, fieldnames\optional{, ! restkey\optional{, restval\optional{, ! dialect=\code{'excel'}\optional{, fmtparam}}}}} Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the \var{fieldnames} --- 106,114 ---- The \module{csv} module defines the following classes: ! \begin{classdesc}{DictReader}{csvfile, fieldnames\optional{, ! restkey=\code{None}\optional{, ! restval=\code{None}\optional{, ! dialect=\code{'excel'}\optional{, ! fmtparam}}}}} Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the \var{fieldnames} *************** *** 117,121 **** ! \begin{classdesc}{DictWriter}{fileobj, fieldnames\optional{, restval=""\optional{, extrasaction=\code{'raise'}\optional{, --- 123,127 ---- ! \begin{classdesc}{DictWriter}{csvfile, fieldnames\optional{, restval=""\optional{, extrasaction=\code{'raise'}\optional{, *************** *** 124,128 **** onto output rows. The \var{fieldnames} parameter identifies the order in which values in the dictionary passed to the \method{writerow()} method are ! written to the \var{fileobj}. The optional \var{restval} parameter specifies the value to be written if the dictionary is missing a key in \var{fieldnames}. If the dictionary passed to the \method{writerow()} --- 130,134 ---- onto output rows. The \var{fieldnames} parameter identifies the order in which values in the dictionary passed to the \method{writerow()} method are ! written to the \var{csvfile}. The optional \var{restval} parameter specifies the value to be written if the dictionary is missing a key in \var{fieldnames}. If the dictionary passed to the \method{writerow()} From montanaro@users.sourceforge.net Wed Feb 26 20:24:58 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 12:24:58 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv29689 Modified Files: libcsv.tex Log Message: nest Dialect class's data attribute descriptions within the class description. Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** libcsv.tex 26 Feb 2003 20:15:39 -0000 1.11 --- libcsv.tex 26 Feb 2003 20:24:53 -0000 1.12 *************** *** 144,149 **** The \class{Dialect} class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific ! \class{reader} or \class{writer} instance. ! \end{classdesc*} \begin{memberdesc}[string]{delimiter} --- 144,149 ---- The \class{Dialect} class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific ! \class{reader} or \class{writer} instance. Dialect objects support the ! following data attributes: \begin{memberdesc}[string]{delimiter} *************** *** 185,188 **** --- 185,189 ---- \end{memberdesc} + \end{classdesc*} The \module{csv} module defines the following constants: From montanaro@users.sourceforge.net Wed Feb 26 20:59:32 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 12:59:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv/test test_csv.py,1.34,1.35 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv/test In directory sc8-pr-cvs1:/tmp/cvs-serv23054 Modified Files: test_csv.py Log Message: add unit tests for dialect validity Index: test_csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/test/test_csv.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** test_csv.py 15 Feb 2003 00:52:11 -0000 1.34 --- test_csv.py 26 Feb 2003 20:59:29 -0000 1.35 *************** *** 460,466 **** --- 460,533 ---- self.assertEqual(fileobj.getvalue(), expected) + class TestDialectValidity(unittest.TestCase): + def test_quoting(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.quoting = None + self.assertRaises(csv.Error, mydialect) + + mydialect.quoting = csv.QUOTE_NONE + mydialect.escapechar = None + self.assertRaises(csv.Error, mydialect) + + mydialect.doublequote = True + mydialect.quoting = csv.QUOTE_ALL + mydialect.quotechar = '"' + d = mydialect() + + mydialect.quotechar = "''" + self.assertRaises(csv.Error, mydialect) + + mydialect.quotechar = 4 + self.assertRaises(csv.Error, mydialect) + + def test_delimiter(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.delimiter = ":::" + self.assertRaises(csv.Error, mydialect) + + mydialect.delimiter = 4 + self.assertRaises(csv.Error, mydialect) + + def test_lineterminator(self): + class mydialect(csv.Dialect): + delimiter = ";" + escapechar = '\\' + doublequote = False + skipinitialspace = True + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() + + mydialect.lineterminator = ":::" + d = mydialect() + + mydialect.lineterminator = 4 + self.assertRaises(csv.Error, mydialect) + + if not hasattr(sys, "gettotalrefcount"): print "*** skipping leakage tests ***" else: + class NUL: + def write(s, *args): + pass + writelines = write + class TestLeaks(unittest.TestCase): def test_create_read(self): *************** *** 482,486 **** delta = 0 lastrc = sys.gettotalrefcount() ! s = StringIO() for i in xrange(20): gc.collect() --- 549,553 ---- delta = 0 lastrc = sys.gettotalrefcount() ! s = NUL() for i in xrange(20): gc.collect() *************** *** 514,520 **** delta = 0 rows = [[1,2,3]]*5 - class NUL: - def write(s, *args): - pass s = NUL() lastrc = sys.gettotalrefcount() --- 581,584 ---- From montanaro@users.sourceforge.net Wed Feb 26 20:59:08 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 12:59:08 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv22815 Modified Files: csv.py Log Message: add several more validity checks Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** csv.py 12 Feb 2003 15:11:53 -0000 1.32 --- csv.py 26 Feb 2003 20:59:05 -0000 1.33 *************** *** 32,45 **** if not self._valid: errors.append("can't directly instantiate Dialect class") if self.delimiter is None: ! errors.append("delimiter not set") if self.quotechar is None: ! errors.append("quotechar not set") if self.lineterminator is None: errors.append("lineterminator not set") if self.doublequote not in (True, False): ! errors.append("doublequote setting must be True or False") if self.skipinitialspace not in (True, False): ! errors.append("skipinitialspace setting must be True or False") return errors --- 32,68 ---- if not self._valid: errors.append("can't directly instantiate Dialect class") + if self.delimiter is None: ! errors.append("delimiter character not set") ! elif (not isinstance(self.delimiter, str) or ! len(self.delimiter) > 1): ! errors.append("delimiter must be one-character string") ! if self.quotechar is None: ! if self.quoting != QUOTE_NONE: ! errors.append("quotechar not set") ! elif (not isinstance(self.quotechar, str) or ! len(self.quotechar) > 1): ! errors.append("quotechar must be one-character string") ! if self.lineterminator is None: errors.append("lineterminator not set") + elif not isinstance(self.lineterminator, str): + errors.append("lineterminator must be a string") + if self.doublequote not in (True, False): ! errors.append("doublequote parameter must be True or False") ! if self.skipinitialspace not in (True, False): ! errors.append("skipinitialspace parameter must be True or False") ! ! if self.quoting is None: ! errors.append("quoting parameter not set") ! elif self.quoting == QUOTE_NONE and self.escapechar is None: ! errors.append("escapechar must be set when quoting is QUOTE_NONE") ! ! if self.escapechar is None and self.doublequote == False: ! errors.append("escapechar must be set when doublequote is False") ! return errors From montanaro@users.sourceforge.net Wed Feb 26 22:12:00 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 14:12:00 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv libcsv.tex,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv25749 Modified Files: libcsv.tex Log Message: indicate that the dialect parameter to reader() and writer() factory functions may be an instance of a dialect or a string referring to a registered dialect Index: libcsv.tex =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/libcsv.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** libcsv.tex 26 Feb 2003 20:24:53 -0000 1.12 --- libcsv.tex 26 Feb 2003 22:11:56 -0000 1.13 *************** *** 55,59 **** method is called. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV ! dialect. The other optional {}\var{fmtparam} keyword arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting --- 55,61 ---- method is called. An optional \var{dialect} parameter can be given which is used to define a set of parameters specific to a particular CSV ! dialect. It may be an instance of a subclass of the \class{Dialect} ! class or one of the strings returned by the \function{list_dialects} ! function. The other optional {}\var{fmtparam} keyword arguments can be given to override individual formatting parameters in the current dialect. For more information about the dialect and formatting *************** *** 68,79 **** dialect=\code{'excel'}\optional{, fmtparam}}} Return a writer object responsible for converting the user's data into ! delimited strings on the given file-like object. An optional \var{dialect} ! parameter can be given which is used to define a set of parameters specific ! to a particular CSV dialect. The other optional \var{fmtparam} keyword ! arguments can be given to override individual formatting parameters in the ! current dialect. For more information about the dialect and formatting ! parameters, see section~\ref{fmt-params}, ``Dialects and Formatting ! Parameters'' for details of these parameters. To make it as easy as ! possible to interface with modules which implement the DB API, the value \constant{None} is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values --- 70,84 ---- dialect=\code{'excel'}\optional{, fmtparam}}} Return a writer object responsible for converting the user's data into ! delimited strings on the given file-like object. An optional ! {}\var{dialect} parameter can be given which is used to define a set of ! parameters specific to a particular CSV dialect. It may be an instance ! of a subclass of the \class{Dialect} class or one of the strings ! returned by the \function{list_dialects} function. The other optional ! {}\var{fmtparam} keyword arguments can be given to override individual ! formatting parameters in the current dialect. For more information ! about the dialect and formatting parameters, see ! section~\ref{fmt-params}, ``Dialects and Formatting Parameters'' for ! details of these parameters. To make it as easy as possible to ! interface with modules which implement the DB API, the value \constant{None} is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values From akuchling@users.sourceforge.net Wed Feb 26 22:26:11 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 26 Feb 2003 14:26:11 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils util.py,1.65.6.1,1.65.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv32054 Modified Files: Tag: release22-maint util.py Log Message: Backport rev. 1.73: Translate spaces in the machine name to underscores Index: util.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/util.py,v retrieving revision 1.65.6.1 retrieving revision 1.65.6.2 diff -C2 -d -r1.65.6.1 -r1.65.6.2 *** util.py 13 Aug 2002 17:49:18 -0000 1.65.6.1 --- util.py 26 Feb 2003 22:26:03 -0000 1.65.6.2 *************** *** 43,50 **** (osname, host, release, version, machine) = os.uname() ! # Convert the OS name to lowercase and remove '/' characters ! # (to accommodate BSD/OS) osname = string.lower(osname) osname = string.replace(osname, '/', '') if osname[:5] == "linux": --- 43,51 ---- (osname, host, release, version, machine) = os.uname() ! # Convert the OS name to lowercase, remove '/' characters ! # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = string.lower(osname) osname = string.replace(osname, '/', '') + machine = string.replace(machine, ' ', '_') if osname[:5] == "linux": From montanaro@users.sourceforge.net Wed Feb 26 22:33:53 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 26 Feb 2003 14:33:53 -0800 Subject: [Python-checkins] python/nondist/sandbox/csv csv.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/csv In directory sc8-pr-cvs1:/tmp/cvs-serv5422 Modified Files: csv.py Log Message: try to match behavior of the underlying C code (without actually looking at the code ;-) Index: csv.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/csv/csv.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** csv.py 26 Feb 2003 20:59:05 -0000 1.33 --- csv.py 26 Feb 2003 22:33:48 -0000 1.34 *************** *** 57,67 **** errors.append("skipinitialspace parameter must be True or False") if self.quoting is None: errors.append("quoting parameter not set") - elif self.quoting == QUOTE_NONE and self.escapechar is None: - errors.append("escapechar must be set when quoting is QUOTE_NONE") - - if self.escapechar is None and self.doublequote == False: - errors.append("escapechar must be set when doublequote is False") return errors --- 57,66 ---- errors.append("skipinitialspace parameter must be True or False") + if (not isinstance(self.escapechar, str) or + len(self.escapechar) > 1): + errors.append("escapechar must be one-character string") + if self.quoting is None: errors.append("quoting parameter not set") return errors From rhettinger@users.sourceforge.net Wed Feb 26 22:45:22 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Wed, 26 Feb 2003 14:45:22 -0800 Subject: [Python-checkins] python/dist/src/Lib httplib.py,1.71,1.72 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv8466 Modified Files: httplib.py Log Message: Module review: * Replaced "while 1" with "while True" * Rewrote read() and readline() for clarity and speed. * Replaced variable 'list' with 'hlist' * Used augmented assignment in two places. Index: httplib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/httplib.py,v retrieving revision 1.71 retrieving revision 1.72 diff -C2 -d -r1.71 -r1.72 *** httplib.py 25 Feb 2003 17:48:15 -0000 1.71 --- httplib.py 26 Feb 2003 22:45:18 -0000 1.72 *************** *** 140,144 **** self.dict = {} self.unixfrom = '' ! self.headers = list = [] self.status = '' headerseen = "" --- 140,144 ---- self.dict = {} self.unixfrom = '' ! self.headers = hlist = [] self.status = '' headerseen = "" *************** *** 149,153 **** elif self.seekable: tell = self.fp.tell ! while 1: if tell: try: --- 149,153 ---- elif self.seekable: tell = self.fp.tell ! while True: if tell: try: *************** *** 169,173 **** # for http and/or for repeating headers # It's a continuation line. ! list.append(line) self.addcontinue(headerseen, line.strip()) continue --- 169,173 ---- # for http and/or for repeating headers # It's a continuation line. ! hlist.append(line) self.addcontinue(headerseen, line.strip()) continue *************** *** 181,185 **** if headerseen: # It's a legal header line, save it. ! list.append(line) self.addheader(headerseen, line[len(headerseen)+1:].strip()) continue --- 181,185 ---- if headerseen: # It's a legal header line, save it. ! hlist.append(line) self.addheader(headerseen, line[len(headerseen)+1:].strip()) continue *************** *** 265,274 **** # read until we get a non-100 response ! while 1: version, status, reason = self._read_status() if status != 100: break # skip the header from the 100 response ! while 1: skip = self.fp.readline().strip() if not skip: --- 265,274 ---- # read until we get a non-100 response ! while True: version, status, reason = self._read_status() if status != 100: break # skip the header from the 100 response ! while True: skip = self.fp.readline().strip() if not skip: *************** *** 412,416 **** # XXX This accumulates chunks by repeated string concatenation, # which is not efficient as the number or size of chunks gets big. ! while 1: if chunk_left is None: line = self.fp.readline() --- 412,416 ---- # XXX This accumulates chunks by repeated string concatenation, # which is not efficient as the number or size of chunks gets big. ! while True: if chunk_left is None: line = self.fp.readline() *************** *** 442,446 **** # read and discard trailer up to the CRLF terminator ### note: we shouldn't have any trailers! ! while 1: line = self.fp.readline() if line == '\r\n': --- 442,446 ---- # read and discard trailer up to the CRLF terminator ### note: we shouldn't have any trailers! ! while True: line = self.fp.readline() if line == '\r\n': *************** *** 472,477 **** if not chunk: raise IncompleteRead(s) ! s = s + chunk ! amt = amt - len(chunk) return s --- 472,477 ---- if not chunk: raise IncompleteRead(s) ! s += chunk ! amt -= len(chunk) return s *************** *** 729,733 **** if body: self.putheader('Content-Length', str(len(body))) ! for hdr, value in headers.items(): self.putheader(hdr, value) self.endheaders() --- 729,733 ---- if body: self.putheader('Content-Length', str(len(body))) ! for hdr, value in headers.iteritems(): self.putheader(hdr, value) self.endheaders() *************** *** 841,845 **** buf = '' # put in a loop so that we retry on transient errors ! while 1: try: buf = self._ssl.read(self._bufsize) --- 841,845 ---- buf = '' # put in a loop so that we retry on transient errors ! while True: try: buf = self._ssl.read(self._bufsize) *************** *** 865,904 **** def read(self, size=None): L = [self._buf] - avail = len(self._buf) - while size is None or avail < size: - s = self._read() - if s == '': - break - L.append(s) - avail += len(s) - all = "".join(L) if size is None: self._buf = '' ! return all else: ! self._buf = all[size:] ! return all[:size] def readline(self): L = [self._buf] self._buf = '' ! while 1: ! i = L[-1].find("\n") ! if i >= 0: ! break ! s = self._read() ! if s == '': ! break L.append(s) ! if i == -1: ! # loop exited because there is no more data ! return "".join(L) ! else: ! all = "".join(L) ! # XXX could do enough bookkeeping not to do a 2nd search ! i = all.find("\n") + 1 ! line = all[:i] ! self._buf = all[i:] ! return line class FakeSocket(SharedSocketClient): --- 865,894 ---- def read(self, size=None): L = [self._buf] if size is None: self._buf = '' ! for s in iter(self._read, ""): ! L.append(s) ! return "".join(L) else: ! avail = len(self._buf) ! for s in iter(self._read, ""): ! L.append(s) ! avail += len(s) ! if avail >= size: ! all = "".join(L) ! self._buf = all[size:] ! return all[:size] def readline(self): L = [self._buf] self._buf = '' ! for s in iter(self._read, ""): L.append(s) ! if "\n" in s: ! i = s.find("\n") + 1 ! self._buf = s[i:] ! L[-1] = s[:i] ! break ! return "".join(L) class FakeSocket(SharedSocketClient): From rhettinger@users.sourceforge.net Thu Feb 27 00:05:37 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Wed, 26 Feb 2003 16:05:37 -0800 Subject: [Python-checkins] python/dist/src/Lib filecmp.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv10274 Modified Files: filecmp.py Log Message: Module review: * Changed variable name from 'list' to 'flist'. * Replaced "while 1" with "while True". * Replaced if/elif/elif/elif structure with a shorter and faster dispatch dictionary that maps attrs to methods. * Simplified and sped comparison logic by using ifilter, ifilterfalse, and dict.fromkeys. * Used True and False rather than 1 and 0. Index: filecmp.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/filecmp.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** filecmp.py 6 Feb 2003 19:38:45 -0000 1.15 --- filecmp.py 27 Feb 2003 00:05:31 -0000 1.16 *************** *** 13,16 **** --- 13,17 ---- import stat import warnings + from itertools import ifilter, ifilterfalse __all__ = ["cmp","dircmp","cmpfiles"] *************** *** 70,80 **** fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') ! while 1: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if b1 != b2: ! return 0 if not b1: ! return 1 # Directory comparison class. --- 71,81 ---- fp1 = open(f1, 'rb') fp2 = open(f2, 'rb') ! while True: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) if b1 != b2: ! return False if not b1: ! return True # Directory comparison class. *************** *** 134,177 **** self.right_list.sort() - __p4_attrs = ('subdirs',) - __p3_attrs = ('same_files', 'diff_files', 'funny_files') - __p2_attrs = ('common_dirs', 'common_files', 'common_funny') - __p1_attrs = ('common', 'left_only', 'right_only') - __p0_attrs = ('left_list', 'right_list') - - def __getattr__(self, attr): - if attr in self.__p4_attrs: - self.phase4() - elif attr in self.__p3_attrs: - self.phase3() - elif attr in self.__p2_attrs: - self.phase2() - elif attr in self.__p1_attrs: - self.phase1() - elif attr in self.__p0_attrs: - self.phase0() - else: - raise AttributeError, attr - return getattr(self, attr) - def phase1(self): # Compute common names ! a_only, b_only = [], [] ! common = {} ! b = {} ! for fnm in self.right_list: ! b[fnm] = 1 ! for x in self.left_list: ! if b.get(x, 0): ! common[x] = 1 ! else: ! a_only.append(x) ! for x in self.right_list: ! if common.get(x, 0): ! pass ! else: ! b_only.append(x) self.common = common.keys() - self.left_only = a_only - self.right_only = b_only def phase2(self): # Distinguish files, directories, funnies --- 135,144 ---- self.right_list.sort() def phase1(self): # Compute common names ! b = dict.fromkeys(self.right_list) ! common = dict.fromkeys(ifilter(b.has_key, self.left_list)) ! self.left_only = list(ifilterfalse(common.has_key, self.left_list)) ! self.right_only = list(ifilterfalse(common.has_key, self.right_list)) self.common = common.keys() def phase2(self): # Distinguish files, directories, funnies *************** *** 266,269 **** --- 233,247 ---- sd.report_full_closure() + methodmap = dict(subdirs=phase4, + same_files=phase3, diff_files=phase3, funny_files=phase3, + common_dirs = phase2, common_files=phase2, common_funny=phase2, + common=phase1, left_only=phase1, right_only=phase1, + left_list=phase0, right_list=phase0) + + def __getattr__(self, attr): + if attr not in self.methodmap: + raise AttributeError, attr + self.methodmap[attr](self) + return getattr(self, attr) def cmpfiles(a, b, common, shallow=1, use_statcache=None): *************** *** 298,302 **** # 2 for funny cases (can't stat, etc.) # ! def _cmp(a, b, sh): try: return not abs(cmp(a, b, sh)) --- 276,280 ---- # 2 for funny cases (can't stat, etc.) # ! def _cmp(a, b, sh, abs=abs, cmp=cmp): try: return not abs(cmp(a, b, sh)) *************** *** 307,315 **** # Return a copy with items that occur in skip removed. # ! def _filter(list, skip): ! result = [] ! for item in list: ! if item not in skip: result.append(item) ! return result --- 285,290 ---- # Return a copy with items that occur in skip removed. # ! def _filter(flist, skip): ! return list(ifilterfalse(skip.__contains__, flist)) From mhammond@users.sourceforge.net Thu Feb 27 06:59:13 2003 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Wed, 26 Feb 2003 22:59:13 -0800 Subject: [Python-checkins] python/dist/src/Tools/webchecker webchecker.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/webchecker In directory sc8-pr-cvs1:/tmp/cvs-serv13525 Modified Files: webchecker.py Log Message: When bad HTML is encountered, ignore the page rather than failing with a traceback. Index: webchecker.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/webchecker/webchecker.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** webchecker.py 12 Nov 2002 22:19:34 -0000 1.29 --- webchecker.py 27 Feb 2003 06:59:10 -0000 1.30 *************** *** 401,405 **** self.markdone(url_pair) return ! page = self.getpage(url_pair) if page: # Store the page which corresponds to this URL. --- 401,413 ---- self.markdone(url_pair) return ! try: ! page = self.getpage(url_pair) ! except sgmllib.SGMLParseError, msg: ! msg = self.sanitize(msg) ! self.note(0, "Error parsing %s: %s", ! self.format_url(url_pair), msg) ! # Dont actually mark the URL as bad - it exists, just ! # we can't parse it! ! page = None if page: # Store the page which corresponds to this URL. From mwh@users.sourceforge.net Thu Feb 27 14:50:39 2003 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 27 Feb 2003 06:50:39 -0800 Subject: [Python-checkins] python/dist/src/Python ceval.c,2.351,2.352 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv5999 Modified Files: ceval.c Log Message: In the process of adding all the extended slice support I attempted to change _PyEval_SliceIndex to round massively negative longs up to -INT_MAX, instead of 0 but botched it. Get it right. Thx to Armin for the report. Index: ceval.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/ceval.c,v retrieving revision 2.351 retrieving revision 2.352 diff -C2 -d -r2.351 -r2.352 *** ceval.c 26 Feb 2003 18:11:50 -0000 2.351 --- ceval.c 27 Feb 2003 14:50:34 -0000 2.352 *************** *** 3615,3620 **** /* It's an overflow error, so we need to check the sign of the long integer, ! set the value to INT_MAX or 0, and clear ! the error. */ /* Create a long integer with a value of 0 */ --- 3615,3620 ---- /* It's an overflow error, so we need to check the sign of the long integer, ! set the value to INT_MAX or -INT_MAX, ! and clear the error. */ /* Create a long integer with a value of 0 */ *************** *** 3629,3636 **** if (cmp < 0) return 0; ! else if (cmp > 0) x = INT_MAX; else ! x = 0; } } else { --- 3629,3636 ---- if (cmp < 0) return 0; ! else if (cmp) x = INT_MAX; else ! x = -INT_MAX; } } else { From gvanrossum@users.sourceforge.net Thu Feb 27 18:39:22 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 10:39:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_zlib.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv26116 Modified Files: test_zlib.py Log Message: Use floor division (//). Index: test_zlib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_zlib.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** test_zlib.py 19 Feb 2003 02:35:06 -0000 1.21 --- test_zlib.py 27 Feb 2003 18:39:18 -0000 1.22 *************** *** 233,237 **** cb = combuf while cb: ! #max_length = 1 + len(cb)/10 chunk = dco.decompress(cb, dcx) self.failIf(len(chunk) > dcx, --- 233,237 ---- cb = combuf while cb: ! #max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, dcx) self.failIf(len(chunk) > dcx, *************** *** 269,273 **** cb = combuf while cb: ! max_length = 1 + len(cb)/10 chunk = dco.decompress(cb, max_length) self.failIf(len(chunk) > max_length, --- 269,273 ---- cb = combuf while cb: ! max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, max_length) self.failIf(len(chunk) > max_length, *************** *** 296,300 **** cb = combuf while cb: ! max_length = 1 + len(cb)/10 chunk = dco.decompress(cb, max_length) self.failIf(len(chunk) > max_length, --- 296,300 ---- cb = combuf while cb: ! max_length = 1 + len(cb)//10 chunk = dco.decompress(cb, max_length) self.failIf(len(chunk) > max_length, From gvanrossum@users.sourceforge.net Thu Feb 27 20:04:23 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:04:23 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.185,1.186 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv32236 Modified Files: test_descr.py Log Message: Use floor division (// and __[r]floordiv__ in right-dispatch test. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.185 retrieving revision 1.186 diff -C2 -d -r1.185 -r1.186 *** test_descr.py 19 Feb 2003 02:35:05 -0000 1.185 --- test_descr.py 27 Feb 2003 20:04:19 -0000 1.186 *************** *** 3679,3711 **** class B(int): ! def __div__(self, other): ! return "B.__div__" ! def __rdiv__(self, other): ! return "B.__rdiv__" ! vereq(B(1) / 1, "B.__div__") ! vereq(1 / B(1), "B.__rdiv__") # Case 2: subclass of object; this is just the baseline for case 3 class C(object): ! def __div__(self, other): ! return "C.__div__" ! def __rdiv__(self, other): ! return "C.__rdiv__" ! vereq(C() / 1, "C.__div__") ! vereq(1 / C(), "C.__rdiv__") # Case 3: subclass of new-style class; here it gets interesting class D(C): ! def __div__(self, other): ! return "D.__div__" ! def __rdiv__(self, other): ! return "D.__rdiv__" ! vereq(D() / C(), "D.__div__") ! vereq(C() / D(), "D.__rdiv__") # Case 4: this didn't work right in 2.2.2 and 2.3a1 --- 3679,3711 ---- class B(int): ! def __floordiv__(self, other): ! return "B.__floordiv__" ! def __rfloordiv__(self, other): ! return "B.__rfloordiv__" ! vereq(B(1) // 1, "B.__floordiv__") ! vereq(1 // B(1), "B.__rfloordiv__") # Case 2: subclass of object; this is just the baseline for case 3 class C(object): ! def __floordiv__(self, other): ! return "C.__floordiv__" ! def __rfloordiv__(self, other): ! return "C.__rfloordiv__" ! vereq(C() // 1, "C.__floordiv__") ! vereq(1 // C(), "C.__rfloordiv__") # Case 3: subclass of new-style class; here it gets interesting class D(C): ! def __floordiv__(self, other): ! return "D.__floordiv__" ! def __rfloordiv__(self, other): ! return "D.__rfloordiv__" ! vereq(D() // C(), "D.__floordiv__") ! vereq(C() // D(), "D.__rfloordiv__") # Case 4: this didn't work right in 2.2.2 and 2.3a1 *************** *** 3714,3723 **** pass ! vereq(E.__rdiv__, C.__rdiv__) ! vereq(E() / 1, "C.__div__") ! vereq(1 / E(), "C.__rdiv__") ! vereq(E() / C(), "C.__div__") ! vereq(C() / E(), "C.__div__") # This one would fail def dict_type_with_metaclass(): --- 3714,3723 ---- pass ! vereq(E.__rfloordiv__, C.__rfloordiv__) ! vereq(E() // 1, "C.__floordiv__") ! vereq(1 // E(), "C.__rfloordiv__") ! vereq(E() // C(), "C.__floordiv__") ! vereq(C() // E(), "C.__floordiv__") # This one would fail def dict_type_with_metaclass(): From gvanrossum@users.sourceforge.net Thu Feb 27 20:15:24 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:15:24 -0800 Subject: [Python-checkins] python/dist/src/Lib/logging __init__.py,1.6,1.7 config.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/logging In directory sc8-pr-cvs1:/tmp/cvs-serv3136/logging Modified Files: __init__.py config.py Log Message: Get rid of many apply() calls. Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/__init__.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** __init__.py 21 Feb 2003 22:29:45 -0000 1.6 --- __init__.py 27 Feb 2003 20:14:47 -0000 1.7 *************** *** 875,879 **** return if DEBUG >= self.getEffectiveLevel(): ! apply(self._log, (DEBUG, msg, args), kwargs) def info(self, msg, *args, **kwargs): --- 875,879 ---- return if DEBUG >= self.getEffectiveLevel(): ! self._log(DEBUG, msg, args, **kwargs) def info(self, msg, *args, **kwargs): *************** *** 889,893 **** return if INFO >= self.getEffectiveLevel(): ! apply(self._log, (INFO, msg, args), kwargs) def warning(self, msg, *args, **kwargs): --- 889,893 ---- return if INFO >= self.getEffectiveLevel(): ! self._log(INFO, msg, args, **kwargs) def warning(self, msg, *args, **kwargs): *************** *** 903,907 **** return if self.isEnabledFor(WARNING): ! apply(self._log, (WARNING, msg, args), kwargs) warn = warning --- 903,907 ---- return if self.isEnabledFor(WARNING): ! self._log(WARNING, msg, args, **kwargs) warn = warning *************** *** 919,923 **** return if self.isEnabledFor(ERROR): ! apply(self._log, (ERROR, msg, args), kwargs) def exception(self, msg, *args): --- 919,923 ---- return if self.isEnabledFor(ERROR): ! self._log(ERROR, msg, args, **kwargs) def exception(self, msg, *args): *************** *** 925,929 **** Convenience method for logging an ERROR with exception information. """ ! apply(self.error, (msg,) + args, {'exc_info': 1}) def critical(self, msg, *args, **kwargs): --- 925,929 ---- Convenience method for logging an ERROR with exception information. """ ! self.error(msg, exc_info=1, *args) def critical(self, msg, *args, **kwargs): *************** *** 939,943 **** return if CRITICAL >= self.getEffectiveLevel(): ! apply(self._log, (CRITICAL, msg, args), kwargs) fatal = critical --- 939,943 ---- return if CRITICAL >= self.getEffectiveLevel(): ! self._log(CRITICAL, msg, args, **kwargs) fatal = critical *************** *** 955,959 **** return if self.isEnabledFor(level): ! apply(self._log, (level, msg, args), kwargs) def findCaller(self): --- 955,959 ---- return if self.isEnabledFor(level): ! self._log(level, msg, args, **kwargs) def findCaller(self): *************** *** 1132,1136 **** if len(root.handlers) == 0: basicConfig() ! apply(root.critical, (msg,)+args, kwargs) fatal = critical --- 1132,1136 ---- if len(root.handlers) == 0: basicConfig() ! root.critical(msg, *args, **kwargs) fatal = critical *************** *** 1142,1146 **** if len(root.handlers) == 0: basicConfig() ! apply(root.error, (msg,)+args, kwargs) def exception(msg, *args): --- 1142,1146 ---- if len(root.handlers) == 0: basicConfig() ! root.error(msg, *args, **kwargs) def exception(msg, *args): *************** *** 1149,1153 **** with exception information. """ ! apply(error, (msg,)+args, {'exc_info': 1}) def warning(msg, *args, **kwargs): --- 1149,1153 ---- with exception information. """ ! error(msg, exc_info=1, *args) def warning(msg, *args, **kwargs): *************** *** 1157,1161 **** if len(root.handlers) == 0: basicConfig() ! apply(root.warning, (msg,)+args, kwargs) warn = warning --- 1157,1161 ---- if len(root.handlers) == 0: basicConfig() ! root.warning(msg, *args, **kwargs) warn = warning *************** *** 1167,1171 **** if len(root.handlers) == 0: basicConfig() ! apply(root.info, (msg,)+args, kwargs) def debug(msg, *args, **kwargs): --- 1167,1171 ---- if len(root.handlers) == 0: basicConfig() ! root.info(msg, *args, **kwargs) def debug(msg, *args, **kwargs): *************** *** 1175,1179 **** if len(root.handlers) == 0: basicConfig() ! apply(root.debug, (msg,)+args, kwargs) def disable(level): --- 1175,1179 ---- if len(root.handlers) == 0: basicConfig() ! root.debug(msg, *args, **kwargs) def disable(level): Index: config.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/logging/config.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** config.py 20 Dec 2002 01:54:21 -0000 1.5 --- config.py 27 Feb 2003 20:14:48 -0000 1.6 *************** *** 103,107 **** args = cp.get(sectname, "args") args = eval(args, vars(logging)) ! h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") --- 103,107 ---- args = cp.get(sectname, "args") args = eval(args, vars(logging)) ! h = klass(*args) if "level" in opts: level = cp.get(sectname, "level") From gvanrossum@users.sourceforge.net Thu Feb 27 20:15:25 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:15:25 -0800 Subject: [Python-checkins] python/dist/src/Lib/xml/dom __init__.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/xml/dom In directory sc8-pr-cvs1:/tmp/cvs-serv3136/xml/dom Modified Files: __init__.py Log Message: Get rid of many apply() calls. Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/xml/dom/__init__.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** __init__.py 25 Jan 2003 17:11:07 -0000 1.12 --- __init__.py 27 Feb 2003 20:14:51 -0000 1.13 *************** *** 67,71 **** raise RuntimeError( "DOMException should not be instantiated directly") ! apply(Exception.__init__, (self,) + args, kw) def _get_code(self): --- 67,71 ---- raise RuntimeError( "DOMException should not be instantiated directly") ! Exception.__init__(self, *args, **kw) def _get_code(self): From gvanrossum@users.sourceforge.net Thu Feb 27 20:15:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:15:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/xml/sax expatreader.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/xml/sax In directory sc8-pr-cvs1:/tmp/cvs-serv3136/xml/sax Modified Files: expatreader.py Log Message: Get rid of many apply() calls. Index: expatreader.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/xml/sax/expatreader.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** expatreader.py 25 Jan 2003 16:51:50 -0000 1.31 --- expatreader.py 27 Feb 2003 20:14:51 -0000 1.32 *************** *** 402,406 **** def create_parser(*args, **kwargs): ! return apply(ExpatParser, args, kwargs) # --- --- 402,406 ---- def create_parser(*args, **kwargs): ! return ExpatParser(*args, **kwargs) # --- From gvanrossum@users.sourceforge.net Thu Feb 27 20:15:26 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:15:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_extcall.py,1.18,1.19 test_struct.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3136/test Modified Files: test_extcall.py test_struct.py Log Message: Get rid of many apply() calls. Index: test_extcall.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_extcall.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** test_extcall.py 30 Jul 2002 23:26:01 -0000 1.18 --- test_extcall.py 27 Feb 2003 20:14:49 -0000 1.19 *************** *** 240,243 **** for k in kwargs: kwdict[k] = k + k print func.func_name, args, sortdict(kwdict), '->', ! try: apply(func, args, kwdict) except TypeError, err: print err --- 240,243 ---- for k in kwargs: kwdict[k] = k + k print func.func_name, args, sortdict(kwdict), '->', ! try: func(*args, **kwdict) except TypeError, err: print err Index: test_struct.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_struct.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_struct.py 23 Jul 2002 19:04:04 -0000 1.15 --- test_struct.py 27 Feb 2003 20:14:50 -0000 1.16 *************** *** 1,5 **** from test.test_support import TestFailed, verbose, verify import struct - ## import pdb import sys --- 1,4 ---- *************** *** 22,26 **** def simple_err(func, *args): try: ! apply(func, args) except struct.error: pass --- 21,25 ---- def simple_err(func, *args): try: ! func(*args) except struct.error: pass *************** *** 28,36 **** raise TestFailed, "%s%s did not raise struct.error" % ( func.__name__, args) - ## pdb.set_trace() def any_err(func, *args): try: ! apply(func, args) except (struct.error, OverflowError, TypeError): pass --- 27,34 ---- raise TestFailed, "%s%s did not raise struct.error" % ( func.__name__, args) def any_err(func, *args): try: ! func(*args) except (struct.error, OverflowError, TypeError): pass *************** *** 38,42 **** raise TestFailed, "%s%s did not raise error" % ( func.__name__, args) - ## pdb.set_trace() --- 36,39 ---- From gvanrossum@users.sourceforge.net Thu Feb 27 20:15:55 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Thu, 27 Feb 2003 12:15:55 -0800 Subject: [Python-checkins] python/dist/src/Lib BaseHTTPServer.py,1.24,1.25 UserList.py,1.17,1.18 atexit.py,1.5,1.6 bdb.py,1.41,1.42 cgi.py,1.75,1.76 copy.py,1.39,1.40 formatter.py,1.22,1.23 ihooks.py,1.15,1.16 imaplib.py,1.59,1.60 mhlib.py,1.34,1.35 mimify.py,1.21,1.22 modulefinder.py,1.4,1.5 nntplib.py,1.34,1.35 os.py,1.68,1.69 pdb.py,1.61,1.62 pre.py,1.13,1.14 profile.py,1.47,1.48 pstats.py,1.27,1.28 pty.py,1.14,1.15 pydoc.py,1.77,1.78 rexec.py,1.47,1.48 robotparser.py,1.16,1.17 sched.py,1.13,1.14 telnetlib.py,1.22,1.23 threading.py,1.31,1.32 tokenize.py,1.34,1.35 trace.py,1.2,1.3 unittest.py,1.21,1.22 urllib.py,1.153,1.154 xdrlib.py,1.14,1.15 xmllib.py,1.30,1.31 xmlrpclib.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv3136 Modified Files: BaseHTTPServer.py UserList.py atexit.py bdb.py cgi.py copy.py formatter.py ihooks.py imaplib.py mhlib.py mimify.py modulefinder.py nntplib.py os.py pdb.py pre.py profile.py pstats.py pty.py pydoc.py rexec.py robotparser.py sched.py telnetlib.py threading.py tokenize.py trace.py unittest.py urllib.py xdrlib.py xmllib.py xmlrpclib.py Log Message: Get rid of many apply() calls. Index: BaseHTTPServer.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/BaseHTTPServer.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** BaseHTTPServer.py 3 Feb 2003 19:11:18 -0000 1.24 --- BaseHTTPServer.py 27 Feb 2003 20:14:29 -0000 1.25 *************** *** 416,420 **** """ ! apply(self.log_message, args) def log_message(self, format, *args): --- 416,420 ---- """ ! self.log_message(*args) def log_message(self, format, *args): Index: UserList.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/UserList.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** UserList.py 9 Jun 2001 07:34:05 -0000 1.17 --- UserList.py 27 Feb 2003 20:14:31 -0000 1.18 *************** *** 78,82 **** def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() ! def sort(self, *args): apply(self.data.sort, args) def extend(self, other): if isinstance(other, UserList): --- 78,82 ---- def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() ! def sort(self, *args): self.data.sort(*args) def extend(self, other): if isinstance(other, UserList): Index: atexit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/atexit.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** atexit.py 16 Jul 2002 19:30:58 -0000 1.5 --- atexit.py 27 Feb 2003 20:14:31 -0000 1.6 *************** *** 18,22 **** while _exithandlers: func, targs, kargs = _exithandlers.pop() ! apply(func, targs, kargs) def register(func, *targs, **kargs): --- 18,22 ---- while _exithandlers: func, targs, kargs = _exithandlers.pop() ! func(*targs, **kargs) def register(func, *targs, **kargs): Index: bdb.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bdb.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** bdb.py 1 Jun 2002 14:18:45 -0000 1.41 --- bdb.py 27 Feb 2003 20:14:32 -0000 1.42 *************** *** 386,390 **** try: try: ! res = apply(func, args) except BdbQuit: pass --- 386,390 ---- try: try: ! res = func(*args) except BdbQuit: pass Index: cgi.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/cgi.py,v retrieving revision 1.75 retrieving revision 1.76 diff -C2 -d -r1.75 -r1.76 *** cgi.py 11 Sep 2002 18:20:34 -0000 1.75 --- cgi.py 27 Feb 2003 20:14:32 -0000 1.76 *************** *** 89,93 **** else: log = dolog ! apply(log, allargs) def dolog(fmt, *args): --- 89,93 ---- else: log = dolog ! log(*allargs) def dolog(fmt, *args): Index: copy.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/copy.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** copy.py 19 Feb 2003 02:35:02 -0000 1.39 --- copy.py 27 Feb 2003 20:14:33 -0000 1.40 *************** *** 141,145 **** if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() ! y = apply(x.__class__, args) else: y = _EmptyClass() --- 141,145 ---- if hasattr(x, '__getinitargs__'): args = x.__getinitargs__() ! y = x.__class__(*args) else: y = _EmptyClass() *************** *** 294,298 **** args = x.__getinitargs__() args = deepcopy(args, memo) ! y = apply(x.__class__, args) else: y = _EmptyClass() --- 294,298 ---- args = x.__getinitargs__() args = deepcopy(args, memo) ! y = x.__class__(*args) else: y = _EmptyClass() Index: formatter.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/formatter.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** formatter.py 3 Jun 2002 15:58:31 -0000 1.22 --- formatter.py 27 Feb 2003 20:14:33 -0000 1.23 *************** *** 109,113 **** if not self.hard_break: self.writer.send_line_break() ! apply(self.writer.send_hor_rule, args, kw) self.hard_break = self.nospace = 1 self.have_label = self.para_end = self.softspace = self.parskip = 0 --- 109,113 ---- if not self.hard_break: self.writer.send_line_break() ! self.writer.send_hor_rule(*args, **kw) self.hard_break = self.nospace = 1 self.have_label = self.para_end = self.softspace = self.parskip = 0 Index: ihooks.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/ihooks.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** ihooks.py 16 Dec 2002 13:11:56 -0000 1.15 --- ihooks.py 27 Feb 2003 20:14:34 -0000 1.16 *************** *** 84,88 **** def note(self, *args): if self.verbose: ! apply(self.message, args) def message(self, format, *args): --- 84,88 ---- def note(self, *args): if self.verbose: ! self.message(*args) def message(self, format, *args): *************** *** 195,199 **** # etc. ! def openfile(self, *x): return apply(open, x) openfile_error = IOError def listdir(self, x): return os.listdir(x) --- 195,199 ---- # etc. ! def openfile(self, *x): return open(*x) openfile_error = IOError def listdir(self, x): return os.listdir(x) Index: imaplib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/imaplib.py,v retrieving revision 1.59 retrieving revision 1.60 diff -C2 -d -r1.59 -r1.60 *** imaplib.py 13 Jan 2003 15:04:26 -0000 1.59 --- imaplib.py 27 Feb 2003 20:14:34 -0000 1.60 *************** *** 580,586 **** name = 'SEARCH' if charset: ! typ, dat = apply(self._simple_command, (name, 'CHARSET', charset) + criteria) else: ! typ, dat = apply(self._simple_command, (name,) + criteria) return self._untagged_response(typ, dat, name) --- 580,586 ---- name = 'SEARCH' if charset: ! typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria) else: ! typ, dat = self._simple_command(name, *criteria) return self._untagged_response(typ, dat, name) *************** *** 643,647 **** if (sort_criteria[0],sort_criteria[-1]) != ('(',')'): sort_criteria = '(%s)' % sort_criteria ! typ, dat = apply(self._simple_command, (name, sort_criteria, charset) + search_criteria) return self._untagged_response(typ, dat, name) --- 643,647 ---- if (sort_criteria[0],sort_criteria[-1]) != ('(',')'): sort_criteria = '(%s)' % sort_criteria ! typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria) return self._untagged_response(typ, dat, name) *************** *** 693,697 **** % (command, self.state)) name = 'UID' ! typ, dat = apply(self._simple_command, (name, command) + args) if command in ('SEARCH', 'SORT'): name = command --- 693,697 ---- % (command, self.state)) name = 'UID' ! typ, dat = self._simple_command(name, command, *args) if command in ('SEARCH', 'SORT'): name = command *************** *** 724,728 **** if not name in Commands: Commands[name] = (self.state,) ! return apply(self._simple_command, (name,) + args) --- 724,728 ---- if not name in Commands: Commands[name] = (self.state,) ! return self._simple_command(name, *args) *************** *** 996,1000 **** def _simple_command(self, name, *args): ! return self._command_complete(name, apply(self._command, (name,) + args)) --- 996,1000 ---- def _simple_command(self, name, *args): ! return self._command_complete(name, self._command(name, *args)) *************** *** 1041,1045 **** while n: try: ! apply(self._mesg, self._cmd_log[i]) except: pass --- 1041,1045 ---- while n: try: ! self._mesg(*self._cmd_log[i]) except: pass *************** *** 1391,1395 **** def run(cmd, args): M._mesg('%s %s' % (cmd, args)) ! typ, dat = apply(getattr(M, cmd), args) M._mesg('%s => %s %s' % (cmd, typ, dat)) if typ == 'NO': raise dat[0] --- 1391,1395 ---- def run(cmd, args): M._mesg('%s %s' % (cmd, args)) ! typ, dat = getattr(M, cmd)(*args) M._mesg('%s => %s %s' % (cmd, typ, dat)) if typ == 'NO': raise dat[0] Index: mhlib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/mhlib.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** mhlib.py 4 Jun 2002 02:17:04 -0000 1.34 --- mhlib.py 27 Feb 2003 20:14:35 -0000 1.35 *************** *** 252,256 **** def error(self, *args): """Error message handler.""" ! apply(self.mh.error, args) def getfullname(self): --- 252,256 ---- def error(self, *args): """Error message handler.""" ! self.mh.error(*args) def getfullname(self): Index: mimify.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/mimify.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** mimify.py 4 Jul 2001 10:15:58 -0000 1.21 --- mimify.py 27 Feb 2003 20:14:35 -0000 1.22 *************** *** 462,464 **** if decode_base64: encode_args = encode_args + (decode_base64,) ! apply(encode, encode_args) --- 462,464 ---- if decode_base64: encode_args = encode_args + (decode_base64,) ! encode(*encode_args) Index: modulefinder.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/modulefinder.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** modulefinder.py 1 Feb 2003 10:29:45 -0000 1.4 --- modulefinder.py 27 Feb 2003 20:14:35 -0000 1.5 *************** *** 98,102 **** if level <= self.debug: self.indent = self.indent + 1 ! apply(self.msg, args) def msgout(self, *args): --- 98,102 ---- if level <= self.debug: self.indent = self.indent + 1 ! self.msg(*args) def msgout(self, *args): *************** *** 104,108 **** if level <= self.debug: self.indent = self.indent - 1 ! apply(self.msg, args) def run_script(self, pathname): --- 104,108 ---- if level <= self.debug: self.indent = self.indent - 1 ! self.msg(*args) def run_script(self, pathname): Index: nntplib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/nntplib.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** nntplib.py 24 Nov 2002 02:35:34 -0000 1.34 --- nntplib.py 27 Feb 2003 20:14:36 -0000 1.35 *************** *** 42,46 **** """Base class for all nntplib exceptions""" def __init__(self, *args): ! apply(Exception.__init__, (self,)+args) try: self.response = args[0] --- 42,46 ---- """Base class for all nntplib exceptions""" def __init__(self, *args): ! Exception.__init__(self, *args) try: self.response = args[0] Index: os.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/os.py,v retrieving revision 1.68 retrieving revision 1.69 diff -C2 -d -r1.68 -r1.69 *** os.py 19 Feb 2003 02:35:03 -0000 1.68 --- os.py 27 Feb 2003 20:14:37 -0000 1.69 *************** *** 272,276 **** head, tail = path.split(file) if head: ! apply(func, (file,) + argrest) return if 'PATH' in env: --- 272,276 ---- head, tail = path.split(file) if head: ! func(file, *argrest) return if 'PATH' in env: *************** *** 284,288 **** fullname = path.join(dir, file) try: ! apply(func, (fullname,) + argrest) except error, e: tb = sys.exc_info()[2] --- 284,288 ---- fullname = path.join(dir, file) try: ! func(fullname, *argrest) except error, e: tb = sys.exc_info()[2] Index: pdb.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pdb.py,v retrieving revision 1.61 retrieving revision 1.62 diff -C2 -d -r1.61 -r1.62 *** pdb.py 31 Jan 2003 17:48:29 -0000 1.61 --- pdb.py 27 Feb 2003 20:14:37 -0000 1.62 *************** *** 949,953 **** def runcall(*args): ! return apply(Pdb().runcall, args) def set_trace(): --- 949,953 ---- def runcall(*args): ! return Pdb().runcall(*args) def set_trace(): Index: pre.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pre.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** pre.py 27 Jun 2002 19:59:27 -0000 1.13 --- pre.py 27 Feb 2003 20:14:37 -0000 1.14 *************** *** 506,510 **** self.flags = statetuple[1] self.groupindex = statetuple[2] ! self.code = apply(pcre_compile, statetuple) class _Dummy: --- 506,510 ---- self.flags = statetuple[1] self.groupindex = statetuple[2] ! self.code = pcre_compile(*statetuple) class _Dummy: Index: profile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/profile.py,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** profile.py 2 Jun 2002 18:55:56 -0000 1.47 --- profile.py 27 Feb 2003 20:14:38 -0000 1.48 *************** *** 417,421 **** sys.setprofile(self.dispatcher) try: ! return apply(func, args, kw) finally: sys.setprofile(None) --- 417,421 ---- sys.setprofile(self.dispatcher) try: ! return func(*args, **kw) finally: sys.setprofile(None) Index: pstats.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pstats.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** pstats.py 2 Jun 2002 18:55:56 -0000 1.27 --- pstats.py 27 Feb 2003 20:14:38 -0000 1.28 *************** *** 77,81 **** args = args[1:] self.init(arg) ! apply(self.add, args) def init(self, arg): --- 77,81 ---- args = args[1:] self.init(arg) ! self.add(*args) def init(self, arg): *************** *** 135,139 **** def add(self, *arg_list): if not arg_list: return self ! if len(arg_list) > 1: apply(self.add, arg_list[1:]) other = arg_list[0] if type(self) != type(other) or self.__class__ != other.__class__: --- 135,139 ---- def add(self, *arg_list): if not arg_list: return self ! if len(arg_list) > 1: self.add(*arg_list[1:]) other = arg_list[0] if type(self) != type(other) or self.__class__ != other.__class__: *************** *** 529,533 **** processed.append(term) if self.stats: ! apply(getattr(self.stats, fn), processed) else: print "No statistics object is loaded." --- 529,533 ---- processed.append(term) if self.stats: ! getattr(self.stats, fn)(*processed) else: print "No statistics object is loaded." *************** *** 595,599 **** abbrevs = self.stats.get_sort_arg_defs() if line and not filter(lambda x,a=abbrevs: x not in a,line.split()): ! apply(self.stats.sort_stats, line.split()) else: print "Valid sort keys (unique prefixes are accepted):" --- 595,599 ---- abbrevs = self.stats.get_sort_arg_defs() if line and not filter(lambda x,a=abbrevs: x not in a,line.split()): ! self.stats.sort_stats(*line.split()) else: print "Valid sort keys (unique prefixes are accepted):" Index: pty.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pty.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** pty.py 29 Jan 2003 03:49:43 -0000 1.14 --- pty.py 27 Feb 2003 20:14:38 -0000 1.15 *************** *** 164,168 **** pid, master_fd = fork() if pid == CHILD: ! apply(os.execlp, (argv[0],) + argv) try: mode = tty.tcgetattr(STDIN_FILENO) --- 164,168 ---- pid, master_fd = fork() if pid == CHILD: ! os.execlp(argv[0], *argv) try: mode = tty.tcgetattr(STDIN_FILENO) Index: pydoc.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pydoc.py,v retrieving revision 1.77 retrieving revision 1.78 diff -C2 -d -r1.77 -r1.78 *** pydoc.py 16 Feb 2003 01:12:32 -0000 1.77 --- pydoc.py 27 Feb 2003 20:14:39 -0000 1.78 *************** *** 267,274 **** """Generate documentation for an object.""" args = (object, name) + args ! if inspect.ismodule(object): return apply(self.docmodule, args) ! if inspect.isclass(object): return apply(self.docclass, args) ! if inspect.isroutine(object): return apply(self.docroutine, args) ! return apply(self.docother, args) def fail(self, object, name=None, *args): --- 267,274 ---- """Generate documentation for an object.""" args = (object, name) + args ! if inspect.ismodule(object): return self.docmodule(*args) ! if inspect.isclass(object): return self.docclass(*args) ! if inspect.isroutine(object): returnself.docroutine(*args) ! return self.docother(*args) def fail(self, object, name=None, *args): *************** *** 380,384 **** """Format a section with a big heading.""" title = '%s' % title ! return apply(self.section, (title,) + args) def preformat(self, text): --- 380,384 ---- """Format a section with a big heading.""" title = '%s' % title ! return self.section(title, *args) def preformat(self, text): Index: rexec.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/rexec.py,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** rexec.py 6 Jan 2003 15:43:14 -0000 1.47 --- rexec.py 27 Feb 2003 20:14:40 -0000 1.48 *************** *** 49,53 **** TEMPLATE = """ def %s(self, *args): ! return apply(getattr(self.mod, self.name).%s, args) """ --- 49,53 ---- TEMPLATE = """ def %s(self, *args): ! return getattr(self.mod, self.name).%s(*args) """ *************** *** 408,419 **** sys.stderr = self.save_stderr ! def s_apply(self, func, args=(), kw=None): self.save_files() try: self.set_files() ! if kw: ! r = apply(func, args, kw) ! else: ! r = apply(func, args) finally: self.restore_files() --- 408,416 ---- sys.stderr = self.save_stderr ! def s_apply(self, func, args=(), kw={}): self.save_files() try: self.set_files() ! r = func(*args, **kw) finally: self.restore_files() Index: robotparser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/robotparser.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** robotparser.py 31 May 2002 14:14:06 -0000 1.16 --- robotparser.py 27 Feb 2003 20:14:40 -0000 1.17 *************** *** 231,235 **** class URLopener(urllib.FancyURLopener): def __init__(self, *args): ! apply(urllib.FancyURLopener.__init__, (self,) + args) self.errcode = 200 --- 231,235 ---- class URLopener(urllib.FancyURLopener): def __init__(self, *args): ! urllib.FancyURLopener.__init__(self, *args) self.errcode = 200 Index: sched.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/sched.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** sched.py 15 Feb 2001 22:15:13 -0000 1.13 --- sched.py 27 Feb 2003 20:14:41 -0000 1.14 *************** *** 103,106 **** else: del q[0] ! void = apply(action, argument) self.delayfunc(0) # Let other threads run --- 103,106 ---- else: del q[0] ! void = action(*argument) self.delayfunc(0) # Let other threads run Index: telnetlib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/telnetlib.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** telnetlib.py 9 Nov 2002 05:08:06 -0000 1.22 --- telnetlib.py 27 Feb 2003 20:14:41 -0000 1.23 *************** *** 312,316 **** if timeout is not None: s_args = s_args + (timeout,) ! while not self.eof and apply(select.select, s_args) == s_reply: i = max(0, len(self.cookedq)-n) self.fill_rawq() --- 312,316 ---- if timeout is not None: s_args = s_args + (timeout,) ! while not self.eof and select.select(*s_args) == s_reply: i = max(0, len(self.cookedq)-n) self.fill_rawq() Index: threading.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/threading.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** threading.py 30 Dec 2002 23:32:50 -0000 1.31 --- threading.py 27 Feb 2003 20:14:41 -0000 1.32 *************** *** 58,62 **** def RLock(*args, **kwargs): ! return apply(_RLock, args, kwargs) class _RLock(_Verbose): --- 58,62 ---- def RLock(*args, **kwargs): ! return _RLock(*args, **kwargs) class _RLock(_Verbose): *************** *** 129,133 **** def Condition(*args, **kwargs): ! return apply(_Condition, args, kwargs) class _Condition(_Verbose): --- 129,133 ---- def Condition(*args, **kwargs): ! return _Condition(*args, **kwargs) class _Condition(_Verbose): *************** *** 241,245 **** def Semaphore(*args, **kwargs): ! return apply(_Semaphore, args, kwargs) class _Semaphore(_Verbose): --- 241,245 ---- def Semaphore(*args, **kwargs): ! return _Semaphore(*args, **kwargs) class _Semaphore(_Verbose): *************** *** 283,287 **** def BoundedSemaphore(*args, **kwargs): ! return apply(_BoundedSemaphore, args, kwargs) class _BoundedSemaphore(_Semaphore): --- 283,287 ---- def BoundedSemaphore(*args, **kwargs): ! return _BoundedSemaphore(*args, **kwargs) class _BoundedSemaphore(_Semaphore): *************** *** 298,302 **** def Event(*args, **kwargs): ! return apply(_Event, args, kwargs) class _Event(_Verbose): --- 298,302 ---- def Event(*args, **kwargs): ! return _Event(*args, **kwargs) class _Event(_Verbose): *************** *** 397,401 **** def run(self): if self.__target: ! apply(self.__target, self.__args, self.__kwargs) def __bootstrap(self): --- 397,401 ---- def run(self): if self.__target: ! self.__target(*self.__args, **self.__kwargs) def __bootstrap(self): Index: tokenize.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/tokenize.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** tokenize.py 5 Nov 2002 06:06:02 -0000 1.34 --- tokenize.py 27 Feb 2003 20:14:42 -0000 1.35 *************** *** 43,48 **** def group(*choices): return '(' + '|'.join(choices) + ')' ! def any(*choices): return apply(group, choices) + '*' ! def maybe(*choices): return apply(group, choices) + '?' Whitespace = r'[ \f\t]*' --- 43,48 ---- def group(*choices): return '(' + '|'.join(choices) + ')' ! def any(*choices): return group(*choices) + '*' ! def maybe(*choices): return group(*choices) + '?' Whitespace = r'[ \f\t]*' *************** *** 158,162 **** def tokenize_loop(readline, tokeneater): for token_info in generate_tokens(readline): ! apply(tokeneater, token_info) def generate_tokens(readline): --- 158,162 ---- def tokenize_loop(readline, tokeneater): for token_info in generate_tokens(readline): ! tokeneater(*token_info) def generate_tokens(readline): Index: trace.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/trace.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** trace.py 19 Feb 2003 02:35:03 -0000 1.2 --- trace.py 27 Feb 2003 20:14:43 -0000 1.3 *************** *** 472,476 **** sys.settrace(self.globaltrace) try: ! result = apply(func, args, kw) finally: if not self.donothing: --- 472,476 ---- sys.settrace(self.globaltrace) try: ! result = func(*args, **kw) finally: if not self.donothing: Index: unittest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/unittest.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** unittest.py 29 Dec 2002 17:59:23 -0000 1.21 --- unittest.py 27 Feb 2003 20:14:43 -0000 1.22 *************** *** 116,120 **** def _exc_info_to_string(self, err): """Converts a sys.exc_info()-style tuple of values into a string.""" ! return string.join(apply(traceback.format_exception, err), '') def __repr__(self): --- 116,120 ---- def _exc_info_to_string(self, err): """Converts a sys.exc_info()-style tuple of values into a string.""" ! return string.join(traceback.format_exception(*err), '') def __repr__(self): *************** *** 277,281 **** """ try: ! apply(callableObj, args, kwargs) except excClass: return --- 277,281 ---- """ try: ! callableObj(*args, **kwargs) except excClass: return *************** *** 562,566 **** def writeln(self, *args): ! if args: apply(self.write, args) self.write('\n') # text-mode streams translate to \r\n if needed --- 562,566 ---- def writeln(self, *args): ! if args: self.write(*args) self.write('\n') # text-mode streams translate to \r\n if needed Index: urllib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/urllib.py,v retrieving revision 1.153 retrieving revision 1.154 diff -C2 -d -r1.153 -r1.154 *** urllib.py 11 Oct 2002 14:36:24 -0000 1.153 --- urllib.py 27 Feb 2003 20:14:43 -0000 1.154 *************** *** 294,298 **** if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) ! for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: --- 294,298 ---- if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) ! for args in self.addheaders: h.putheader(*args) h.endheaders() if data is not None: *************** *** 372,376 **** if auth: h.putheader('Authorization: Basic %s' % auth) if realhost: h.putheader('Host', realhost) ! for args in self.addheaders: apply(h.putheader, args) h.endheaders() if data is not None: --- 372,376 ---- if auth: h.putheader('Authorization: Basic %s' % auth) if realhost: h.putheader('Host', realhost) ! for args in self.addheaders: h.putheader(*args) h.endheaders() if data is not None: *************** *** 542,546 **** def __init__(self, *args, **kwargs): ! apply(URLopener.__init__, (self,) + args, kwargs) self.auth_cache = {} self.tries = 0 --- 542,546 ---- def __init__(self, *args, **kwargs): ! URLopener.__init__(self, *args, **kwargs) self.auth_cache = {} self.tries = 0 *************** *** 805,809 **** addbase.close(self) if self.closehook: ! apply(self.closehook, self.hookargs) self.closehook = None self.hookargs = None --- 805,809 ---- addbase.close(self) if self.closehook: ! self.closehook(*self.hookargs) self.closehook = None self.hookargs = None Index: xdrlib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/xdrlib.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** xdrlib.py 31 Mar 2002 13:59:18 -0000 1.14 --- xdrlib.py 27 Feb 2003 20:14:45 -0000 1.15 *************** *** 247,251 **** print 'pack test', count, try: ! apply(method, args) print 'succeeded' except ConversionError, var: --- 247,251 ---- print 'pack test', count, try: ! method(*args) print 'succeeded' except ConversionError, var: *************** *** 273,277 **** try: if succeedlist[count]: ! x = apply(method, args) print pred(x) and 'succeeded' or 'failed', ':', x else: --- 273,277 ---- try: if succeedlist[count]: ! x = method(*args) print pred(x) and 'succeeded' or 'failed', ':', x else: Index: xmllib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/xmllib.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** xmllib.py 1 Jun 2002 14:18:47 -0000 1.30 --- xmllib.py 27 Feb 2003 20:14:45 -0000 1.31 *************** *** 810,814 **** def __init__(self, **kw): self.testdata = "" ! apply(XMLParser.__init__, (self,), kw) def handle_xml(self, encoding, standalone): --- 810,814 ---- def __init__(self, **kw): self.testdata = "" ! XMLParser.__init__(self, **kw) def handle_xml(self, encoding, standalone): Index: xmlrpclib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/xmlrpclib.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** xmlrpclib.py 22 Jan 2003 18:17:23 -0000 1.23 --- xmlrpclib.py 27 Feb 2003 20:14:46 -0000 1.24 *************** *** 721,725 **** raise ResponseError() if self._type == "fault": ! raise apply(Fault, (), self._stack[0]) return tuple(self._stack) --- 721,725 ---- raise ResponseError() if self._type == "fault": ! raise Fault(**self._stack[0]) return tuple(self._stack) *************** *** 1214,1218 **** ) else: ! return apply(HTTPS, (host, None), x509 or {}) ## --- 1214,1218 ---- ) else: ! return HTTPS(host, None, **(x509 or {})) ## From montanaro@users.sourceforge.net Thu Feb 27 21:27:11 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 27 Feb 2003 13:27:11 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_dis.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv29223 Added Files: test_dis.py Log Message: simple test case for dis module --- NEW FILE: test_dis.py --- from test.test_support import verify, verbose, TestFailed, run_unittest import sys import dis import StringIO # Minimal tests for dis module import unittest # placement is crucial!!! move the start of _f and you have to adjust the # line numbers in dis_f def _f(a): print a return 1 dis_f = """\ 13 0 LOAD_FAST 0 (a) 3 PRINT_ITEM 4 PRINT_NEWLINE 14 5 LOAD_CONST 1 (1) 8 RETURN_VALUE 9 LOAD_CONST 0 (None) 12 RETURN_VALUE """ class DisTests(unittest.TestCase): def test_opmap(self): self.assertEqual(dis.opmap["STOP_CODE"], 0) self.assertEqual(dis.opmap["LOAD_CONST"] in dis.hasconst, True) self.assertEqual(dis.opmap["STORE_NAME"] in dis.hasname, True) def test_opname(self): self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") def test_boundaries(self): self.assertEqual(dis.opmap["EXTENDED_ARG"], dis.EXTENDED_ARG) self.assertEqual(dis.opmap["STORE_NAME"], dis.HAVE_ARGUMENT) def test_dis(self): s = StringIO.StringIO() save_stdout = sys.stdout sys.stdout = s dis.dis(_f) sys.stdout = save_stdout self.assertEqual(dis_f, s.getvalue()) def test_main(): run_unittest(DisTests) if __name__ == "__main__": test_main() From montanaro@users.sourceforge.net Thu Feb 27 21:27:55 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 27 Feb 2003 13:27:55 -0800 Subject: [Python-checkins] python/dist/src/Lib opcode.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv29496 Added Files: opcode.py Log Message: new opcode module - extract opcode definitions from dis.py - eventually should be generated automatically --- NEW FILE: opcode.py --- """ opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<' + `op` + '>' del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def jrel_op(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) # Instruction opcodes for compiled code def_op('STOP_CODE', 0) def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('ROT_FOUR', 5) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_DIVIDE', 21) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('SLICE+0', 30) def_op('SLICE+1', 31) def_op('SLICE+2', 32) def_op('SLICE+3', 33) def_op('STORE_SLICE+0', 40) def_op('STORE_SLICE+1', 41) def_op('STORE_SLICE+2', 42) def_op('STORE_SLICE+3', 43) def_op('DELETE_SLICE+0', 50) def_op('DELETE_SLICE+1', 51) def_op('DELETE_SLICE+2', 52) def_op('DELETE_SLICE+3', 53) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_DIVIDE', 58) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) def_op('PRINT_EXPR', 70) def_op('PRINT_ITEM', 71) def_op('PRINT_NEWLINE', 72) def_op('PRINT_ITEM_TO', 73) def_op('PRINT_NEWLINE_TO', 74) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('LOAD_LOCALS', 82) def_op('RETURN_VALUE', 83) def_op('IMPORT_STAR', 84) def_op('EXEC_STMT', 85) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('BUILD_CLASS', 89) HAVE_ARGUMENT = 90 # Opcodes from here have an argument: name_op('STORE_NAME', 90) # Index in name list name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items jrel_op('FOR_ITER', 93) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" name_op('DELETE_GLOBAL', 98) # "" def_op('DUP_TOPX', 99) # number of items to duplicate def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items def_op('BUILD_MAP', 104) # Always zero for now name_op('LOAD_ATTR', 105) # Index in name list def_op('COMPARE_OP', 106) # Comparison operator hascompare.append(106) name_op('IMPORT_NAME', 107) # Index in name list name_op('IMPORT_FROM', 108) # Index in name list jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jrel_op('JUMP_IF_FALSE', 111) # "" jrel_op('JUMP_IF_TRUE', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address jrel_op('SETUP_LOOP', 120) # Distance to target address jrel_op('SETUP_EXCEPT', 121) # "" jrel_op('SETUP_FINALLY', 122) # "" def_op('LOAD_FAST', 124) # Local variable number haslocal.append(124) def_op('STORE_FAST', 125) # Local variable number haslocal.append(125) def_op('DELETE_FAST', 126) # Local variable number haslocal.append(126) def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) def_op('MAKE_FUNCTION', 132) # Number of args with default values def_op('BUILD_SLICE', 133) # Number of items def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) def_op('EXTENDED_ARG', 143) EXTENDED_ARG = 143 del def_op, name_op, jrel_op, jabs_op From montanaro@users.sourceforge.net Thu Feb 27 21:29:31 2003 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 27 Feb 2003 13:29:31 -0800 Subject: [Python-checkins] python/dist/src/Lib dis.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv30385 Modified Files: dis.py Log Message: * separate opcode definitions into opcode.py * add disassemble_string * allow classes and strings containing bytecode to be disassembled Index: dis.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/dis.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** dis.py 30 Aug 2002 13:09:49 -0000 1.44 --- dis.py 27 Feb 2003 21:29:27 -0000 1.45 *************** *** 4,10 **** import types ! __all__ = ["dis","disassemble","distb","disco","opname","cmp_op", ! "hasconst","hasname","hasjrel","hasjabs","haslocal", ! "hascompare", "hasfree"] def dis(x=None): --- 4,12 ---- import types ! from opcode import * ! from opcode import __all__ as _opcodes_all ! ! __all__ = ["dis","disassemble","distb","disco"] + _opcodes_all ! del _opcodes_all def dis(x=None): *************** *** 29,33 **** if type(x1) in (types.MethodType, types.FunctionType, ! types.CodeType): print "Disassembly of %s:" % name try: --- 31,36 ---- if type(x1) in (types.MethodType, types.FunctionType, ! types.CodeType, ! types.ClassType): print "Disassembly of %s:" % name try: *************** *** 38,41 **** --- 41,46 ---- elif hasattr(x, 'co_code'): disassemble(x) + elif isinstance(x, str): + disassemble_string(x) else: raise TypeError, \ *************** *** 125,128 **** --- 130,175 ---- print + def disassemble_string(code, lasti=-1, varnames=None, names=None, + constants=None): + labels = findlabels(code) + n = len(code) + i = 0 + while i < n: + c = code[i] + op = ord(c) + if op == opmap['SET_LINENO'] and i > 0: + print # Extra blank line + if i == lasti: print '-->', + else: print ' ', + if i in labels: print '>>', + else: print ' ', + print `i`.rjust(4), + print opname[op].ljust(15), + i = i+1 + if op >= HAVE_ARGUMENT: + oparg = ord(code[i]) + ord(code[i+1])*256 + i = i+2 + print `oparg`.rjust(5), + if op in hasconst: + if constants: + print '(' + `constants[oparg]` + ')', + else: + print '(%d)'%oparg, + elif op in hasname: + if names is not None: + print '(' + names[oparg] + ')', + else: + print '(%d)'%oparg, + elif op in hasjrel: + print '(to ' + `i + oparg` + ')', + elif op in haslocal: + if varnames: + print '(' + varnames[oparg] + ')', + else: + print '(%d)' % oparg, + elif op in hascompare: + print '(' + cmp_op[oparg] + ')', + print + disco = disassemble # XXX For backwards compatibility *************** *** 153,330 **** return labels - cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', - 'is not', 'exception match', 'BAD') - - hasconst = [] - hasname = [] - hasjrel = [] - hasjabs = [] - haslocal = [] - hascompare = [] - hasfree = [] - - opname = [''] * 256 - for op in range(256): opname[op] = '<' + `op` + '>' - del op - - def def_op(name, op): - opname[op] = name - - def name_op(name, op): - opname[op] = name - hasname.append(op) - - def jrel_op(name, op): - opname[op] = name - hasjrel.append(op) - - def jabs_op(name, op): - opname[op] = name - hasjabs.append(op) - - # Instruction opcodes for compiled code - - def_op('STOP_CODE', 0) - def_op('POP_TOP', 1) - def_op('ROT_TWO', 2) - def_op('ROT_THREE', 3) - def_op('DUP_TOP', 4) - def_op('ROT_FOUR', 5) - - def_op('UNARY_POSITIVE', 10) - def_op('UNARY_NEGATIVE', 11) - def_op('UNARY_NOT', 12) - def_op('UNARY_CONVERT', 13) - - def_op('UNARY_INVERT', 15) - - def_op('BINARY_POWER', 19) - - def_op('BINARY_MULTIPLY', 20) - def_op('BINARY_DIVIDE', 21) - def_op('BINARY_MODULO', 22) - def_op('BINARY_ADD', 23) - def_op('BINARY_SUBTRACT', 24) - def_op('BINARY_SUBSCR', 25) - def_op('BINARY_FLOOR_DIVIDE', 26) - def_op('BINARY_TRUE_DIVIDE', 27) - def_op('INPLACE_FLOOR_DIVIDE', 28) - def_op('INPLACE_TRUE_DIVIDE', 29) - - def_op('SLICE+0', 30) - def_op('SLICE+1', 31) - def_op('SLICE+2', 32) - def_op('SLICE+3', 33) - - def_op('STORE_SLICE+0', 40) - def_op('STORE_SLICE+1', 41) - def_op('STORE_SLICE+2', 42) - def_op('STORE_SLICE+3', 43) - - def_op('DELETE_SLICE+0', 50) - def_op('DELETE_SLICE+1', 51) - def_op('DELETE_SLICE+2', 52) - def_op('DELETE_SLICE+3', 53) - - def_op('INPLACE_ADD', 55) - def_op('INPLACE_SUBTRACT', 56) - def_op('INPLACE_MULTIPLY', 57) - def_op('INPLACE_DIVIDE', 58) - def_op('INPLACE_MODULO', 59) - def_op('STORE_SUBSCR', 60) - def_op('DELETE_SUBSCR', 61) - - def_op('BINARY_LSHIFT', 62) - def_op('BINARY_RSHIFT', 63) - def_op('BINARY_AND', 64) - def_op('BINARY_XOR', 65) - def_op('BINARY_OR', 66) - def_op('INPLACE_POWER', 67) - def_op('GET_ITER', 68) - - def_op('PRINT_EXPR', 70) - def_op('PRINT_ITEM', 71) - def_op('PRINT_NEWLINE', 72) - def_op('PRINT_ITEM_TO', 73) - def_op('PRINT_NEWLINE_TO', 74) - def_op('INPLACE_LSHIFT', 75) - def_op('INPLACE_RSHIFT', 76) - def_op('INPLACE_AND', 77) - def_op('INPLACE_XOR', 78) - def_op('INPLACE_OR', 79) - def_op('BREAK_LOOP', 80) - - def_op('LOAD_LOCALS', 82) - def_op('RETURN_VALUE', 83) - def_op('IMPORT_STAR', 84) - def_op('EXEC_STMT', 85) - def_op('YIELD_VALUE', 86) - - def_op('POP_BLOCK', 87) - def_op('END_FINALLY', 88) - def_op('BUILD_CLASS', 89) - - HAVE_ARGUMENT = 90 # Opcodes from here have an argument: - - name_op('STORE_NAME', 90) # Index in name list - name_op('DELETE_NAME', 91) # "" - def_op('UNPACK_SEQUENCE', 92) # Number of tuple items - jrel_op('FOR_ITER', 93) - - name_op('STORE_ATTR', 95) # Index in name list - name_op('DELETE_ATTR', 96) # "" - name_op('STORE_GLOBAL', 97) # "" - name_op('DELETE_GLOBAL', 98) # "" - def_op('DUP_TOPX', 99) # number of items to duplicate - def_op('LOAD_CONST', 100) # Index in const list - hasconst.append(100) - name_op('LOAD_NAME', 101) # Index in name list - def_op('BUILD_TUPLE', 102) # Number of tuple items - def_op('BUILD_LIST', 103) # Number of list items - def_op('BUILD_MAP', 104) # Always zero for now - name_op('LOAD_ATTR', 105) # Index in name list - def_op('COMPARE_OP', 106) # Comparison operator - hascompare.append(106) - name_op('IMPORT_NAME', 107) # Index in name list - name_op('IMPORT_FROM', 108) # Index in name list - - jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip - jrel_op('JUMP_IF_FALSE', 111) # "" - jrel_op('JUMP_IF_TRUE', 112) # "" - jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code - - name_op('LOAD_GLOBAL', 116) # Index in name list - - jabs_op('CONTINUE_LOOP', 119) # Target address - jrel_op('SETUP_LOOP', 120) # Distance to target address - jrel_op('SETUP_EXCEPT', 121) # "" - jrel_op('SETUP_FINALLY', 122) # "" - - def_op('LOAD_FAST', 124) # Local variable number - haslocal.append(124) - def_op('STORE_FAST', 125) # Local variable number - haslocal.append(125) - def_op('DELETE_FAST', 126) # Local variable number - haslocal.append(126) - - def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) - def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) - def_op('MAKE_FUNCTION', 132) # Number of args with default values - def_op('BUILD_SLICE', 133) # Number of items - - def_op('MAKE_CLOSURE', 134) - def_op('LOAD_CLOSURE', 135) - hasfree.append(135) - def_op('LOAD_DEREF', 136) - hasfree.append(136) - def_op('STORE_DEREF', 137) - hasfree.append(137) - - def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) - def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) - def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) - - def_op('EXTENDED_ARG', 143) - EXTENDED_ARG = 143 def _test(): --- 200,203 ---- From jackjansen@users.sourceforge.net Thu Feb 27 22:36:22 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 14:36:22 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac dialogs.rsrc,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv26264 Modified Files: dialogs.rsrc Log Message: Changing the window type to movable modal isn't enough to make the dialogs movable: apprently you also need to set a bit in the dlgx resource. Did this. Index: dialogs.rsrc =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/dialogs.rsrc,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 Binary files /tmp/cvstK1xC0 and /tmp/cvssKtxVQ differ From jackjansen@users.sourceforge.net Thu Feb 27 22:50:52 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 14:50:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/dlg _Dlgmodule.c,1.17,1.18 dlgscan.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/dlg In directory sc8-pr-cvs1:/tmp/cvs-serv32629 Modified Files: _Dlgmodule.c dlgscan.py Log Message: StdFilterProc() uses InOut parameters. Index: _Dlgmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/dlg/_Dlgmodule.c,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** _Dlgmodule.c 23 Dec 2002 23:16:22 -0000 1.17 --- _Dlgmodule.c 27 Feb 2003 22:50:49 -0000 1.18 *************** *** 15,21 **** /* Macro to test whether a weak-loaded CFM function exists */ #define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\ ! PyErr_SetString(PyExc_NotImplementedError, \ ! "Not available in this shared library/OS version"); \ ! return NULL; \ }} while(0) --- 15,21 ---- /* Macro to test whether a weak-loaded CFM function exists */ #define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\ ! PyErr_SetString(PyExc_NotImplementedError, \ ! "Not available in this shared library/OS version"); \ ! return NULL; \ }} while(0) *************** *** 503,507 **** PyMac_PRECHECK(StdFilterProc); #endif ! if (!PyArg_ParseTuple(_args, "")) return NULL; _rv = StdFilterProc(_self->ob_itself, --- 503,509 ---- PyMac_PRECHECK(StdFilterProc); #endif ! if (!PyArg_ParseTuple(_args, "O&h", ! PyMac_GetEventRecord, &event, ! &itemHit)) return NULL; _rv = StdFilterProc(_self->ob_itself, *************** *** 904,908 **** PyDoc_STR("(DialogItemIndex itemNo, DialogItemIndex amountToRemove, Boolean disposeItemData) -> None")}, {"StdFilterProc", (PyCFunction)DlgObj_StdFilterProc, 1, ! PyDoc_STR("() -> (Boolean _rv, EventRecord event, DialogItemIndex itemHit)")}, {"SetDialogDefaultItem", (PyCFunction)DlgObj_SetDialogDefaultItem, 1, PyDoc_STR("(DialogItemIndex newItem) -> None")}, --- 906,910 ---- PyDoc_STR("(DialogItemIndex itemNo, DialogItemIndex amountToRemove, Boolean disposeItemData) -> None")}, {"StdFilterProc", (PyCFunction)DlgObj_StdFilterProc, 1, ! PyDoc_STR("(EventRecord event, DialogItemIndex itemHit) -> (Boolean _rv, EventRecord event, DialogItemIndex itemHit)")}, {"SetDialogDefaultItem", (PyCFunction)DlgObj_SetDialogDefaultItem, 1, PyDoc_STR("(DialogItemIndex newItem) -> None")}, Index: dlgscan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/dlg/dlgscan.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** dlgscan.py 12 Dec 2002 10:31:50 -0000 1.18 --- dlgscan.py 27 Feb 2003 22:50:50 -0000 1.19 *************** *** 100,103 **** --- 100,110 ---- ([("WindowPtr", "*", "ReturnMode")], [("ExistingWindowPtr", "*", "*")]), + + # StdFilterProc + ([('EventRecord', 'event', 'OutMode'), + ('DialogItemIndex', 'itemHit', 'OutMode')], + [('EventRecord', 'event', 'InOutMode'), + ('DialogItemIndex', 'itemHit', 'InOutMode')]) + ] From jackjansen@users.sourceforge.net Thu Feb 27 22:53:01 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 14:53:01 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.679,1.680 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv1141 Modified Files: NEWS Log Message: Added a note about EasyDialogs dialogs having become movable. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.679 retrieving revision 1.680 diff -C2 -d -r1.679 -r1.680 *** NEWS 25 Feb 2003 21:41:59 -0000 1.679 --- NEWS 27 Feb 2003 22:52:58 -0000 1.680 *************** *** 71,74 **** --- 71,76 ---- - A new method MacOS.WMAvailable() returns true if it is safe to access the window manager, false otherwise. + + - EasyDialogs dialogs are now movable-modal. From jackjansen@users.sourceforge.net Thu Feb 27 23:17:30 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 15:17:30 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_macostools.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv12390 Modified Files: test_macostools.py Log Message: Getting rid of macfs. Index: test_macostools.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_macostools.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** test_macostools.py 19 Feb 2003 02:35:06 -0000 1.4 --- test_macostools.py 27 Feb 2003 23:17:26 -0000 1.5 *************** *** 3,7 **** import unittest import macostools ! import macfs import MacOS import os --- 3,7 ---- import unittest import macostools ! import Carbon.File import MacOS import os *************** *** 68,72 **** pass macostools.mkalias(test_support.TESTFN, TESTFN2) ! fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) --- 68,72 ---- pass macostools.mkalias(test_support.TESTFN, TESTFN2) ! fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) *************** *** 77,81 **** pass macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) ! fss, _, _ = macfs.ResolveAliasFile(TESTFN2) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) --- 77,81 ---- pass macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) ! fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) From jackjansen@users.sourceforge.net Thu Feb 27 23:18:02 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 15:18:02 -0800 Subject: [Python-checkins] python/dist/src/Lib/plat-mac macfs.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/plat-mac In directory sc8-pr-cvs1:/tmp/cvs-serv12612 Modified Files: macfs.py Log Message: Added a deprecation warning. Index: macfs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/plat-mac/macfs.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** macfs.py 29 Jan 2003 09:56:56 -0000 1.8 --- macfs.py 27 Feb 2003 23:17:59 -0000 1.9 *************** *** 8,11 **** --- 8,14 ---- import warnings + warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs", + DeprecationWarning, stacklevel=2) + # First step: ensure we also emulate the MACFS module, which contained # all the constants From jackjansen@users.sourceforge.net Thu Feb 27 23:18:48 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 15:18:48 -0800 Subject: [Python-checkins] python/dist/src/Lib macpath.py,1.46,1.47 py_compile.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv12993 Modified Files: macpath.py py_compile.py Log Message: Getting rid of macfs. Index: macpath.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/macpath.py,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** macpath.py 14 Feb 2003 19:35:30 -0000 1.46 --- macpath.py 27 Feb 2003 23:18:45 -0000 1.47 *************** *** 130,135 **** try: ! import macfs ! return macfs.ResolveAliasFile(s)[2] except: return False --- 130,135 ---- try: ! import Carbon.File ! return Carbon.File.ResolveAliasFile(s, 0)[2] except: return False *************** *** 248,252 **** path = abspath(path) try: ! import macfs except ImportError: return path --- 248,252 ---- path = abspath(path) try: ! import Carbon.File except ImportError: return path *************** *** 257,261 **** for c in components[1:]: path = join(path, c) ! path = macfs.ResolveAliasFile(path)[0].as_pathname() return path --- 257,261 ---- for c in components[1:]: path = join(path, c) ! path = Carbon.File.FSResolveAliasFile(path, 1)[0].as_pathname() return path Index: py_compile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/py_compile.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** py_compile.py 29 Jan 2003 03:49:43 -0000 1.25 --- py_compile.py 27 Feb 2003 23:18:46 -0000 1.26 *************** *** 64,70 **** # Define an internal helper according to the platform if os.name == "mac": ! import macfs def set_creator_type(file): ! macfs.FSSpec(file).SetCreatorType('Pyth', 'PYC ') else: def set_creator_type(file): --- 64,70 ---- # Define an internal helper according to the platform if os.name == "mac": ! import MacOS def set_creator_type(file): ! MacOS.SetCreatorAndType(file, 'Pyth', 'PYC ') else: def set_creator_type(file): From jackjansen@users.sourceforge.net Thu Feb 27 23:19:49 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 27 Feb 2003 15:19:49 -0800 Subject: [Python-checkins] python/dist/src Makefile.pre.in,1.114,1.115 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv13361 Modified Files: Makefile.pre.in Log Message: In make clobber also clean out the Python.framework. Index: Makefile.pre.in =================================================================== RCS file: /cvsroot/python/python/dist/src/Makefile.pre.in,v retrieving revision 1.114 retrieving revision 1.115 diff -C2 -d -r1.114 -r1.115 *** Makefile.pre.in 25 Feb 2003 12:41:08 -0000 1.114 --- Makefile.pre.in 27 Feb 2003 23:19:46 -0000 1.115 *************** *** 917,920 **** --- 917,921 ---- config.cache config.log pyconfig.h Modules/config.c -rm -rf build platform + -rm -rf $(PYTHONFRAMEWORKDIR) # Make things extra clean, before making a distribution: From nnorwitz@users.sourceforge.net Fri Feb 28 03:14:40 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 27 Feb 2003 19:14:40 -0800 Subject: [Python-checkins] python/dist/src/Modules unicodedata.c,2.27,2.28 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv31129/Modules Modified Files: unicodedata.c Log Message: Fix SF bug #694816, remove comparison of unsigned value < 0 Index: unicodedata.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/unicodedata.c,v retrieving revision 2.27 retrieving revision 2.28 diff -C2 -d -r2.27 -r2.28 *** unicodedata.c 7 Dec 2002 14:56:36 -0000 2.27 --- unicodedata.c 28 Feb 2003 03:14:37 -0000 2.28 *************** *** 34,38 **** { int index; ! if (code < 0 || code >= 0x110000) index = 0; else { --- 34,38 ---- { int index; ! if (code >= 0x110000) index = 0; else { *************** *** 259,263 **** get_decomp_record(Py_UCS4 code, int *index, int *prefix, int *count) { ! if (code < 0 || code >= 0x110000) { *index = 0; } --- 259,263 ---- get_decomp_record(Py_UCS4 code, int *index, int *prefix, int *count) { ! if (code >= 0x110000) { *index = 0; } From nnorwitz@users.sourceforge.net Fri Feb 28 03:16:09 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Thu, 27 Feb 2003 19:16:09 -0800 Subject: [Python-checkins] python/dist/src/Parser pgen.c,2.22,2.23 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv31746/Parser Modified Files: pgen.c Log Message: Remove setting i since it isn't used. Found in unrelated bug 690012. Index: pgen.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/pgen.c,v retrieving revision 2.22 retrieving revision 2.23 diff -C2 -d -r2.22 -r2.23 *** pgen.c 31 May 2002 13:11:40 -0000 2.22 --- pgen.c 28 Feb 2003 03:16:07 -0000 2.23 *************** *** 284,291 **** compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - REQ(n, ATOM); - i = n->n_nchildren; REQN(i, 1); n = n->n_child; --- 284,288 ---- From rhettinger@users.sourceforge.net Fri Feb 28 05:11:05 2003 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Thu, 27 Feb 2003 21:11:05 -0800 Subject: [Python-checkins] python/dist/src/Include abstract.h,2.46,2.47 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv29966 Modified Files: abstract.h Log Message: Fix spelling and grammar. Index: abstract.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/abstract.h,v retrieving revision 2.46 retrieving revision 2.47 diff -C2 -d -r2.46 -r2.47 *** abstract.h 25 Nov 2002 15:06:29 -0000 2.46 --- abstract.h 28 Feb 2003 05:11:03 -0000 2.47 *************** *** 49,53 **** components of a Python C interface consisting of several components. ! From the viewpoint of of C access to Python services, we have (as suggested by Guido in off-line discussions): --- 49,53 ---- components of a Python C interface consisting of several components. ! From the viewpoint of C access to Python services, we have (as suggested by Guido in off-line discussions): *************** *** 69,73 **** interface provided by the standard built-in types, such as floats, strings, and lists. This interface exists and is currently ! documented by the collection of include files provides with the Python distributions. --- 69,73 ---- interface provided by the standard built-in types, such as floats, strings, and lists. This interface exists and is currently ! documented by the collection of include files provided with the Python distributions. *************** *** 468,472 **** 0 is returned on success. buffer and buffer_len are only ! set in case no error occurrs. Otherwise, -1 is returned and an exception set. --- 468,472 ---- 0 is returned on success. buffer and buffer_len are only ! set in case no error occurs. Otherwise, -1 is returned and an exception set. *************** *** 705,709 **** /* ! Returns the result of bitwise or or o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1|o2. --- 705,709 ---- /* ! Returns the result of bitwise or on o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1|o2. *************** *** 1042,1046 **** PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if error. ! PY_ITERSEARCH_INDEX: return 0-based index of first occurence of obj in seq; set ValueError and return -1 if none found; also return -1 on error. --- 1042,1046 ---- PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if error. ! PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of obj in seq; set ValueError and return -1 if none found; also return -1 on error. From jvr@users.sourceforge.net Fri Feb 28 08:54:04 2003 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Fri, 28 Feb 2003 00:54:04 -0800 Subject: [Python-checkins] python/dist/src/Modules zipimport.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9323/Modules Modified Files: zipimport.c Log Message: use proper constant instead of comment (noted by nnorwitz) Index: zipimport.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/zipimport.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** zipimport.c 18 Feb 2003 03:37:49 -0000 1.10 --- zipimport.c 28 Feb 2003 08:54:01 -0000 1.11 *************** *** 665,669 **** return NULL; } ! fseek(fp, -22, 2); /* Seek from end of file */ header_end = ftell(fp); if (fread(endof_central_dir, 1, 22, fp) != 22) { --- 665,669 ---- return NULL; } ! fseek(fp, -22, SEEK_END); header_end = ftell(fp); if (fread(endof_central_dir, 1, 22, fp) != 22) { From jackjansen@users.sourceforge.net Fri Feb 28 12:51:21 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 28 Feb 2003 04:51:21 -0800 Subject: [Python-checkins] python/dist/src/Include py_curses.h,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv4384 Modified Files: py_curses.h Log Message: Moved the Apple workaround for the guard define for wchar_t out of the #ifdef HAVE_NCURSES_H: the same problem exists on OSX 10.1 with a fink-installed curses (which uses curses.h as the include file name). Index: py_curses.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/py_curses.h,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** py_curses.h 22 Nov 2002 16:12:57 -0000 1.5 --- py_curses.h 28 Feb 2003 12:51:18 -0000 1.6 *************** *** 3,7 **** #define Py_CURSES_H - #ifdef HAVE_NCURSES_H #ifdef __APPLE__ /* --- 3,6 ---- *************** *** 13,16 **** --- 12,17 ---- #endif #endif + + #ifdef HAVE_NCURSES_H #include #else From gvanrossum@users.sourceforge.net Fri Feb 28 14:11:49 2003 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Fri, 28 Feb 2003 06:11:49 -0800 Subject: [Python-checkins] python/dist/src/Doc/ref ref3.tex,1.99,1.100 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ref In directory sc8-pr-cvs1:/tmp/cvs-serv20937 Modified Files: ref3.tex Log Message: SF doc patch #692001, properties and __getattribute__. I added some stuff, and changed 'property' to 'descriptor'. Index: ref3.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ref/ref3.tex,v retrieving revision 1.99 retrieving revision 1.100 diff -C2 -d -r1.99 -r1.100 *** ref3.tex 31 Jan 2003 18:52:45 -0000 1.99 --- ref3.tex 28 Feb 2003 14:11:45 -0000 1.100 *************** *** 1156,1162 **** attribute access (use of, assignment to, or deletion of \code{x.name}) for class instances. - For performance reasons, these methods are cached in the class object - at class definition time; therefore, they cannot be changed after the - class definition is executed. \begin{methoddesc}[object]{__getattr__}{self, name} --- 1156,1159 ---- *************** *** 1172,1179 **** This is done both for efficiency reasons and because otherwise \method{__setattr__()} would have no way to access other attributes of ! the instance. ! Note that at least for instance variables, you can fake ! total control by not inserting any values in the instance ! attribute dictionary (but instead inserting them in another object). \withsubitem{(object method)}{\ttindex{__setattr__()}} \end{methoddesc} --- 1169,1177 ---- This is done both for efficiency reasons and because otherwise \method{__setattr__()} would have no way to access other attributes of ! the instance. Note that at least for instance variables, you can fake ! total control by not inserting any values in the instance attribute ! dictionary (but instead inserting them in another object). See the ! \method{__getattribute__()} method below for a way to actually get ! total control in new-style classes. \withsubitem{(object method)}{\ttindex{__setattr__()}} \end{methoddesc} *************** *** 1189,1193 **** would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., ! \samp{self.__dict__[\var{name}] = value}. \withsubitem{(instance attribute)}{\ttindex{__dict__}} \end{methoddesc} --- 1187,1194 ---- would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., ! \samp{self.__dict__[\var{name}] = value}. For new-style classes, ! rather than accessing the instance dictionary, it should call the base ! class method with the same name, for example, ! \samp{object.__setattr__(self, name, value)}. \withsubitem{(instance attribute)}{\ttindex{__dict__}} \end{methoddesc} *************** *** 1197,1200 **** --- 1198,1246 ---- assignment. This should only be implemented if \samp{del obj.\var{name}} is meaningful for the object. + \end{methoddesc} + + \subsubsection{More attribute access for new-style classes \lable{new-style-attribute-access}} + + The following methods only apply to new-style classes. + + \begin{methoddesc}[object]{__getattribute__}{self, name} + Called unconditionally to implement attribute accesses for instances + of the class. If the class also defines \method{__getattr__}, it will + never be called (unless called explicitly). + This method should return the (computed) attribute + value or raise an \exception{AttributeError} exception. + In order to avoid infinite recursion in this method, its + implementation should always call the base class method with the same + name to access any attributes it needs to access, for example, + \samp{object.__getattribute__(self, name)}. + \end{methoddesc} + + \subsubsubsection{Implementing Descriptors \label{descriptors}} + + The following methods only apply when an instance of the class + containing the method (a so-called \emph{descriptor} class) is in + the class dictionary of another new-style class, known as the + \emph{owner} class. In the examples below, ``the attribute'' refers to + the attribute whose name is the key of the property in the accessed + class' \code{__dict__}. + + \begin{methoddesc}[object]{__get__}{self, instance, owner} + Called to get the attribute of the owner class (class attribute acess) + or of an instance of that class (instance attribute acces). + \var{owner} is always the owner class, while \var{instance} is the + instance that the attribute was accessed through, or \code{None} when + the attribute is accessed through the \var{owner}. This method should + return the (computed) attribute value or raise an + \exception{AttributeError} exception. + \end{methoddesc} + + \begin{methoddesc}[object]{__set__}{self, instance, value} + Called to set the attribute on an instance \{instance} of the owner + class to a new value, \var{value}. + \end{methoddesc} + + \begin{methoddesc}[object]{__delete__}{self, instance} + Called to delete the attribute on an instance \{instance} of the owner + class. \end{methoddesc} From jackjansen@users.sourceforge.net Fri Feb 28 15:19:04 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 28 Feb 2003 07:19:04 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PythonIDEMain.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv22249 Modified Files: PythonIDEMain.py Log Message: Removed silly print. Index: PythonIDEMain.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PythonIDEMain.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** PythonIDEMain.py 25 Feb 2003 15:08:02 -0000 1.29 --- PythonIDEMain.py 28 Feb 2003 15:18:59 -0000 1.30 *************** *** 354,358 **** import PackageManager PackageManager.PackageBrowser() - print "Done" def makehelpmenu(self): --- 354,357 ---- From jackjansen@users.sourceforge.net Fri Feb 28 15:19:53 2003 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Fri, 28 Feb 2003 07:19:53 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PackageManager.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv22604 Modified Files: PackageManager.py Log Message: Check modes on install and temporary directories. Fixes #693230. Index: PackageManager.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PackageManager.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PackageManager.py 14 Feb 2003 14:13:25 -0000 1.3 --- PackageManager.py 28 Feb 2003 15:19:51 -0000 1.4 *************** *** 228,232 **** except IOError, arg: return "Cannot open %s: %s" % (url, arg) ! return None def closepimp(self): --- 228,232 ---- except IOError, arg: return "Cannot open %s: %s" % (url, arg) ! return self.pimpprefs.check() def closepimp(self): From bwarsaw@users.sourceforge.net Fri Feb 28 15:27:43 2003 From: bwarsaw@users.sourceforge.net (bwarsaw@users.sourceforge.net) Date: Fri, 28 Feb 2003 07:27:43 -0800 Subject: [Python-checkins] python/dist/src/Parser pgen.c,2.23,2.24 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv26527 Modified Files: pgen.c Log Message: compile_atom(): Neal's last checkin removing the setting of i broke the build, so I'm restoring it. I'm not sure what Neal's intent was, since the line following the one he removed was "REQN(i, 1)" so i is obviously used. ;) Index: pgen.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/pgen.c,v retrieving revision 2.23 retrieving revision 2.24 diff -C2 -d -r2.23 -r2.24 *** pgen.c 28 Feb 2003 03:16:07 -0000 2.23 --- pgen.c 28 Feb 2003 15:27:40 -0000 2.24 *************** *** 284,288 **** --- 284,291 ---- compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { + int i; + REQ(n, ATOM); + i = n->n_nchildren; REQN(i, 1); n = n->n_child; From neal@metaslash.com Fri Feb 28 15:36:40 2003 From: neal@metaslash.com (Neal Norwitz) Date: Fri, 28 Feb 2003 10:36:40 -0500 Subject: [Python-checkins] python/dist/src/Parser pgen.c,2.23,2.24 In-Reply-To: References: Message-ID: <20030228153639.GX2041@epoch.metaslash.com> On Fri, Feb 28, 2003 at 07:27:43AM -0800, bwarsaw@users.sourceforge.net wrote: > > compile_atom(): Neal's last checkin removing the setting of i broke > the build, so I'm restoring it. I'm not sure what Neal's intent was, > since the line following the one he removed was "REQN(i, 1)" so i is > obviously used. ;) Sorry about that. Now I see that i is used in debug builds, but unused in non-debug builds. Neal From nnorwitz@users.sourceforge.net Fri Feb 28 17:21:41 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 09:21:41 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.151,1.152 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv13513 Modified Files: setup.py Log Message: Fix SF bug #690012 (among others), iconv_codec stops build Change setup.py to catch all exceptions. - Rename module if the exception was an ImportError - Only warn if the exception was any other error Revert _iconv_codec to raising a RuntimeError. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.151 retrieving revision 1.152 diff -C2 -d -r1.151 -r1.152 *** setup.py 24 Feb 2003 12:56:36 -0000 1.151 --- setup.py 28 Feb 2003 17:21:37 -0000 1.152 *************** *** 208,214 **** try: imp.load_dynamic(ext.name, ext_filename) ! except ImportError, why: ! if 1: self.announce('*** WARNING: renaming "%s" since importing it' ' failed: %s' % (ext.name, why), level=3) --- 208,215 ---- try: imp.load_dynamic(ext.name, ext_filename) ! except: ! exc_type, why, tb = sys.exc_info() ! if issubclass(exc_type, ImportError): self.announce('*** WARNING: renaming "%s" since importing it' ' failed: %s' % (ext.name, why), level=3) *************** *** 232,236 **** else: self.announce('*** WARNING: importing extension "%s" ' ! 'failed: %s' % (ext.name, why), level=3) def get_platform (self): --- 233,238 ---- else: self.announce('*** WARNING: importing extension "%s" ' ! 'failed with %s: %s' % (ext.name, exc_type, why), ! level=3) def get_platform (self): From nnorwitz@users.sourceforge.net Fri Feb 28 17:21:42 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 09:21:42 -0800 Subject: [Python-checkins] python/dist/src/Modules _iconv_codec.c,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv13513/Modules Modified Files: _iconv_codec.c Log Message: Fix SF bug #690012 (among others), iconv_codec stops build Change setup.py to catch all exceptions. - Rename module if the exception was an ImportError - Only warn if the exception was any other error Revert _iconv_codec to raising a RuntimeError. Index: _iconv_codec.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_iconv_codec.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _iconv_codec.c 24 Feb 2003 20:17:32 -0000 1.13 --- _iconv_codec.c 28 Feb 2003 17:21:39 -0000 1.14 *************** *** 675,679 **** if (hdl == (iconv_t)-1) { ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: iconv_open() failed"); return; --- 675,679 ---- if (hdl == (iconv_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: iconv_open() failed"); return; *************** *** 682,686 **** res = iconv(hdl, &inptr, &insize, &outptr, &outsize); if (res == (size_t)-1) { ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: iconv() failed"); return; --- 682,686 ---- res = iconv(hdl, &inptr, &insize, &outptr, &outsize); if (res == (size_t)-1) { ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: iconv() failed"); return; *************** *** 699,703 **** else { iconv_close(hdl); ! PyErr_SetString(PyExc_ImportError, "can't initialize the _iconv_codec module: mixed endianess"); return; --- 699,703 ---- else { iconv_close(hdl); ! PyErr_SetString(PyExc_RuntimeError, "can't initialize the _iconv_codec module: mixed endianess"); return; From nnorwitz@users.sourceforge.net Fri Feb 28 17:24:05 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 09:24:05 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.680,1.681 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv15517/Misc Modified Files: NEWS Log Message: Fix SF bug #690012 Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.680 retrieving revision 1.681 diff -C2 -d -r1.680 -r1.681 *** NEWS 27 Feb 2003 22:52:58 -0000 1.680 --- NEWS 28 Feb 2003 17:24:00 -0000 1.681 *************** *** 40,43 **** --- 40,45 ---- ----- + - Fix build problems when _iconv_codec failed. (SF bug #690012.) + - Fix problem building on OSF1 because the compiler only accepted preprocessor directives that start in column 1. (SF bug #691793.) From nnorwitz@users.sourceforge.net Fri Feb 28 17:39:46 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 09:39:46 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.152,1.153 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv22963 Modified Files: setup.py Log Message: Just pointed out the code was better written with try: # ... except ImportError, why: except: # ... All other changes are re-indenting/formatting. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.152 retrieving revision 1.153 diff -C2 -d -r1.152 -r1.153 *** setup.py 28 Feb 2003 17:21:37 -0000 1.152 --- setup.py 28 Feb 2003 17:39:42 -0000 1.153 *************** *** 208,238 **** try: imp.load_dynamic(ext.name, ext_filename) ! except: exc_type, why, tb = sys.exc_info() ! if issubclass(exc_type, ImportError): ! self.announce('*** WARNING: renaming "%s" since importing it' ! ' failed: %s' % (ext.name, why), level=3) ! assert not self.inplace ! basename, tail = os.path.splitext(ext_filename) ! newname = basename + "_failed" + tail ! if os.path.exists(newname): os.remove(newname) ! os.rename(ext_filename, newname) ! ! # XXX -- This relies on a Vile HACK in ! # distutils.command.build_ext.build_extension(). The ! # _built_objects attribute is stored there strictly for ! # use here. ! # If there is a failure, _built_objects may not be there, ! # so catch the AttributeError and move on. ! try: ! for filename in self._built_objects: ! os.remove(filename) ! except AttributeError: ! self.announce('unable to remove files (ignored)') ! else: ! self.announce('*** WARNING: importing extension "%s" ' ! 'failed with %s: %s' % (ext.name, exc_type, why), ! level=3) def get_platform (self): --- 208,237 ---- try: imp.load_dynamic(ext.name, ext_filename) ! except ImportError, why: ! self.announce('*** WARNING: renaming "%s" since importing it' ! ' failed: %s' % (ext.name, why), level=3) ! assert not self.inplace ! basename, tail = os.path.splitext(ext_filename) ! newname = basename + "_failed" + tail ! if os.path.exists(newname): ! os.remove(newname) ! os.rename(ext_filename, newname) + # XXX -- This relies on a Vile HACK in + # distutils.command.build_ext.build_extension(). The + # _built_objects attribute is stored there strictly for + # use here. + # If there is a failure, _built_objects may not be there, + # so catch the AttributeError and move on. + try: + for filename in self._built_objects: + os.remove(filename) + except AttributeError: + self.announce('unable to remove files (ignored)') + except: exc_type, why, tb = sys.exc_info() ! self.announce('*** WARNING: importing extension "%s" ' ! 'failed with %s: %s' % (ext.name, exc_type, why), ! level=3) def get_platform (self): From nnorwitz@users.sourceforge.net Fri Feb 28 19:53:43 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 11:53:43 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.131,1.132 test_timeout.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv18489/Lib/test Modified Files: regrtest.py test_timeout.py Log Message: Fix SF bugs #692951 and 692988, test_timeout.py needs 'network' resource require -u network to run test_timeout since it fails when not connected to a network. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.131 retrieving revision 1.132 diff -C2 -d -r1.131 -r1.132 *** regrtest.py 26 Feb 2003 19:51:23 -0000 1.131 --- regrtest.py 28 Feb 2003 19:53:32 -0000 1.132 *************** *** 544,547 **** --- 544,550 ---- # Controlled by test_socket_ssl.skip_expected. Requires the network # resource, and a socket module with ssl support. + # test_timeout + # Controlled by test_timeout.skip_expected. Requires the network + # resource and a socket module. _expectations = { *************** *** 946,949 **** --- 949,953 ---- from test import test_normalization from test import test_socket_ssl + from test import test_timeout self.valid = False *************** *** 960,963 **** --- 964,970 ---- if test_socket_ssl.skip_expected: self.expected.add('test_socket_ssl') + + if test_timeout.skip_expected: + self.expected.add('test_timeout') if not sys.platform in ("mac", "darwin"): Index: test_timeout.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_timeout.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_timeout.py 21 Feb 2003 16:45:41 -0000 1.11 --- test_timeout.py 28 Feb 2003 19:53:34 -0000 1.12 *************** *** 4,7 **** --- 4,10 ---- from test import test_support + # This requires the 'network' resource as given on the regrtest command line. + skip_expected = not test_support.is_resource_enabled('network') + import time import socket *************** *** 183,186 **** --- 186,191 ---- def test_main(): + test_support.requires('network') + suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CreationTestCase)) From nnorwitz@users.sourceforge.net Fri Feb 28 19:57:14 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 11:57:14 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.681,1.682 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv20202/Misc Modified Files: NEWS Log Message: Fix SF bugs #692951 and 692988, test_timeout.py needs 'network' resource require -u network to run test_timeout since it fails when not connected to a network. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.681 retrieving revision 1.682 diff -C2 -d -r1.681 -r1.682 *** NEWS 28 Feb 2003 17:24:00 -0000 1.681 --- NEWS 28 Feb 2003 19:57:03 -0000 1.682 *************** *** 58,62 **** ----- ! TBD Windows --- 58,63 ---- ----- ! - test_timeout now requires -u network to be passed to regrtest to run. ! See SF bug #692988. Windows From nnorwitz@users.sourceforge.net Fri Feb 28 20:00:46 2003 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Fri, 28 Feb 2003 12:00:46 -0800 Subject: [Python-checkins] python/dist/src/Lib/encodings __init__.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/encodings In directory sc8-pr-cvs1:/tmp/cvs-serv21839/Lib/encodings Modified Files: __init__.py Log Message: Handle iconv initialization erorrs Index: __init__.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/encodings/__init__.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** __init__.py 26 Jan 2003 11:27:16 -0000 1.15 --- __init__.py 28 Feb 2003 20:00:42 -0000 1.16 *************** *** 125,128 **** try: import iconv_codec ! except ImportError: pass --- 125,128 ---- try: import iconv_codec ! except (ImportError, RuntimeError): pass From akuchling@users.sourceforge.net Fri Feb 28 21:23:05 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:23:05 -0800 Subject: [Python-checkins] distutils/test/dists - New directory Message-ID: Update of /cvsroot/python/distutils/test/dists In directory sc8-pr-cvs1:/tmp/cvs-serv24114/dists Log Message: Directory /cvsroot/python/distutils/test/dists added to the repository From akuchling@users.sourceforge.net Fri Feb 28 21:23:31 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:23:31 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path - New directory Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path In directory sc8-pr-cvs1:/tmp/cvs-serv24361/compiler_path Log Message: Directory /cvsroot/python/distutils/test/dists/compiler_path added to the repository From akuchling@users.sourceforge.net Fri Feb 28 21:23:46 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:23:46 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path/dir1 - New directory Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path/dir1 In directory sc8-pr-cvs1:/tmp/cvs-serv24466/compiler_path/dir1 Log Message: Directory /cvsroot/python/distutils/test/dists/compiler_path/dir1 added to the repository From akuchling@users.sourceforge.net Fri Feb 28 21:23:47 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:23:47 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path/dir2 - New directory Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path/dir2 In directory sc8-pr-cvs1:/tmp/cvs-serv24466/compiler_path/dir2 Log Message: Directory /cvsroot/python/distutils/test/dists/compiler_path/dir2 added to the repository From akuchling@users.sourceforge.net Fri Feb 28 21:28:06 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:28:06 -0800 Subject: [Python-checkins] distutils/test/dists README.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/distutils/test/dists In directory sc8-pr-cvs1:/tmp/cvs-serv26365 Added Files: README.txt Log Message: Add a directory for Distutil test examples that require a distribution of some sort --- NEW FILE: README.txt --- Test cases that contain a full setup.py and associated files. There's no way to run these automatically. From akuchling@users.sourceforge.net Fri Feb 28 21:28:08 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:28:08 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path/dir1 foo.c,NONE,1.1 Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path/dir1 In directory sc8-pr-cvs1:/tmp/cvs-serv26365/compiler_path/dir1 Added Files: foo.c Log Message: Add a directory for Distutil test examples that require a distribution of some sort --- NEW FILE: foo.c --- /* Empty file */ From akuchling@users.sourceforge.net Fri Feb 28 21:28:07 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:28:07 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path README.txt,NONE,1.1 foo.c,NONE,1.1 setup.py,NONE,1.1 Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path In directory sc8-pr-cvs1:/tmp/cvs-serv26365/compiler_path Added Files: README.txt foo.c setup.py Log Message: Add a directory for Distutil test examples that require a distribution of some sort --- NEW FILE: README.txt --- Tests compilation of C files with multiple source modules with the same name. --- NEW FILE: foo.c --- /* Empty file */ --- NEW FILE: setup.py --- import os from distutils.core import setup from distutils.extension import Extension setup( name="compiler_path", version="1.0", ext_modules=[Extension(name='foo', sources=['dir1/foo.c', 'dir2/foo.c', os.path.join(os.getcwd(), 'foo.c')])] ) From akuchling@users.sourceforge.net Fri Feb 28 21:28:09 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 13:28:09 -0800 Subject: [Python-checkins] distutils/test/dists/compiler_path/dir2 foo.c,NONE,1.1 Message-ID: Update of /cvsroot/python/distutils/test/dists/compiler_path/dir2 In directory sc8-pr-cvs1:/tmp/cvs-serv26365/compiler_path/dir2 Added Files: foo.c Log Message: Add a directory for Distutil test examples that require a distribution of some sort --- NEW FILE: foo.c --- /* Empty file */ From akuchling@users.sourceforge.net Fri Feb 28 22:03:10 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 14:03:10 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils/command build_py.py,1.41,1.42 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils/command In directory sc8-pr-cvs1:/tmp/cvs-serv8488 Modified Files: build_py.py Log Message: [Patch #695090 from Bernhard Herzog] Allow specifying both py_modules and packages Index: build_py.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/command/build_py.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** build_py.py 19 Nov 2002 13:12:28 -0000 1.41 --- build_py.py 28 Feb 2003 22:03:04 -0000 1.42 *************** *** 87,109 **** # and 'py_modules'. The former lets us work with whole packages, not # specifying individual modules at all; the latter is for ! # specifying modules one-at-a-time. Currently they are mutually ! # exclusive: you can define one or the other (or neither), but not ! # both. It remains to be seen how limiting this is. ! ! # Dispose of the two "unusual" cases first: no pure Python modules ! # at all (no problem, just return silently), and over-specified ! # 'packages' and 'py_modules' options. ! ! if not self.py_modules and not self.packages: ! return ! if self.py_modules and self.packages: ! raise DistutilsOptionError, \ ! "build_py: supplying both 'packages' and 'py_modules' " + \ ! "options is not allowed" - # Now we're down to two cases: 'py_modules' only and 'packages' only. if self.py_modules: self.build_modules() ! else: self.build_packages() --- 87,95 ---- # and 'py_modules'. The former lets us work with whole packages, not # specifying individual modules at all; the latter is for ! # specifying modules one-at-a-time. if self.py_modules: self.build_modules() ! if self.packages: self.build_packages() *************** *** 277,284 **** 'find_package_modules()' do.""" if self.py_modules: ! modules = self.find_modules() ! else: ! modules = [] for package in self.packages: package_dir = self.get_package_dir(package) --- 263,270 ---- 'find_package_modules()' do.""" + modules = [] if self.py_modules: ! modules.extend(self.find_modules()) ! if self.packages: for package in self.packages: package_dir = self.get_package_dir(package) From akuchling@users.sourceforge.net Fri Feb 28 22:09:41 2003 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Fri, 28 Feb 2003 14:09:41 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.682,1.683 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv11311 Modified Files: NEWS Log Message: Add news item for patch #695090 Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.682 retrieving revision 1.683 diff -C2 -d -r1.682 -r1.683 *** NEWS 28 Feb 2003 19:57:03 -0000 1.682 --- NEWS 28 Feb 2003 22:09:33 -0000 1.683 *************** *** 32,35 **** --- 32,39 ---- strings.) + - Distutils: both 'py_modules' and 'packages' keywords can now be specified + in core.setup(). Previously you could supply one or the other, but + not both of them. (SF patch #695090 from Bernhard Herzog) + Tools/Demos -----------