From python-3000-checkins at python.org Sat Jan 6 14:29:15 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 6 Jan 2007 14:29:15 +0100 (CET) Subject: [Python-3000-checkins] r53288 - python/branches/p3yk/Python/Python-ast.c Message-ID: <20070106132915.3D8FD1E4002@bag.python.org> Author: martin.v.loewis Date: Sat Jan 6 14:29:14 2007 New Revision: 53288 Modified: python/branches/p3yk/Python/Python-ast.c Log: Commit __version__ change. Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Sat Jan 6 14:29:14 2007 @@ -3126,7 +3126,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "52491") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53170") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From python-3000-checkins at python.org Sat Jan 6 14:49:09 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 6 Jan 2007 14:49:09 +0100 (CET) Subject: [Python-3000-checkins] r53289 - python/branches/p3yk/PCbuild/pythoncore.vcproj Message-ID: <20070106134909.841BE1E4002@bag.python.org> Author: martin.v.loewis Date: Sat Jan 6 14:49:08 2007 New Revision: 53289 Modified: python/branches/p3yk/PCbuild/pythoncore.vcproj Log: Add the bytes type to the build process. Modified: python/branches/p3yk/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/p3yk/PCbuild/pythoncore.vcproj (original) +++ python/branches/p3yk/PCbuild/pythoncore.vcproj Sat Jan 6 14:49:08 2007 @@ -437,6 +437,9 @@ RelativePath="..\Objects\bufferobject.c"> + + Author: thomas.wouters Date: Wed Jan 10 00:18:33 2007 New Revision: 53332 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/README python/branches/p3yk/Doc/api/newtypes.tex python/branches/p3yk/Doc/howto/functional.rst python/branches/p3yk/Doc/lib/libbsddb.tex python/branches/p3yk/Doc/lib/libbz2.tex python/branches/p3yk/Doc/lib/libctypes.tex python/branches/p3yk/Doc/lib/libfuncs.tex python/branches/p3yk/Doc/lib/liblogging.tex python/branches/p3yk/Doc/lib/libmmap.tex python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex python/branches/p3yk/Doc/lib/libsocket.tex python/branches/p3yk/Doc/lib/libsqlite3.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libtarfile.tex python/branches/p3yk/Doc/lib/libtest.tex python/branches/p3yk/Doc/lib/liburlparse.tex python/branches/p3yk/Doc/mac/toolbox.tex python/branches/p3yk/Doc/whatsnew/whatsnew25.tex python/branches/p3yk/LICENSE python/branches/p3yk/Lib/CGIHTTPServer.py python/branches/p3yk/Lib/SimpleHTTPServer.py python/branches/p3yk/Lib/StringIO.py python/branches/p3yk/Lib/bsddb/dbobj.py python/branches/p3yk/Lib/bsddb/test/test_1413192.py python/branches/p3yk/Lib/bsddb/test/test_associate.py python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_dbobj.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py python/branches/p3yk/Lib/bsddb/test/test_dbtables.py python/branches/p3yk/Lib/bsddb/test/test_env_close.py python/branches/p3yk/Lib/bsddb/test/test_join.py python/branches/p3yk/Lib/bsddb/test/test_lock.py python/branches/p3yk/Lib/bsddb/test/test_misc.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/cookielib.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/heapq.py python/branches/p3yk/Lib/hmac.py python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk/Lib/idlelib/NEWS.txt python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/pty.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/sre_parse.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_dumbdbm.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_import.py python/branches/p3yk/Lib/test/test_pty.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_repr.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_uu.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/threading.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Misc/ACKS python/branches/p3yk/Misc/developers.txt python/branches/p3yk/Modules/_bsddb.c python/branches/p3yk/Modules/bz2module.c python/branches/p3yk/Modules/collectionsmodule.c python/branches/p3yk/Modules/main.c python/branches/p3yk/Modules/socketmodule.c python/branches/p3yk/Modules/timemodule.c python/branches/p3yk/Objects/dictnotes.txt python/branches/p3yk/Objects/setobject.c python/branches/p3yk/PC/python_nt.rc python/branches/p3yk/PCbuild/python20.wse python/branches/p3yk/PCbuild8/python20.wse python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/errors.c python/branches/p3yk/Python/getcopyright.c python/branches/p3yk/README python/branches/p3yk/setup.py Log: Merged revisions 53005-53303 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53012 | walter.doerwald | 2006-12-12 22:55:31 +0100 (Tue, 12 Dec 2006) | 2 lines Fix typo. ........ r53023 | brett.cannon | 2006-12-13 23:31:37 +0100 (Wed, 13 Dec 2006) | 2 lines Remove an unneeded import of 'warnings'. ........ r53025 | brett.cannon | 2006-12-14 00:02:38 +0100 (Thu, 14 Dec 2006) | 2 lines Remove unneeded imports of 'warnings'. ........ r53026 | brett.cannon | 2006-12-14 00:09:53 +0100 (Thu, 14 Dec 2006) | 4 lines Add test.test_support.guard_warnings_filter . This function returns a context manager that protects warnings.filter from being modified once the context is exited. ........ r53029 | george.yoshida | 2006-12-14 03:22:44 +0100 (Thu, 14 Dec 2006) | 2 lines Note that guard_warnings_filter was added in 2.6 ........ r53031 | vinay.sajip | 2006-12-14 09:53:55 +0100 (Thu, 14 Dec 2006) | 1 line Added news on recent changes to logging ........ r53032 | andrew.kuchling | 2006-12-14 19:57:53 +0100 (Thu, 14 Dec 2006) | 1 line [Patch #1599256 from David Watson] check that os.fsync is available before using it ........ r53042 | kurt.kaiser | 2006-12-15 06:13:11 +0100 (Fri, 15 Dec 2006) | 6 lines 1. Avoid hang when encountering a duplicate in a completion list. Bug 1571112. 2. Duplicate some old entries from Python's NEWS to IDLE's NEWS.txt M AutoCompleteWindow.py M NEWS.txt ........ r53048 | andrew.kuchling | 2006-12-18 18:12:31 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1618083] Add missing word; make a few grammar fixes ........ r53050 | andrew.kuchling | 2006-12-18 18:16:05 +0100 (Mon, 18 Dec 2006) | 1 line Bump version ........ r53051 | andrew.kuchling | 2006-12-18 18:22:07 +0100 (Mon, 18 Dec 2006) | 1 line [Bug #1616726] Fix description of generator.close(); if you raise some random exception, the exception is raised and doesn't trigger a RuntimeError ........ r53052 | andrew.kuchling | 2006-12-18 18:38:14 +0100 (Mon, 18 Dec 2006) | 1 line Describe new methods in Queue module ........ r53053 | andrew.kuchling | 2006-12-18 20:22:24 +0100 (Mon, 18 Dec 2006) | 1 line [Patch #1615868 by Lars Gustaebel] Use Py_off_t to fix BZ2File.seek() for offsets > 2Gb ........ r53057 | andrew.kuchling | 2006-12-18 22:29:07 +0100 (Mon, 18 Dec 2006) | 1 line Fix markup ........ r53063 | thomas.wouters | 2006-12-19 09:17:50 +0100 (Tue, 19 Dec 2006) | 5 lines Make sre's SubPattern objects accept slice objects like it already accepts simple slices. ........ r53065 | andrew.kuchling | 2006-12-19 15:13:05 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1618455 by Ben Maurer] Improve speed of HMAC by using str.translate() instead of a more general XOR that has to construct a list. Slightly modified from Maurer's patch: the _strxor() function is no longer necessary at all. ........ r53066 | andrew.kuchling | 2006-12-19 15:28:23 +0100 (Tue, 19 Dec 2006) | 9 lines [Bug #1613651] Document socket.recv_into, socket.recvfrom_into Also, the text for recvfrom told you to read recv() for an explanation of the 'flags' argument, but recv() just pointed you at the man page. Copied the man-page text to recvfrom(), recvfrom_into, recv_into to avoid the pointless redirection. I don't have LaTeX on this machine; hope my markup is OK. ........ r53067 | andrew.kuchling | 2006-12-19 15:29:04 +0100 (Tue, 19 Dec 2006) | 1 line Comment typo ........ r53068 | andrew.kuchling | 2006-12-19 16:11:41 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1617413 from Dug Song] Fix HTTP Basic authentication via HTTPS ........ r53071 | andrew.kuchling | 2006-12-19 16:18:12 +0100 (Tue, 19 Dec 2006) | 1 line [Patch #1600491 from Jim Jewett] Describe how to build help files on Windows ........ r53073 | andrew.kuchling | 2006-12-19 16:43:10 +0100 (Tue, 19 Dec 2006) | 6 lines [Patch #1587139 by kxroberto] Protect lock acquisition/release with try...finally to ensure the lock is always released. This could use the 'with' statement, but the patch uses 'finally'. 2.5 backport candidate. ........ r53074 | vinay.sajip | 2006-12-19 19:29:11 +0100 (Tue, 19 Dec 2006) | 1 line Updated documentation for findCaller() to indicate that a 3-tuple is now returned, rather than a 2-tuple. ........ r53090 | georg.brandl | 2006-12-19 23:06:46 +0100 (Tue, 19 Dec 2006) | 3 lines Patch #1484695: The tarfile module now raises a HeaderError exception if a buffer given to frombuf() is invalid. ........ r53099 | raymond.hettinger | 2006-12-20 07:42:06 +0100 (Wed, 20 Dec 2006) | 5 lines Bug #1590891: random.randrange don't return correct value for big number Needs to be backported. ........ r53106 | georg.brandl | 2006-12-20 12:55:16 +0100 (Wed, 20 Dec 2006) | 3 lines Testcase for patch #1484695. ........ r53110 | andrew.kuchling | 2006-12-20 20:48:20 +0100 (Wed, 20 Dec 2006) | 17 lines [Apply length-checking.diff from bug #1599254] Add length checking to single-file mailbox formats: before doing a flush() on a mailbox, seek to the end and verify its length is unchanged, raising ExternalClashError if the file's length has changed. This fix avoids potential data loss if some other process appends to the mailbox file after the table of contents has been generated; instead of overwriting the modified file, you'll get the exception. I also noticed that the self._lookup() call in self.flush() wasn't necessary (everything that sets self._pending to True also calls self.lookup()), and replaced it by an assertion. 2.5 backport candidate. ........ r53112 | andrew.kuchling | 2006-12-20 20:57:10 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619674] Make sum() use the term iterable, not sequence ........ r53113 | andrew.kuchling | 2006-12-20 20:58:11 +0100 (Wed, 20 Dec 2006) | 1 line Two grammar fixes ........ r53115 | andrew.kuchling | 2006-12-20 21:11:12 +0100 (Wed, 20 Dec 2006) | 5 lines Some other built-in functions are described with 'sequence' arguments that should really be 'iterable'; this commit changes them. Did I miss any? Did I introduce any errors? ........ r53117 | andrew.kuchling | 2006-12-20 21:20:42 +0100 (Wed, 20 Dec 2006) | 1 line [Bug #1619680] in_dll() arguments are documented in the wrong order ........ r53120 | neal.norwitz | 2006-12-21 05:38:00 +0100 (Thu, 21 Dec 2006) | 1 line Lars asked for permission on on python-dev for work on tarfile.py ........ r53125 | andrew.kuchling | 2006-12-21 14:40:29 +0100 (Thu, 21 Dec 2006) | 1 line Mention the os.SEEK_* constants ........ r53129 | walter.doerwald | 2006-12-21 19:06:30 +0100 (Thu, 21 Dec 2006) | 2 lines Fix typo. ........ r53131 | thomas.heller | 2006-12-21 19:30:56 +0100 (Thu, 21 Dec 2006) | 3 lines Fix wrong markup of an argument in a method signature. Will backport. ........ r53137 | andrew.kuchling | 2006-12-22 01:50:56 +0100 (Fri, 22 Dec 2006) | 1 line Typo fix ........ r53139 | andrew.kuchling | 2006-12-22 14:25:02 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #737202; fix from Titus Brown] Make CGIHTTPServer work for scripts in sub-directories ........ r53141 | andrew.kuchling | 2006-12-22 16:04:45 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128] Make the mode argument of dumbdbm actually work the way it's described, and add a test for it. 2.5 bugfix candidate, maybe; arguably this patch changes the API of dumbdbm and shouldn't be added in a point-release. ........ r53142 | andrew.kuchling | 2006-12-22 16:16:58 +0100 (Fri, 22 Dec 2006) | 6 lines [Bug #802128 continued] Modify mode depending on the process umask. Is there really no other way to read the umask than to set it? Hope this works on Windows... ........ r53145 | andrew.kuchling | 2006-12-22 17:43:26 +0100 (Fri, 22 Dec 2006) | 1 line [Bug #776202] Apply Walter Doerwald's patch to use text mode for encoded files ........ r53146 | andrew.kuchling | 2006-12-22 19:41:42 +0100 (Fri, 22 Dec 2006) | 9 lines [Patch #783050 from Patrick Lynch] The emulation of forkpty() is incorrect; the master should close the slave fd. Added a test to test_pty.py that reads from the master_fd after doing a pty.fork(); without the fix it hangs forever instead of raising an exception. () 2.5 backport candidate. ........ r53147 | andrew.kuchling | 2006-12-22 20:06:16 +0100 (Fri, 22 Dec 2006) | 1 line [Patch #827559 from Chris Gonnerman] Make SimpleHTTPServer redirect when a directory URL is missing the trailing slash; this lets relative links work. ........ r53149 | andrew.kuchling | 2006-12-22 20:21:27 +0100 (Fri, 22 Dec 2006) | 1 line Darn; this test works when you run test_pty.py directly, but fails when regrtest runs it (the os.read() raises os.error). I can't figure out the cause, so am commenting out the test. ........ r53150 | andrew.kuchling | 2006-12-22 22:48:19 +0100 (Fri, 22 Dec 2006) | 1 line Frak; this test also fails ........ r53153 | lars.gustaebel | 2006-12-23 17:40:13 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1230446: tarfile.py: fix ExFileObject so that read() and tell() work correctly together with readline(). Will backport to 2.5. ........ r53155 | lars.gustaebel | 2006-12-23 18:57:23 +0100 (Sat, 23 Dec 2006) | 5 lines Patch #1262036: Prevent TarFiles from being added to themselves under certain conditions. Will backport to 2.5. ........ r53159 | andrew.kuchling | 2006-12-27 04:25:31 +0100 (Wed, 27 Dec 2006) | 4 lines [Part of patch #1182394] Move the HMAC blocksize to be a class-level constant; this allows changing it in a subclass. To accommodate this, copy() now uses __class__. Also add some text to a comment. ........ r53160 | andrew.kuchling | 2006-12-27 04:31:24 +0100 (Wed, 27 Dec 2006) | 1 line [Rest of patch #1182394] Add ._current() method so that we can use the written-in-C .hexdigest() method ........ r53161 | lars.gustaebel | 2006-12-27 11:30:46 +0100 (Wed, 27 Dec 2006) | 4 lines Patch #1504073: Fix tarfile.open() for mode "r" with a fileobj argument. Will backport to 2.5. ........ r53165 | neal.norwitz | 2006-12-28 05:39:20 +0100 (Thu, 28 Dec 2006) | 1 line Remove a stray (old) macro name left around (I guess) ........ r53188 | neal.norwitz | 2006-12-29 04:01:53 +0100 (Fri, 29 Dec 2006) | 1 line SF bug #1623890, fix argument name in docstring ........ r53200 | raymond.hettinger | 2006-12-30 05:01:17 +0100 (Sat, 30 Dec 2006) | 1 line For sets with cyclical reprs, emit an ellipsis instead of infinitely recursing. ........ r53232 | brett.cannon | 2007-01-04 01:23:49 +0100 (Thu, 04 Jan 2007) | 3 lines Add EnvironmentVarGuard to test.test_support. Provides a context manager to temporarily set or unset environment variables. ........ r53235 | neal.norwitz | 2007-01-04 07:25:31 +0100 (Thu, 04 Jan 2007) | 1 line SF #1627373, fix typo in CarbonEvt. ........ r53244 | raymond.hettinger | 2007-01-04 18:53:34 +0100 (Thu, 04 Jan 2007) | 1 line Fix stability of heapq's nlargest() and nsmallest(). ........ r53249 | martin.v.loewis | 2007-01-04 22:06:12 +0100 (Thu, 04 Jan 2007) | 3 lines Bug #1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid relying on atexit. Will backport to 2.5. ........ r53252 | gregory.p.smith | 2007-01-05 02:59:42 +0100 (Fri, 05 Jan 2007) | 3 lines Support linking of the bsddb module against BerkeleyDB 4.5.x (will backport to 2.5) ........ r53253 | gregory.p.smith | 2007-01-05 03:06:17 +0100 (Fri, 05 Jan 2007) | 2 lines bump module version to match supported berkeleydb version ........ r53255 | neal.norwitz | 2007-01-05 06:25:22 +0100 (Fri, 05 Jan 2007) | 6 lines Prevent crash on shutdown which can occur if we are finalizing and the module dict has been cleared already and some object raises a warning (like in a __del__). Will backport. ........ r53258 | gregory.p.smith | 2007-01-05 08:21:35 +0100 (Fri, 05 Jan 2007) | 2 lines typo fix ........ r53260 | neal.norwitz | 2007-01-05 09:06:43 +0100 (Fri, 05 Jan 2007) | 1 line Add Collin Winter for access to update PEP 3107 ........ r53262 | andrew.kuchling | 2007-01-05 15:22:17 +0100 (Fri, 05 Jan 2007) | 1 line [Bug #1622533] Make docstrings raw strings because they contain control characters (\0, \1) ........ r53264 | andrew.kuchling | 2007-01-05 16:51:24 +0100 (Fri, 05 Jan 2007) | 1 line [Patch #1520904] Fix bsddb tests to write to the temp directory instead of the Lib/bsddb/test directory ........ r53279 | brett.cannon | 2007-01-05 22:45:09 +0100 (Fri, 05 Jan 2007) | 3 lines Silence a warning from gcc 4.0.1 by specifying a function's parameter list is 'void' instead of just a set of empty parentheses. ........ r53285 | raymond.hettinger | 2007-01-06 02:14:41 +0100 (Sat, 06 Jan 2007) | 2 lines SF# 1409443: Expand comment to cover the interaction between f->f_lasti and the PREDICT macros. ........ r53286 | anthony.baxter | 2007-01-06 05:45:54 +0100 (Sat, 06 Jan 2007) | 1 line update to (c) years to include 2007 ........ r53291 | neal.norwitz | 2007-01-06 22:24:35 +0100 (Sat, 06 Jan 2007) | 1 line Add Josiah to SF for maintaining asyncore/asynchat ........ r53293 | peter.astrand | 2007-01-07 09:53:46 +0100 (Sun, 07 Jan 2007) | 1 line Re-implemented fix for #1531862 once again, in a way that works with Python 2.2. Fixes bug #1603424. ........ r53295 | peter.astrand | 2007-01-07 15:34:16 +0100 (Sun, 07 Jan 2007) | 1 line Avoid O(N**2) bottleneck in _communicate_(). Fixes #1598181. ........ r53300 | raymond.hettinger | 2007-01-08 19:09:20 +0100 (Mon, 08 Jan 2007) | 1 line Fix zero-length corner case for iterating over a mutating deque. ........ r53301 | vinay.sajip | 2007-01-08 19:50:32 +0100 (Mon, 08 Jan 2007) | 4 lines Bare except clause removed from SMTPHandler.emit(). Now, only ImportError is trapped. Bare except clause removed from SocketHandler.createSocket(). Now, only socket.error is trapped. (SF #411881) ........ r53302 | vinay.sajip | 2007-01-08 19:51:46 +0100 (Mon, 08 Jan 2007) | 2 lines Bare except clause removed from LogRecord.__init__. Now, only ValueError, TypeError and AttributeError are trapped. (SF #411881) ........ r53303 | vinay.sajip | 2007-01-08 19:52:36 +0100 (Mon, 08 Jan 2007) | 1 line Added entries about removal of some bare except clauses from logging. ........ Modified: python/branches/p3yk/Doc/README ============================================================================== --- python/branches/p3yk/Doc/README (original) +++ python/branches/p3yk/Doc/README Wed Jan 10 00:18:33 2007 @@ -229,7 +229,7 @@ as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000-2006 Python Software Foundation. +Copyright (c) 2000-2007 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk/Doc/api/newtypes.tex ============================================================================== --- python/branches/p3yk/Doc/api/newtypes.tex (original) +++ python/branches/p3yk/Doc/api/newtypes.tex Wed Jan 10 00:18:33 2007 @@ -103,8 +103,6 @@ the value for the \var{methods} argument]{2.3} \end{cfuncdesc} -DL_IMPORT - \begin{cvardesc}{PyObject}{_Py_NoneStruct} Object which is visible in Python as \code{None}. This should only be accessed using the \code{Py_None} macro, which evaluates to a Modified: python/branches/p3yk/Doc/howto/functional.rst ============================================================================== --- python/branches/p3yk/Doc/howto/functional.rst (original) +++ python/branches/p3yk/Doc/howto/functional.rst Wed Jan 10 00:18:33 2007 @@ -1398,10 +1398,10 @@ ''''''''''''''''''''''''''' http://docs.python.org/lib/module-itertools.html: -Documentation ``for the itertools`` module. +Documentation for the ``itertools`` module. http://docs.python.org/lib/module-operator.html: -Documentation ``for the operator`` module. +Documentation for the ``operator`` module. http://www.python.org/dev/peps/pep-0289/: PEP 289: "Generator Expressions" Modified: python/branches/p3yk/Doc/lib/libbsddb.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libbsddb.tex (original) +++ python/branches/p3yk/Doc/lib/libbsddb.tex Wed Jan 10 00:18:33 2007 @@ -16,7 +16,7 @@ \function{pickle.dumps()}. The \module{bsddb} module requires a Berkeley DB library version from -3.3 thru 4.4. +3.3 thru 4.5. \begin{seealso} \seeurl{http://pybsddb.sourceforge.net/} Modified: python/branches/p3yk/Doc/lib/libbz2.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libbz2.tex (original) +++ python/branches/p3yk/Doc/lib/libbz2.tex Wed Jan 10 00:18:33 2007 @@ -81,10 +81,10 @@ \begin{methoddesc}[BZ2File]{seek}{offset\optional{, whence}} Move to new file position. Argument \var{offset} is a byte count. Optional -argument \var{whence} defaults to \code{0} (offset from start of file, -offset should be \code{>= 0}); other values are \code{1} (move relative to -current position, positive or negative), and \code{2} (move relative to end -of file, usually negative, although many platforms allow seeking beyond +argument \var{whence} defaults to \code{os.SEEK_SET} or \code{0} (offset from start of file; +offset should be \code{>= 0}); other values are \code{os.SEEK_CUR} or \code{1} (move relative to +current position; offset can be positive or negative), and \code{os.SEEK_END} or \code{2} (move relative to end +of file; offset is usually negative, although many platforms allow seeking beyond the end of a file). Note that seeking of bz2 files is emulated, and depending on the parameters Modified: python/branches/p3yk/Doc/lib/libctypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libctypes.tex (original) +++ python/branches/p3yk/Doc/lib/libctypes.tex Wed Jan 10 00:18:33 2007 @@ -2085,10 +2085,10 @@ the type. Some types accept other objects as well. \end{methoddesc} -\begin{methoddesc}{in_dll}{name, library} +\begin{methoddesc}{in_dll}{library, name} This method returns a ctypes type instance exported by a shared library. \var{name} is the name of the symbol that exports the data, -\code{library} is the loaded shared library. +\var{library} is the loaded shared library. \end{methoddesc} Common instance variables of ctypes data types: Modified: python/branches/p3yk/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfuncs.tex (original) +++ python/branches/p3yk/Doc/lib/libfuncs.tex Wed Jan 10 00:18:33 2007 @@ -237,11 +237,11 @@ \code{del \var{x}.\var{foobar}}. \end{funcdesc} -\begin{funcdesc}{dict}{\optional{mapping-or-sequence}} +\begin{funcdesc}{dict}{\optional{arg}} Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. - If the positional argument is a mapping object, return a dictionary + If the positional argument \var{arg} is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. Otherwise the positional argument must be a sequence, a container that supports iteration, or an iterator object. The elements of the argument @@ -448,18 +448,18 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{filter}{function, list} - Construct a list from those elements of \var{list} for which - \var{function} returns true. \var{list} may be either a sequence, a - container which supports iteration, or an iterator, If \var{list} +\begin{funcdesc}{filter}{function, iterable} + Construct a list from those elements of \var{iterable} for which + \var{function} returns true. \var{iterable} may be either a sequence, a + container which supports iteration, or an iterator, If \var{iterable} is a string or a tuple, the result also has that type; otherwise it is always a list. If \var{function} is \code{None}, the identity function is assumed, that is, all elements of - \var{list} that are false are removed. + \var{iterable} that are false are removed. - Note that \code{filter(function, \var{list})} is equivalent to - \code{[item for item in \var{list} if function(item)]} if function is - not \code{None} and \code{[item for item in \var{list} if item]} if + Note that \code{filter(function, \var{iterable})} is equivalent to + \code{[item for item in \var{iterable} if function(item)]} if function is + not \code{None} and \code{[item for item in \var{iterable} if item]} if function is \code{None}. \end{funcdesc} @@ -608,12 +608,12 @@ may be a sequence (string, tuple or list) or a mapping (dictionary). \end{funcdesc} -\begin{funcdesc}{list}{\optional{sequence}} +\begin{funcdesc}{list}{\optional{iterable}} Return a list whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be either a sequence, a + \var{iterable}'s items. \var{iterable} may be either a sequence, a container that supports iteration, or an iterator object. If - \var{sequence} is already a list, a copy is made and returned, - similar to \code{\var{sequence}[:]}. For instance, + \var{iterable} is already a list, a copy is made and returned, + similar to \code{\var{iterable}[:]}. For instance, \code{list('abc')} returns \code{['a', 'b', 'c']} and \code{list( (1, 2, 3) )} returns \code{[1, 2, 3]}. If no argument is given, returns a new empty list, \code{[]}. @@ -639,22 +639,22 @@ are given, returns \code{0L}. \end{funcdesc} -\begin{funcdesc}{map}{function, list, ...} - Apply \var{function} to every item of \var{list} and return a list - of the results. If additional \var{list} arguments are passed, +\begin{funcdesc}{map}{function, iterable, ...} + Apply \var{function} to every item of \var{iterable} and return a list + of the results. If additional \var{iterable} arguments are passed, \var{function} must take that many arguments and is applied to the - items of all lists in parallel; if a list is shorter than another it + items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with \code{None} items. If \var{function} is \code{None}, the identity function is assumed; if there are - multiple list arguments, \function{map()} returns a list consisting - of tuples containing the corresponding items from all lists (a kind - of transpose operation). The \var{list} arguments may be any kind - of sequence; the result is always a list. + multiple arguments, \function{map()} returns a list consisting + of tuples containing the corresponding items from all iterables (a kind + of transpose operation). The \var{iterable} arguments may be a sequence + or any iterable object; the result is always a list. \end{funcdesc} -\begin{funcdesc}{max}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the largest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{max}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the largest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments. The optional \var{key} argument specifies a one-argument ordering @@ -664,16 +664,16 @@ \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} -\begin{funcdesc}{min}{s\optional{, args...}\optional{key}} - With a single argument \var{s}, return the smallest item of a - non-empty sequence (such as a string, tuple or list). With more +\begin{funcdesc}{min}{iterable\optional{, args...}\optional{key}} + With a single argument \var{iterable}, return the smallest item of a + non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments. The optional \var{key} argument specifies a one-argument ordering function like that used for \method{list.sort()}. The \var{key} argument, if supplied, must be in keyword form (for example, \samp{min(a,b,c,key=func)}). - \versionchanged[Added support for the optional \var{key} argument]{2.5} + \versionchanged[Added support for the optional \var{key} argument]{2.5} \end{funcdesc} \begin{funcdesc}{object}{} @@ -1073,11 +1073,11 @@ string, \code{''}. \end{funcdesc} -\begin{funcdesc}{sum}{sequence\optional{, start}} - Sums \var{start} and the items of a \var{sequence}, from left to - right, and returns the total. \var{start} defaults to \code{0}. - The \var{sequence}'s items are normally numbers, and are not allowed - to be strings. The fast, correct way to concatenate sequence of +\begin{funcdesc}{sum}{iterable\optional{, start}} + Sums \var{start} and the items of an \var{iterable} from left to + right and returns the total. \var{start} defaults to \code{0}. + The \var{iterable}'s items are normally numbers, and are not allowed + to be strings. The fast, correct way to concatenate a sequence of strings is by calling \code{''.join(\var{sequence})}. \versionadded{2.3} \end{funcdesc} @@ -1105,11 +1105,11 @@ \versionadded{2.2} \end{funcdesc} -\begin{funcdesc}{tuple}{\optional{sequence}} +\begin{funcdesc}{tuple}{\optional{iterable}} Return a tuple whose items are the same and in the same order as - \var{sequence}'s items. \var{sequence} may be a sequence, a + \var{iterable}'s items. \var{iterable} may be a sequence, a container that supports iteration, or an iterator object. - If \var{sequence} is already a tuple, it + If \var{iterable} is already a tuple, it is returned unchanged. For instance, \code{tuple('abc')} returns \code{('a', 'b', 'c')} and \code{tuple([1, 2, 3])} returns \code{(1, 2, 3)}. If no argument is given, returns a new empty Modified: python/branches/p3yk/Doc/lib/liblogging.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liblogging.tex (original) +++ python/branches/p3yk/Doc/lib/liblogging.tex Wed Jan 10 00:18:33 2007 @@ -516,8 +516,10 @@ \end{methoddesc} \begin{methoddesc}{findCaller}{} -Finds the caller's source filename and line number. Returns the filename -and line number as a 2-element tuple. +Finds the caller's source filename and line number. Returns the filename, +line number and function name as a 3-element tuple. +\versionchanged[The function name was added. In earlier versions, the +filename and line number were returned as a 2-element tuple.]{2.5} \end{methoddesc} \begin{methoddesc}{handle}{record} Modified: python/branches/p3yk/Doc/lib/libmmap.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libmmap.tex (original) +++ python/branches/p3yk/Doc/lib/libmmap.tex Wed Jan 10 00:18:33 2007 @@ -140,8 +140,9 @@ \begin{methoddesc}{seek}{pos\optional{, whence}} Set the file's current position. \var{whence} argument is optional - and defaults to \code{0} (absolute file positioning); other values - are \code{1} (seek relative to the current position) and \code{2} + and defaults to \code{os.SEEK_SET} or \code{0} (absolute file + positioning); other values are \code{os.SEEK_CUR} or \code{1} (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} (seek relative to the file's end). \end{methoddesc} Modified: python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex (original) +++ python/branches/p3yk/Doc/lib/libsimplexmlrpc.tex Wed Jan 10 00:18:33 2007 @@ -15,7 +15,7 @@ \begin{classdesc}{SimpleXMLRPCServer}{addr\optional{, requestHandler\optional{, - logRequests\optional{allow_none\optional{, encoding}}}}} + logRequests\optional{, allow_none\optional{, encoding}}}}} Create a new server instance. This class provides methods for registration of functions that can be called by Modified: python/branches/p3yk/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk/Doc/lib/libsocket.tex Wed Jan 10 00:18:33 2007 @@ -569,11 +569,32 @@ Receive data from the socket. The return value is a pair \code{(\var{string}, \var{address})} where \var{string} is a string representing the data received and \var{address} is the address of the -socket sending the data. The optional \var{flags} argument has the -same meaning as for \method{recv()} above. +socket sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} depends on the address family --- see above.) \end{methoddesc} +\begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive data from the socket, writing it into \var{buffer} instead of +creating a new string. The return value is a pair +\code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number +of bytes received and \var{address} is the address of the socket +sending the data. See the \UNIX{} manual page +\manpage{recv}{2} for the meaning of the optional argument +\var{flags}; it defaults to zero. (The format of \var{address} +depends on the address family --- see above.) +\end{methoddesc} + +\begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}} +Receive up to \var{nbytes} bytes from the socket, +storing the data into a buffer rather than creating a new string. +If \var{nbytes} is not specified (or 0), +receive up to the size available in the given buffer. +See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the +optional argument \var{flags}; it defaults to zero. +\end{methoddesc} + \begin{methoddesc}[socket]{send}{string\optional{, flags}} Send data to the socket. The socket must be connected to a remote socket. The optional \var{flags} argument has the same meaning as for Modified: python/branches/p3yk/Doc/lib/libsqlite3.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsqlite3.tex (original) +++ python/branches/p3yk/Doc/lib/libsqlite3.tex Wed Jan 10 00:18:33 2007 @@ -187,12 +187,12 @@ \end{funcdesc} \begin{funcdesc}{complete_statement}{sql} -Returns \constant{True} if the string \var{sql} one or more complete SQL -statements terminated by semicolons. It does not verify if the SQL is -syntactically correct, only if there are no unclosed string literals and if the +Returns \constant{True} if the string \var{sql} contains one or more complete SQL +statements terminated by semicolons. It does not verify that the SQL is +syntactically correct, only that there are no unclosed string literals and the statement is terminated by a semicolon. -This can be used to build a shell for SQLite, like in the following example: +This can be used to build a shell for SQLite, as in the following example: \verbatiminput{sqlite3/complete_statement.py} \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Wed Jan 10 00:18:33 2007 @@ -1660,9 +1660,12 @@ \begin{methoddesc}[file]{seek}{offset\optional{, whence}} Set the file's current position, like \code{stdio}'s \cfunction{fseek()}. - The \var{whence} argument is optional and defaults to \code{0} - (absolute file positioning); other values are \code{1} (seek - relative to the current position) and \code{2} (seek relative to the + The \var{whence} argument is optional and defaults to + \code{os.SEEK_SET} or \code{0} + (absolute file positioning); other values are \code{os.SEEK_CUR} or \code{1} + (seek + relative to the current position) and \code{os.SEEK_END} or \code{2} + (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode \code{'a'} or \code{'a+'}), any \method{seek()} operations will be undone at the next write. If the Modified: python/branches/p3yk/Doc/lib/libtarfile.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtarfile.tex (original) +++ python/branches/p3yk/Doc/lib/libtarfile.tex Wed Jan 10 00:18:33 2007 @@ -124,6 +124,11 @@ only if \member{TarFile.errorlevel}\code{ == 2}. \end{excdesc} +\begin{excdesc}{HeaderError} + Is raised by \method{frombuf()} if the buffer it gets is invalid. + \versionadded{2.6} +\end{excdesc} + \begin{seealso} \seemodule{zipfile}{Documentation of the \refmodule{zipfile} standard module.} @@ -332,6 +337,8 @@ \begin{methoddesc}{frombuf}{} Create and return a \class{TarInfo} object from a string buffer. + \versionadded[Raises \exception{HeaderError} if the buffer is + invalid.]{2.6} \end{methoddesc} \begin{methoddesc}{tobuf}{posix} Modified: python/branches/p3yk/Doc/lib/libtest.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtest.tex (original) +++ python/branches/p3yk/Doc/lib/libtest.tex Wed Jan 10 00:18:33 2007 @@ -263,6 +263,12 @@ This does not equal a failure since it could be the path to the file. \end{funcdesc} +\begin{funcdesc}{guard_warnings_filter}{} +Returns a context manager that guards the \module{warnings} module's +filter settings. +\versionadded{2.6} +\end{funcdesc} + \begin{funcdesc}{run_unittest}{*classes} Execute \class{unittest.TestCase} subclasses passed to the function. The function scans the classes for methods starting with the prefix @@ -275,4 +281,22 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. + +The \module{test.test_support} module defines the following classes: + +\begin{classdesc}{EnvironmentVarGuard}{} +Class used to temporarily set or unset environment variables. Instances can be +used as a context manager. +\versionadded{2.6} +\end{classdesc} + +\begin{methoddesc}{set}{envvar, value} +Temporarily set the environment variable \code{envvar} to the value of +\code{value}. +\end{methoddesc} + +\begin{methoddesc}{unset}{envvar} +Temporarily unset the environment variable \code{envvar}. +\end{methoddesc} + \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/liburlparse.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liburlparse.tex (original) +++ python/branches/p3yk/Doc/lib/liburlparse.tex Wed Jan 10 00:18:33 2007 @@ -89,7 +89,7 @@ \begin{funcdesc}{urlunparse}{parts} Construct a URL from a tuple as returned by \code{urlparse()}. -The \var{parts} argument be any six-item iterable. +The \var{parts} argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). @@ -133,7 +133,7 @@ \begin{funcdesc}{urlunsplit}{parts} Combine the elements of a tuple as returned by \function{urlsplit()} into a complete URL as a string. -The \var{parts} argument be any five-item iterable. +The \var{parts} argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). Modified: python/branches/p3yk/Doc/mac/toolbox.tex ============================================================================== --- python/branches/p3yk/Doc/mac/toolbox.tex (original) +++ python/branches/p3yk/Doc/mac/toolbox.tex Wed Jan 10 00:18:33 2007 @@ -65,7 +65,7 @@ \modulesynopsis{Interface to the Component Manager.} \section{\module{Carbon.CarbonEvt} --- Carbon Event Manager} -\declaremodule{standard}{Carbon.CaronEvt} +\declaremodule{standard}{Carbon.CarbonEvt} \platform{Mac} \modulesynopsis{Interface to the Carbon Event Manager.} Modified: python/branches/p3yk/Doc/whatsnew/whatsnew25.tex ============================================================================== --- python/branches/p3yk/Doc/whatsnew/whatsnew25.tex (original) +++ python/branches/p3yk/Doc/whatsnew/whatsnew25.tex Wed Jan 10 00:18:33 2007 @@ -5,7 +5,7 @@ % Fix XXX comments \title{What's New in Python 2.5} -\release{1.0} +\release{1.01} \author{A.M. Kuchling} \authoraddress{\email{amk at amk.ca}} @@ -556,13 +556,14 @@ where the generator's execution is paused. \item \method{close()} raises a new \exception{GeneratorExit} - exception inside the generator to terminate the iteration. - On receiving this - exception, the generator's code must either raise - \exception{GeneratorExit} or \exception{StopIteration}; catching the - exception and doing anything else is illegal and will trigger - a \exception{RuntimeError}. \method{close()} will also be called by - Python's garbage collector when the generator is garbage-collected. + exception inside the generator to terminate the iteration. On + receiving this exception, the generator's code must either raise + \exception{GeneratorExit} or \exception{StopIteration}. Catching + the \exception{GeneratorExit} exception and returning a value is + illegal and will trigger a \exception{RuntimeError}; if the function + raises some other exception, that exception is propagated to the + caller. \method{close()} will also be called by Python's garbage + collector when the generator is garbage-collected. If you need to run cleanup code when a \exception{GeneratorExit} occurs, I suggest using a \code{try: ... finally:} suite instead of @@ -1663,6 +1664,13 @@ \item The \module{pyexpat} module now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.) +\item The \class{Queue} class provided by the \module{Queue} module +gained two new methods. \method{join()} blocks until all items in +the queue have been retrieved and all processing work on the items +have been completed. Worker threads call the other new method, +\method{task_done()}, to signal that processing for an item has been +completed. (Contributed by Raymond Hettinger.) + \item The old \module{regex} and \module{regsub} modules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules: \module{statcache}, \module{tzparse}, Modified: python/branches/p3yk/LICENSE ============================================================================== --- python/branches/p3yk/LICENSE (original) +++ python/branches/p3yk/LICENSE Wed Jan 10 00:18:33 2007 @@ -88,9 +88,9 @@ prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version -prepared by Licensee. +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make Modified: python/branches/p3yk/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk/Lib/CGIHTTPServer.py Wed Jan 10 00:18:33 2007 @@ -105,17 +105,36 @@ def run_cgi(self): """Execute a CGI script.""" + path = self.path dir, rest = self.cgi_info + + i = path.find('/', len(dir) + 1) + while i >= 0: + nextdir = path[:i] + nextrest = path[i+1:] + + scriptdir = self.translate_path(nextdir) + if os.path.isdir(scriptdir): + dir, rest = nextdir, nextrest + i = path.find('/', len(dir) + 1) + else: + break + + # find an explicit query string, if present. i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' + + # dissect the part after the directory name into a script name & + # a possible additional path, to be stored in PATH_INFO. i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' + scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): Modified: python/branches/p3yk/Lib/SimpleHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/SimpleHTTPServer.py (original) +++ python/branches/p3yk/Lib/SimpleHTTPServer.py Wed Jan 10 00:18:33 2007 @@ -66,6 +66,12 @@ path = self.translate_path(self.path) f = None if os.path.isdir(path): + if not self.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(301) + self.send_header("Location", self.path + "/") + self.end_headers() + return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): Modified: python/branches/p3yk/Lib/StringIO.py ============================================================================== --- python/branches/p3yk/Lib/StringIO.py (original) +++ python/branches/p3yk/Lib/StringIO.py Wed Jan 10 00:18:33 2007 @@ -139,7 +139,7 @@ return r def readline(self, length=None): - """Read one entire line from the file. + r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is Modified: python/branches/p3yk/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/dbobj.py Wed Jan 10 00:18:33 2007 @@ -55,8 +55,9 @@ return self._cobj.set_lg_max(*args, **kwargs) def set_lk_detect(self, *args, **kwargs): return self._cobj.set_lk_detect(*args, **kwargs) - def set_lk_max(self, *args, **kwargs): - return self._cobj.set_lk_max(*args, **kwargs) + if db.version() < (4,5): + def set_lk_max(self, *args, **kwargs): + return self._cobj.set_lk_max(*args, **kwargs) def set_lk_max_locks(self, *args, **kwargs): return self._cobj.set_lk_max_locks(*args, **kwargs) def set_lk_max_lockers(self, *args, **kwargs): Modified: python/branches/p3yk/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_1413192.py Wed Jan 10 00:18:33 2007 @@ -14,7 +14,7 @@ env_name = '.' env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN) +env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) the_txn = env.txn_begin() map = db.DB(env) Modified: python/branches/p3yk/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_associate.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_associate.py Wed Jan 10 00:18:33 2007 @@ -91,7 +91,7 @@ class AssociateErrorTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Wed Jan 10 00:18:33 2007 @@ -54,7 +54,7 @@ def setUp(self): if self.useEnv: - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: shutil.rmtree(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbobj.py Wed Jan 10 00:18:33 2007 @@ -2,6 +2,7 @@ import sys, os, string import unittest import glob +import tempfile try: # For Pythons w/distutils pybsddb @@ -19,7 +20,7 @@ db_name = 'test-dbobj.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Wed Jan 10 00:18:33 2007 @@ -242,7 +242,7 @@ class BasicEnvShelveTestCase(DBShelveTestCase): def do_open(self): self.homeDir = homeDir = os.path.join( - os.path.dirname(sys.argv[0]), 'db_home') + tempfile.gettempdir(), 'db_home') try: os.mkdir(homeDir) except os.error: pass self.env = db.DBEnv() Modified: python/branches/p3yk/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbtables.py Wed Jan 10 00:18:33 2007 @@ -26,6 +26,7 @@ pickle = cPickle except ImportError: import pickle +import tempfile import unittest from .test_all import verbose @@ -46,7 +47,7 @@ db_name = 'test-table.db' def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_env_close.py Wed Jan 10 00:18:33 2007 @@ -33,7 +33,7 @@ class DBEnvClosedEarlyCrash(unittest.TestCase): def setUp(self): - self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + self.homeDir = os.path.join(tempfile.gettempdir(), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass tempfile.tempdir = self.homeDir Modified: python/branches/p3yk/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_join.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_join.py Wed Jan 10 00:18:33 2007 @@ -49,7 +49,7 @@ def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_lock.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_lock.py Wed Jan 10 00:18:33 2007 @@ -30,7 +30,7 @@ class LockingTestCase(unittest.TestCase): def setUp(self): - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except os.error: pass Modified: python/branches/p3yk/Lib/bsddb/test/test_misc.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_misc.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_misc.py Wed Jan 10 00:18:33 2007 @@ -4,6 +4,7 @@ import os import sys import unittest +import tempfile try: # For Pythons w/distutils pybsddb @@ -17,7 +18,7 @@ class MiscTestCase(unittest.TestCase): def setUp(self): self.filename = self.__class__.__name__ + '.db' - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_recno.py Wed Jan 10 00:18:33 2007 @@ -203,10 +203,10 @@ just a line in the file, but you can set a different record delimiter if needed. """ - source = os.path.join(os.path.dirname(sys.argv[0]), - 'db_home/test_recno.txt') - if not os.path.isdir('db_home'): - os.mkdir('db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') + source = os.path.join(homeDir, 'test_recno.txt') + if not os.path.isdir(homeDir): + os.mkdir(homeDir) f = open(source, 'w') # create the file f.close() Modified: python/branches/p3yk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_thread.py Wed Jan 10 00:18:33 2007 @@ -53,7 +53,7 @@ if verbose: dbutils._deadlock_VerboseFile = sys.stdout - homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') + homeDir = os.path.join(tempfile.gettempdir(), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) Modified: python/branches/p3yk/Lib/cookielib.py ============================================================================== --- python/branches/p3yk/Lib/cookielib.py (original) +++ python/branches/p3yk/Lib/cookielib.py Wed Jan 10 00:18:33 2007 @@ -1316,26 +1316,28 @@ """ _debug("add_cookie_header") self._cookies_lock.acquire() + try: - self._policy._now = self._now = int(time.time()) - - cookies = self._cookies_for_request(request) + self._policy._now = self._now = int(time.time()) - attrs = self._cookie_attrs(cookies) - if attrs: - if not request.has_header("Cookie"): - request.add_unredirected_header( - "Cookie", "; ".join(attrs)) - - # if necessary, advertise that we know RFC 2965 - if (self._policy.rfc2965 and not self._policy.hide_cookie2 and - not request.has_header("Cookie2")): - for cookie in cookies: - if cookie.version != 1: - request.add_unredirected_header("Cookie2", '$Version="1"') - break + cookies = self._cookies_for_request(request) - self._cookies_lock.release() + attrs = self._cookie_attrs(cookies) + if attrs: + if not request.has_header("Cookie"): + request.add_unredirected_header( + "Cookie", "; ".join(attrs)) + + # if necessary, advertise that we know RFC 2965 + if (self._policy.rfc2965 and not self._policy.hide_cookie2 and + not request.has_header("Cookie2")): + for cookie in cookies: + if cookie.version != 1: + request.add_unredirected_header("Cookie2", '$Version="1"') + break + + finally: + self._cookies_lock.release() self.clear_expired_cookies() @@ -1602,12 +1604,15 @@ def set_cookie_if_ok(self, cookie, request): """Set a cookie if policy says it's OK to do so.""" self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - if self._policy.set_ok(cookie, request): - self.set_cookie(cookie) + if self._policy.set_ok(cookie, request): + self.set_cookie(cookie) + - self._cookies_lock.release() + finally: + self._cookies_lock.release() def set_cookie(self, cookie): """Set a cookie, without checking whether or not it should be set.""" @@ -1626,13 +1631,15 @@ """Extract cookies from response, where allowable given the request.""" _debug("extract_cookies: %s", response.info()) self._cookies_lock.acquire() - self._policy._now = self._now = int(time.time()) + try: + self._policy._now = self._now = int(time.time()) - for cookie in self.make_cookies(response, request): - if self._policy.set_ok(cookie, request): - _debug(" setting cookie: %s", cookie) - self.set_cookie(cookie) - self._cookies_lock.release() + for cookie in self.make_cookies(response, request): + if self._policy.set_ok(cookie, request): + _debug(" setting cookie: %s", cookie) + self.set_cookie(cookie) + finally: + self._cookies_lock.release() def clear(self, domain=None, path=None, name=None): """Clear some cookies. @@ -1669,10 +1676,12 @@ """ self._cookies_lock.acquire() - for cookie in self: - if cookie.discard: - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + for cookie in self: + if cookie.discard: + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def clear_expired_cookies(self): """Discard all expired cookies. @@ -1685,11 +1694,13 @@ """ self._cookies_lock.acquire() - now = time.time() - for cookie in self: - if cookie.is_expired(now): - self.clear(cookie.domain, cookie.path, cookie.name) - self._cookies_lock.release() + try: + now = time.time() + for cookie in self: + if cookie.is_expired(now): + self.clear(cookie.domain, cookie.path, cookie.name) + finally: + self._cookies_lock.release() def __iter__(self): return deepvalues(self._cookies) @@ -1761,16 +1772,18 @@ else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() - - old_state = copy.deepcopy(self._cookies) - self._cookies = {} try: - self.load(filename, ignore_discard, ignore_expires) - except (LoadError, IOError): - self._cookies = old_state - raise - self._cookies_lock.release() + old_state = copy.deepcopy(self._cookies) + self._cookies = {} + try: + self.load(filename, ignore_discard, ignore_expires) + except (LoadError, IOError): + self._cookies = old_state + raise + + finally: + self._cookies_lock.release() from _LWPCookieJar import LWPCookieJar, lwp_cookie_str from _MozillaCookieJar import MozillaCookieJar Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Wed Jan 10 00:18:33 2007 @@ -1310,7 +1310,7 @@ def _mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=IS_CHARACTER_JUNK): - """Returns generator yielding marked up from/to side by side differences. + r"""Returns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Wed Jan 10 00:18:33 2007 @@ -68,7 +68,8 @@ try: f = _open(self._datfile, 'r') except IOError: - f = _open(self._datfile, 'w', self._mode) + f = _open(self._datfile, 'w') + self._chmod(self._datfile) f.close() self._update() @@ -106,7 +107,8 @@ except self._os.error: pass - f = self._open(self._dirfile, 'w', self._mode) + f = self._open(self._dirfile, 'w') + self._chmod(self._dirfile) for key, pos_and_siz_pair in self._index.iteritems(): f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -152,7 +154,8 @@ # the in-memory index dict, and append one to the directory file. def _addkey(self, key, pos_and_siz_pair): self._index[key] = pos_and_siz_pair - f = _open(self._dirfile, 'a', self._mode) + f = _open(self._dirfile, 'a') + self._chmod(self._dirfile) f.write("%r, %r\n" % (key, pos_and_siz_pair)) f.close() @@ -211,6 +214,9 @@ __del__ = close + def _chmod (self, file): + if hasattr(self._os, 'chmod'): + self._os.chmod(file, self._mode) def open(file, flag=None, mode=0666): @@ -227,4 +233,15 @@ """ # flag argument is currently ignored + + # Modify mode depending on the umask + try: + um = _os.umask(0) + _os.umask(um) + except AttributeError: + pass + else: + # Turn off any bits that are set in the umask + mode = mode & (~um) + return _Database(file, mode) Modified: python/branches/p3yk/Lib/heapq.py ============================================================================== --- python/branches/p3yk/Lib/heapq.py (original) +++ python/branches/p3yk/Lib/heapq.py Wed Jan 10 00:18:33 2007 @@ -130,7 +130,7 @@ 'nsmallest'] from itertools import islice, repeat, count, imap, izip, tee -from operator import itemgetter +from operator import itemgetter, neg import bisect def heappush(heap, item): @@ -315,8 +315,6 @@ Equivalent to: sorted(iterable, key=key)[:n] """ - if key is None: - return _nsmallest(n, iterable) in1, in2 = tee(iterable) it = izip(imap(key, in1), count(), in2) # decorate result = _nsmallest(n, it) @@ -328,10 +326,8 @@ Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ - if key is None: - return _nlargest(n, iterable) in1, in2 = tee(iterable) - it = izip(imap(key, in1), count(), in2) # decorate + it = izip(imap(key, in1), imap(neg, count()), in2) # decorate result = _nlargest(n, it) return map(itemgetter(2), result) # undecorate Modified: python/branches/p3yk/Lib/hmac.py ============================================================================== --- python/branches/p3yk/Lib/hmac.py (original) +++ python/branches/p3yk/Lib/hmac.py Wed Jan 10 00:18:33 2007 @@ -3,13 +3,11 @@ Implements the HMAC algorithm as described by RFC 2104. """ -def _strxor(s1, s2): - """Utility method. XOR the two strings s1 and s2 (must have same length). - """ - return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) +trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) +trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)]) # The size of the digests returned by HMAC depends on the underlying -# hashing module used. +# hashing module used. Use digest_size from the instance of HMAC instead. digest_size = None # A unique object passed by HMAC.copy() to the HMAC constructor, in order @@ -22,6 +20,7 @@ This supports the API for Cryptographic Hash Functions (PEP 247). """ + blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. @@ -49,16 +48,13 @@ self.inner = self.digest_cons() self.digest_size = self.inner.digest_size - blocksize = 64 - ipad = "\x36" * blocksize - opad = "\x5C" * blocksize - + blocksize = self.blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + chr(0) * (blocksize - len(key)) - self.outer.update(_strxor(key, opad)) - self.inner.update(_strxor(key, ipad)) + self.outer.update(key.translate(trans_5C)) + self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg) @@ -75,13 +71,22 @@ An update to this copy won't affect the original object. """ - other = HMAC(_secret_backdoor_key) + other = self.__class__(_secret_backdoor_key) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other + def _current(self): + """Return a hash object for the current state. + + To be used only internally with digest() and hexdigest(). + """ + h = self.outer.copy() + h.update(self.inner.digest()) + return h + def digest(self): """Return the hash value of this hashing object. @@ -89,15 +94,14 @@ not altered in any way by this function; you can continue updating the object after calling this function. """ - h = self.outer.copy() - h.update(self.inner.digest()) + h = self._current() return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ - return "".join([hex(ord(x))[2:].zfill(2) - for x in tuple(self.digest())]) + h = self._current() + return h.hexdigest() def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. Modified: python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py Wed Jan 10 00:18:33 2007 @@ -118,8 +118,11 @@ i = 0 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]: i += 1 - while cursel > 0 and selstart[:i] <= self.completions[cursel-1]: + previous_completion = self.completions[cursel - 1] + while cursel > 0 and selstart[:i] <= previous_completion: i += 1 + if selstart == previous_completion: + break # maybe we have a duplicate? newstart = selstart[:i] self._change_start(newstart) Modified: python/branches/p3yk/Lib/idlelib/NEWS.txt ============================================================================== --- python/branches/p3yk/Lib/idlelib/NEWS.txt (original) +++ python/branches/p3yk/Lib/idlelib/NEWS.txt Wed Jan 10 00:18:33 2007 @@ -3,9 +3,14 @@ *Release date: XX-XXX-200X* +- Avoid hang when encountering a duplicate in a completion list. Bug 1571112. + - Patch #1362975: Rework CodeContext indentation algorithm to avoid hard-coding pixel widths. +- Bug #813342: Start the IDLE subprocess with -Qnew if the parent + is started with that option. + - Some syntax errors were being caught by tokenize during the tabnanny check, resulting in obscure error messages. Do the syntax check first. Bug 1562716, 1562719 @@ -14,6 +19,12 @@ the Python release of which it's a part. +What's New in IDLE 1.2? +======================= + +*Release date: 19-SEP-2006* + + What's New in IDLE 1.2c1? ========================= @@ -44,6 +55,13 @@ *Release date: 03-AUG-2006* +- Bug #1525817: Don't truncate short lines in IDLE's tool tips. + +- Bug #1517990: IDLE keybindings on MacOS X now work correctly + +- Bug #1517996: IDLE now longer shows the default Tk menu when a + path browser, class browser or debugger is the frontmost window on MacOS X + - EditorWindow.test() was failing. Bug 1417598 - EditorWindow failed when used stand-alone if sys.ps1 not set. @@ -80,6 +98,8 @@ *Release date: 05-APR-2006* +- Patch #1162825: Support non-ASCII characters in IDLE window titles. + - Source file f.flush() after writing; trying to avoid lossage if user kills GUI. Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Wed Jan 10 00:18:33 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.4.9.9" -__date__ = "06 February 2006" +__version__ = "0.5.0.0" +__date__ = "08 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -243,7 +243,7 @@ try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] - except: + except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Wed Jan 10 00:18:33 2007 @@ -347,7 +347,7 @@ try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying - except: + except socket.error: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart @@ -738,7 +738,7 @@ import smtplib try: from email.Utils import formatdate - except: + except ImportError: formatdate = self.date_time port = self.mailport if not port: Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Wed Jan 10 00:18:33 2007 @@ -510,6 +510,7 @@ self._next_key = 0 self._pending = False # No changes require rewriting the file. self._locked = False + self._file_length = None # Used to record mailbox size def add(self, message): """Add message and return assigned key.""" @@ -563,7 +564,21 @@ """Write any pending changes to disk.""" if not self._pending: return - self._lookup() + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + new_file = _create_temporary(self._path) try: new_toc = {} @@ -639,6 +654,7 @@ offsets = self._install_message(message) self._post_message_hook(self._file) self._file.flush() + self._file_length = self._file.tell() # Record current length of mailbox return offsets @@ -730,6 +746,7 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file_length = self._file.tell() class MMDF(_mboxMMDF): @@ -773,6 +790,8 @@ break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) + self._file.seek(0, 2) + self._file_length = self._file.tell() class MH(Mailbox): @@ -1198,7 +1217,9 @@ self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) - + self._file.seek(0, 2) + self._file_length = self._file.tell() + def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % @@ -1884,7 +1905,8 @@ def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() - os.fsync(f.fileno()) + if hasattr(os, 'fsync'): + os.fsync(f.fileno()) def _sync_close(f): """Close file f, ensuring all changes are physically on disk.""" Modified: python/branches/p3yk/Lib/pty.py ============================================================================== --- python/branches/p3yk/Lib/pty.py (original) +++ python/branches/p3yk/Lib/pty.py Wed Jan 10 00:18:33 2007 @@ -121,7 +121,9 @@ # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) os.close(tmp_fd) - + else: + os.close(slave_fd) + # Parent and child process. return pid, master_fd Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Wed Jan 10 00:18:33 2007 @@ -1741,6 +1741,9 @@ Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. + +On the Microsoft Windows operating system, the files can be built by +running "hh -decompile . PythonNN.chm" in the C:\PythonNN\Doc> directory. ''') return target = self.topics.get(topic, self.keywords.get(topic)) Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Wed Jan 10 00:18:33 2007 @@ -205,7 +205,7 @@ raise ValueError, "empty range for randrange()" if n >= maxwidth: - return istart + self._randbelow(n) + return istart + istep*self._randbelow(n) return istart + istep*int(self.random() * n) def randint(self, a, b): Modified: python/branches/p3yk/Lib/sre_parse.py ============================================================================== --- python/branches/p3yk/Lib/sre_parse.py (original) +++ python/branches/p3yk/Lib/sre_parse.py Wed Jan 10 00:18:33 2007 @@ -134,6 +134,8 @@ def __delitem__(self, index): del self.data[index] def __getitem__(self, index): + if isinstance(index, slice): + return SubPattern(self.pattern, self.data[index]) return self.data[index] def __setitem__(self, index, code): self.data[index] = code Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Wed Jan 10 00:18:33 2007 @@ -166,7 +166,7 @@ communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to - terminate. The optional stdin argument should be a string to be + terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. @@ -1005,8 +1005,12 @@ # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. - for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)): - if fd: os.close(fd) + if p2cread and p2cread not in (0,): + os.close(p2cread) + if c2pwrite and c2pwrite not in (p2cread, 1): + os.close(c2pwrite) + if errwrite and errwrite not in (p2cread, c2pwrite, 2): + os.close(errwrite) # Close all other fds, if asked for if close_fds: @@ -1108,6 +1112,7 @@ read_set.append(self.stderr) stderr = [] + input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) @@ -1115,9 +1120,9 @@ # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 - bytes_written = os.write(self.stdin.fileno(), input[:512]) - input = input[bytes_written:] - if not input: + bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) + input_offset += bytes_written + if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Wed Jan 10 00:18:33 2007 @@ -147,7 +147,10 @@ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): - n = int(s.rstrip(NUL + " ") or "0", 8) + try: + n = int(s.rstrip(NUL + " ") or "0", 8) + except ValueError: + raise HeaderError("invalid header") else: n = 0L for i in xrange(len(s) - 1): @@ -282,6 +285,9 @@ class StreamError(TarError): """Exception for unsupported operations on stream-like TarFiles.""" pass +class HeaderError(TarError): + """Exception for invalid headers.""" + pass #--------------------------- # internal stream interface @@ -624,140 +630,194 @@ #------------------------ # Extraction file object #------------------------ -class ExFileObject(object): - """File-like object for reading an archive member. - Is returned by TarFile.extractfile(). Support for - sparse files included. +class _FileInFile(object): + """A thin wrapper around an existing file object that + provides a part of its data as an individual file + object. """ - def __init__(self, tarfile, tarinfo): - self.fileobj = tarfile.fileobj - self.name = tarinfo.name - self.mode = "r" - self.closed = False - self.offset = tarinfo.offset_data - self.size = tarinfo.size - self.pos = 0L - self.linebuffer = "" - if tarinfo.issparse(): - self.sparse = tarinfo.sparse - self.read = self._readsparse - else: - self.read = self._readnormal + def __init__(self, fileobj, offset, size, sparse=None): + self.fileobj = fileobj + self.offset = offset + self.size = size + self.sparse = sparse + self.position = 0 - def __read(self, size): - """Overloadable read method. + def tell(self): + """Return the current file position. """ - return self.fileobj.read(size) + return self.position - def readline(self, size=-1): - """Read a line with approx. size. If size is negative, - read a whole line. readline() and read() must not - be mixed up (!). - """ - if size < 0: - size = sys.maxint - - nl = self.linebuffer.find("\n") - if nl >= 0: - nl = min(nl, size) - else: - size -= len(self.linebuffer) - while (nl < 0 and size > 0): - buf = self.read(min(size, 100)) - if not buf: - break - self.linebuffer += buf - size -= len(buf) - nl = self.linebuffer.find("\n") - if nl == -1: - s = self.linebuffer - self.linebuffer = "" - return s - buf = self.linebuffer[:nl] - self.linebuffer = self.linebuffer[nl + 1:] - while buf[-1:] == "\r": - buf = buf[:-1] - return buf + "\n" - - def readlines(self): - """Return a list with all (following) lines. + def seek(self, position): + """Seek to a position in the file. """ - result = [] - while True: - line = self.readline() - if not line: break - result.append(line) - return result + self.position = position - def _readnormal(self, size=None): - """Read operation for regular files. + def read(self, size=None): + """Read data from the file. """ - if self.closed: - raise ValueError("file is closed") - self.fileobj.seek(self.offset + self.pos) - bytesleft = self.size - self.pos if size is None: - bytestoread = bytesleft + size = self.size - self.position else: - bytestoread = min(size, bytesleft) - self.pos += bytestoread - return self.__read(bytestoread) + size = min(size, self.size - self.position) - def _readsparse(self, size=None): - """Read operation for sparse files. - """ - if self.closed: - raise ValueError("file is closed") + if self.sparse is None: + return self.readnormal(size) + else: + return self.readsparse(size) - if size is None: - size = self.size - self.pos + def readnormal(self, size): + """Read operation for regular files. + """ + self.fileobj.seek(self.offset + self.position) + self.position += size + return self.fileobj.read(size) + def readsparse(self, size): + """Read operation for sparse files. + """ data = [] while size > 0: - buf = self._readsparsesection(size) + buf = self.readsparsesection(size) if not buf: break size -= len(buf) data.append(buf) return "".join(data) - def _readsparsesection(self, size): + def readsparsesection(self, size): """Read a single section of a sparse file. """ - section = self.sparse.find(self.pos) + section = self.sparse.find(self.position) if section is None: return "" - toread = min(size, section.offset + section.size - self.pos) + size = min(size, section.offset + section.size - self.position) + if isinstance(section, _data): - realpos = section.realpos + self.pos - section.offset - self.pos += toread + realpos = section.realpos + self.position - section.offset self.fileobj.seek(self.offset + realpos) - return self.__read(toread) + self.position += size + return self.fileobj.read(size) + else: + self.position += size + return NUL * size +#class _FileInFile + + +class ExFileObject(object): + """File-like object for reading an archive member. + Is returned by TarFile.extractfile(). + """ + blocksize = 1024 + + def __init__(self, tarfile, tarinfo): + self.fileobj = _FileInFile(tarfile.fileobj, + tarinfo.offset_data, + tarinfo.size, + getattr(tarinfo, "sparse", None)) + self.name = tarinfo.name + self.mode = "r" + self.closed = False + self.size = tarinfo.size + + self.position = 0 + self.buffer = "" + + def read(self, size=None): + """Read at most size bytes from the file. If size is not + present or None, read all data until EOF is reached. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + buf = "" + if self.buffer: + if size is None: + buf = self.buffer + self.buffer = "" + else: + buf = self.buffer[:size] + self.buffer = self.buffer[size:] + + if size is None: + buf += self.fileobj.read() else: - self.pos += toread - return NUL * toread + buf += self.fileobj.read(size - len(buf)) + + self.position += len(buf) + return buf + + def readline(self, size=-1): + """Read one entire line from the file. If size is present + and non-negative, return a string with at most that + size, which may be an incomplete line. + """ + if self.closed: + raise ValueError("I/O operation on closed file") + + if "\n" in self.buffer: + pos = self.buffer.find("\n") + 1 + else: + buffers = [self.buffer] + while True: + buf = self.fileobj.read(self.blocksize) + buffers.append(buf) + if not buf or "\n" in buf: + self.buffer = "".join(buffers) + pos = self.buffer.find("\n") + 1 + if pos == 0: + # no newline found. + pos = len(self.buffer) + break + + if size != -1: + pos = min(size, pos) + + buf = self.buffer[:pos] + self.buffer = self.buffer[pos:] + self.position += len(buf) + return buf + + def readlines(self): + """Return a list with all remaining lines. + """ + result = [] + while True: + line = self.readline() + if not line: break + result.append(line) + return result def tell(self): """Return the current file position. """ - return self.pos + if self.closed: + raise ValueError("I/O operation on closed file") + + return self.position - def seek(self, pos, whence=0): + def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ - self.linebuffer = "" - if whence == 0: - self.pos = min(max(pos, 0), self.size) - if whence == 1: + if self.closed: + raise ValueError("I/O operation on closed file") + + if whence == os.SEEK_SET: + self.position = min(max(pos, 0), self.size) + elif whence == os.SEEK_CUR: if pos < 0: - self.pos = max(self.pos + pos, 0) + self.position = max(self.position + pos, 0) else: - self.pos = min(self.pos + pos, self.size) - if whence == 2: - self.pos = max(min(self.size + pos, self.size), 0) + self.position = min(self.position + pos, self.size) + elif whence == os.SEEK_END: + self.position = max(min(self.size + pos, self.size), 0) + else: + raise ValueError("Invalid argument") + + self.buffer = "" + self.fileobj.seek(self.position) def close(self): """Close the file object. @@ -765,20 +825,13 @@ self.closed = True def __iter__(self): - """Get an iterator over the file object. - """ - if self.closed: - raise ValueError("I/O operation on closed file") - return self - - def next(self): - """Get the next item from the file iterator. + """Get an iterator over the file's lines. """ - result = self.readline() - if not result: - raise StopIteration - return result - + while True: + line = self.readline() + if not line: + break + yield line #class ExFileObject #------------------ @@ -821,9 +874,13 @@ """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) != BLOCKSIZE: - raise ValueError("truncated header") + raise HeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: - raise ValueError("empty header") + raise HeaderError("empty header") + + chksum = nti(buf[148:156]) + if chksum not in calc_chksums(buf): + raise HeaderError("bad checksum") tarinfo = cls() tarinfo.buf = buf @@ -833,7 +890,7 @@ tarinfo.gid = nti(buf[116:124]) tarinfo.size = nti(buf[124:136]) tarinfo.mtime = nti(buf[136:148]) - tarinfo.chksum = nti(buf[148:156]) + tarinfo.chksum = chksum tarinfo.type = buf[156:157] tarinfo.linkname = buf[157:257].rstrip(NUL) tarinfo.uname = buf[265:297].rstrip(NUL) @@ -845,8 +902,6 @@ if prefix and not tarinfo.issparse(): tarinfo.name = prefix + "/" + tarinfo.name - if tarinfo.chksum not in calc_chksums(buf): - raise ValueError("invalid header") return tarinfo def tobuf(self, posix=False): @@ -999,7 +1054,7 @@ can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ - self.name = name + self.name = os.path.abspath(name) if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") @@ -1011,7 +1066,7 @@ self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): - self.name = fileobj.name + self.name = os.path.abspath(fileobj.name) if hasattr(fileobj, "mode"): self.mode = fileobj.mode self._extfileobj = True @@ -1088,9 +1143,13 @@ # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) + if fileobj is not None: + saved_pos = fileobj.tell() try: return func(name, "r", fileobj) except (ReadError, CompressionError): + if fileobj is not None: + fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") @@ -1147,24 +1206,12 @@ except (ImportError, AttributeError): raise CompressionError("gzip module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tgz": - ext = ".tar" - if ext == ".gz": - ext = "" - tarname = pre + ext - if fileobj is None: fileobj = _open(name, mode + "b") - if mode != "r": - name = tarname - try: - t = cls.taropen(tarname, mode, - gzip.GzipFile(name, mode, compresslevel, fileobj) - ) + t = cls.taropen(name, mode, + gzip.GzipFile(name, mode, compresslevel, fileobj)) except IOError: raise ReadError("not a gzip file") t._extfileobj = False @@ -1183,21 +1230,13 @@ except ImportError: raise CompressionError("bz2 module is not available") - pre, ext = os.path.splitext(name) - pre = os.path.basename(pre) - if ext == ".tbz2": - ext = ".tar" - if ext == ".bz2": - ext = "" - tarname = pre + ext - if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: - t = cls.taropen(tarname, mode, fileobj) + t = cls.taropen(name, mode, fileobj) except IOError: raise ReadError("not a bzip2 file") t._extfileobj = False @@ -1402,8 +1441,7 @@ arcname = name # Skip if somebody tries to archive the archive... - if self.name is not None \ - and os.path.abspath(name) == os.path.abspath(self.name): + if self.name is not None and os.path.abspath(name) == self.name: self._dbg(2, "tarfile: Skipped %r" % name) return @@ -1795,16 +1833,14 @@ tarinfo = self.proc_member(tarinfo) - except ValueError, e: + except HeaderError, e: if self.ignore_zeros: - self._dbg(2, "0x%X: empty or invalid block: %s" % - (self.offset, e)) + self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE continue else: if self.offset == 0: - raise ReadError("empty, unreadable or compressed " - "file: %s" % e) + raise ReadError(str(e)) return None break Modified: python/branches/p3yk/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compile.py (original) +++ python/branches/p3yk/Lib/test/test_compile.py Wed Jan 10 00:18:33 2007 @@ -1,5 +1,4 @@ import unittest -import warnings import sys from test import test_support Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Wed Jan 10 00:18:33 2007 @@ -396,6 +396,12 @@ d.pop() self.assertRaises(RuntimeError, it.next) + def test_runtime_error_on_empty_deque(self): + d = deque() + it = iter(d) + d.append(10) + self.assertRaises(RuntimeError, it.next) + class Deque(deque): pass Modified: python/branches/p3yk/Lib/test/test_dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dumbdbm.py (original) +++ python/branches/p3yk/Lib/test/test_dumbdbm.py Wed Jan 10 00:18:33 2007 @@ -38,6 +38,24 @@ self.read_helper(f) f.close() + def test_dumbdbm_creation_mode(self): + # On platforms without chmod, don't do anything. + if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): + return + + try: + old_umask = os.umask(0002) + f = dumbdbm.open(_fname, 'c', 0637) + f.close() + finally: + os.umask(old_umask) + + import stat + st = os.stat(_fname + '.dat') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + st = os.stat(_fname + '.dir') + self.assertEqual(stat.S_IMODE(st.st_mode), 0635) + def test_close_twice(self): f = dumbdbm.open(_fname) f['a'] = 'b' Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Wed Jan 10 00:18:33 2007 @@ -3,7 +3,6 @@ import os import sys import unittest -import warnings import pickle try: import cPickle Modified: python/branches/p3yk/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk/Lib/test/test_heapq.py (original) +++ python/branches/p3yk/Lib/test/test_heapq.py Wed Jan 10 00:18:33 2007 @@ -104,20 +104,20 @@ self.assertEqual(heap_sorted, sorted(data)) def test_nsmallest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nsmallest(n, data), sorted(data)[:n]) - self.assertEqual(nsmallest(n, data, key=f), - sorted(data, key=f)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nsmallest(n, data), sorted(data)[:n]) + self.assertEqual(nsmallest(n, data, key=f), + sorted(data, key=f)[:n]) def test_nlargest(self): - data = [random.randrange(2000) for i in range(1000)] - f = lambda x: x * 547 % 2000 - for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): - self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) - self.assertEqual(nlargest(n, data, key=f), - sorted(data, key=f, reverse=True)[:n]) + data = [(random.randrange(2000), i) for i in range(1000)] + for f in (None, lambda x: x[0] * 547 % 2000): + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n]) + self.assertEqual(nlargest(n, data, key=f), + sorted(data, key=f, reverse=True)[:n]) #============================================================================== Modified: python/branches/p3yk/Lib/test/test_import.py ============================================================================== --- python/branches/p3yk/Lib/test/test_import.py (original) +++ python/branches/p3yk/Lib/test/test_import.py Wed Jan 10 00:18:33 2007 @@ -1,10 +1,11 @@ -from test.test_support import TESTFN, run_unittest +from test.test_support import TESTFN, run_unittest, guard_warnings_filter import unittest import os import random import sys import py_compile +import warnings def remove_files(name): @@ -204,15 +205,11 @@ self.assert_(y is test.test_support, y.__name__) def test_import_initless_directory_warning(self): - import warnings - oldfilters = warnings.filters[:] - warnings.simplefilter('error', ImportWarning); - try: + with guard_warnings_filter(): # Just a random non-package directory we always expect to be # somewhere in sys.path... + warnings.simplefilter('error', ImportWarning) self.assertRaises(ImportWarning, __import__, "site-packages") - finally: - warnings.filters = oldfilters def test_main(verbose=None): run_unittest(ImportTest) Modified: python/branches/p3yk/Lib/test/test_pty.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pty.py (original) +++ python/branches/p3yk/Lib/test/test_pty.py Wed Jan 10 00:18:33 2007 @@ -115,6 +115,12 @@ os._exit(4) else: debug("Waiting for child (%d) to finish."%pid) + ##line = os.read(master_fd, 80) + ##lines = line.replace('\r\n', '\n').split('\n') + ##if False and lines != ['In child, calling os.setsid()', + ## 'Good: OSError was raised.', '']: + ## raise TestFailed("Unexpected output from child: %r" % line) + (pid, status) = os.waitpid(pid, 0) res = status >> 8 debug("Child (%d) exited with status %d (%d)."%(pid, res, status)) @@ -127,6 +133,15 @@ elif res != 4: raise TestFailed, "pty.fork() failed for unknown reasons." + ##debug("Reading from master_fd now that the child has exited") + ##try: + ## s1 = os.read(master_fd, 1024) + ##except os.error: + ## pass + ##else: + ## raise TestFailed("Read from master_fd did not raise exception") + + os.close(master_fd) # pty.fork() passed. Modified: python/branches/p3yk/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk/Lib/test/test_random.py (original) +++ python/branches/p3yk/Lib/test/test_random.py Wed Jan 10 00:18:33 2007 @@ -180,10 +180,9 @@ def test_bigrand(self): # Verify warnings are raised when randrange is too large for random() - oldfilters = warnings.filters[:] - warnings.filterwarnings("error", "Underlying random") - self.assertRaises(UserWarning, self.gen.randrange, 2**60) - warnings.filters[:] = oldfilters + with test_support.guard_warnings_filter(): + warnings.filterwarnings("error", "Underlying random") + self.assertRaises(UserWarning, self.gen.randrange, 2**60) class SystemRandom_TestBasicOps(TestBasicOps): gen = random.SystemRandom() @@ -441,6 +440,14 @@ self.assertEqual(k, numbits) # note the stronger assertion self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion + def test_randrange_bug_1590891(self): + start = 1000000000000 + stop = -100000000000000000000 + step = -200 + x = self.gen.randrange(start, stop, step) + self.assert_(stop < x <= start) + self.assertEqual((x+stop)%step, 0) + _gammacoeff = (0.9999999999995183, 676.5203681218835, -1259.139216722289, 771.3234287757674, -176.6150291498386, 12.50734324009056, -0.1385710331296526, 0.9934937113930748e-05, 0.1659470187408462e-06) Modified: python/branches/p3yk/Lib/test/test_repr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_repr.py (original) +++ python/branches/p3yk/Lib/test/test_repr.py Wed Jan 10 00:18:33 2007 @@ -136,7 +136,6 @@ '> fo, s, + fo.close() + fo = open(test_support.TESTFN, "rb") + self.assertEqual(fo.read(), repr(s)) + finally: + fo.close() + os.remove(test_support.TESTFN) + class TestSet(TestJointOps): thetype = set Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Wed Jan 10 00:18:33 2007 @@ -50,22 +50,17 @@ def with_warning_restore(func): def _with_warning_restore(*args, **kw): - # The `warnings` module doesn't have an advertised way to restore - # its filter list. Cheat. - save_warnings_filters = warnings.filters[:] - # Grrr, we need this function to warn every time. Without removing - # the warningregistry, running test_tarfile then test_struct would fail - # on 64-bit platforms. - globals = func.func_globals - if '__warningregistry__' in globals: - del globals['__warningregistry__'] - warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) - warnings.filterwarnings("error", r""".*format requires.*""", - DeprecationWarning) - try: + with test.test_support.guard_warnings_filter(): + # Grrr, we need this function to warn every time. Without removing + # the warningregistry, running test_tarfile then test_struct would fail + # on 64-bit platforms. + globals = func.func_globals + if '__warningregistry__' in globals: + del globals['__warningregistry__'] + warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) + warnings.filterwarnings("error", r""".*format requires.*""", + DeprecationWarning) return func(*args, **kw) - finally: - warnings.filters[:] = save_warnings_filters[:] return _with_warning_restore def deprecated_err(func, *args): Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Wed Jan 10 00:18:33 2007 @@ -3,7 +3,9 @@ if __name__ != 'test.test_support': raise ImportError, 'test_support must be imported from the test package' +from contextlib import contextmanager import sys +import warnings class Error(Exception): """Base class for regression test exceptions.""" @@ -267,6 +269,48 @@ print >> get_original_stdout(), '\tfetching %s ...' % url fn, _ = urllib.urlretrieve(url, filename) return open(fn) + + at contextmanager +def guard_warnings_filter(): + """Guard the warnings filter from being permanently changed.""" + original_filters = warnings.filters[:] + try: + yield + finally: + warnings.filters = original_filters + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting Modified: python/branches/p3yk/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk/Lib/test/test_tarfile.py Wed Jan 10 00:18:33 2007 @@ -110,7 +110,7 @@ """Test seek() method of _FileObject, incl. random reading. """ if self.sep != "|": - filename = "0-REGTYPE" + filename = "0-REGTYPE-TEXT" self.tar.extract(filename, dirname()) f = open(os.path.join(dirname(), filename), "rb") data = f.read() @@ -149,6 +149,16 @@ s2 = fobj.readlines() self.assert_(s1 == s2, "readlines() after seek failed") + fobj.seek(0) + self.assert_(len(fobj.readline()) == fobj.tell(), + "tell() after readline() failed") + fobj.seek(512) + self.assert_(len(fobj.readline()) + 512 == fobj.tell(), + "tell() after seek() and readline() failed") + fobj.seek(0) + line = fobj.readline() + self.assert_(fobj.read() == data[len(line):], + "read() after readline() failed") fobj.close() def test_old_dirtype(self): @@ -280,6 +290,20 @@ else: self.dst.addfile(tarinfo, f) + def test_add_self(self): + dstname = os.path.abspath(self.dstname) + + self.assertEqual(self.dst.name, dstname, "archive name must be absolute") + + self.dst.add(dstname) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + + cwd = os.getcwd() + os.chdir(dirname()) + self.dst.add(dstname) + os.chdir(cwd) + self.assertEqual(self.dst.getnames(), [], "added the archive to itself") + class Write100Test(BaseTest): # The name field in a tar header stores strings of at most 100 chars. @@ -601,6 +625,38 @@ self.assertEqual(tarfile.filemode(0755), '-rwxr-xr-x') self.assertEqual(tarfile.filemode(07111), '---s--s--t') +class HeaderErrorTest(unittest.TestCase): + + def test_truncated_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "filename\0") + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 511) + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 513) + + def test_empty_header(self): + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, "\0" * 512) + + def test_invalid_header(self): + buf = tarfile.TarInfo("filename").tobuf() + buf = buf[:148] + "foo\0\0\0\0\0" + buf[156:] # invalid number field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, buf) + + def test_bad_checksum(self): + buf = tarfile.TarInfo("filename").tobuf() + b = buf[:148] + " " + buf[156:] # clear the checksum field. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + b = "a" + buf[1:] # manipulate the buffer, so checksum won't match. + self.assertRaises(tarfile.HeaderError, tarfile.TarInfo.frombuf, b) + +class OpenFileobjTest(BaseTest): + # Test for SF bug #1496501. + + def test_opener(self): + fobj = StringIO.StringIO("foo\n") + try: + tarfile.open("", "r", fileobj=fobj) + except tarfile.ReadError: + self.assertEqual(fobj.tell(), 0, "fileobj's position has moved") if bz2: # Bzip2 TestCases @@ -646,6 +702,8 @@ tests = [ FileModeTest, + HeaderErrorTest, + OpenFileobjTest, ReadTest, ReadStreamTest, ReadDetectTest, Modified: python/branches/p3yk/Lib/test/test_uu.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uu.py (original) +++ python/branches/p3yk/Lib/test/test_uu.py Wed Jan 10 00:18:33 2007 @@ -114,11 +114,11 @@ def test_encode(self): try: - fin = open(self.tmpin, 'wb') + fin = open(self.tmpin, 'w') fin.write(plaintext) fin.close() - fin = open(self.tmpin, 'rb') + fin = open(self.tmpin, 'r') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() @@ -130,7 +130,7 @@ self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames - uu.encode(self.tmpin, self.tmpout, mode=0644) + uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() @@ -142,11 +142,11 @@ def test_decode(self): try: - f = open(self.tmpin, 'wb') + f = open(self.tmpin, 'w') f.write(encodedtextwrapped % (0644, self.tmpout)) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() @@ -163,11 +163,11 @@ try: f = cStringIO.StringIO(encodedtextwrapped % (0644, self.tmpout)) - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') uu.decode(f) f.close() - f = open(self.tmpin, 'rb') + f = open(self.tmpin, 'r') self.assertRaises(uu.Error, uu.decode, f) f.close() finally: Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Wed Jan 10 00:18:33 2007 @@ -189,7 +189,7 @@ # None as the value for the callback, where either means "no # callback". The "no callback" ref and proxy objects are supposed # to be shared so long as they exist by all callers so long as - # they are active. In Python 2.3.3 and earlier, this guaranttee + # they are active. In Python 2.3.3 and earlier, this guarantee # was not honored, and was broken in different ways for # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.) Modified: python/branches/p3yk/Lib/threading.py ============================================================================== --- python/branches/p3yk/Lib/threading.py (original) +++ python/branches/p3yk/Lib/threading.py Wed Jan 10 00:18:33 2007 @@ -636,13 +636,11 @@ _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() - import atexit - atexit.register(self.__exitfunc) def _set_daemon(self): return False - def __exitfunc(self): + def _exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: @@ -715,9 +713,11 @@ from thread import stack_size -# Create the main thread object +# Create the main thread object, +# and make it available for the interpreter +# (Py_Main) as threading._shutdown. -_MainThread() +_shutdown = _MainThread()._exitfunc # get thread-local implementation, either from the thread # module, or from the python fallback Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Wed Jan 10 00:18:33 2007 @@ -405,8 +405,8 @@ h.putheader('Content-Length', '%d' % len(data)) else: h.putrequest('GET', selector) - if proxy_auth: h.putheader('Proxy-Authorization: Basic %s' % proxy_auth) - if auth: h.putheader('Authorization: Basic %s' % auth) + if proxy_auth: h.putheader('Proxy-Authorization', 'Basic %s' % proxy_auth) + if auth: h.putheader('Authorization', 'Basic %s' % auth) if realhost: h.putheader('Host', realhost) for args in self.addheaders: h.putheader(*args) h.endheaders() Modified: python/branches/p3yk/Misc/ACKS ============================================================================== --- python/branches/p3yk/Misc/ACKS (original) +++ python/branches/p3yk/Misc/ACKS Wed Jan 10 00:18:33 2007 @@ -285,6 +285,7 @@ Albert Hofkamp Jonathan Hogg Gerrit Holl +Shane Holloway Rune Holm Philip Homburg Naofumi Honda Modified: python/branches/p3yk/Misc/developers.txt ============================================================================== --- python/branches/p3yk/Misc/developers.txt (original) +++ python/branches/p3yk/Misc/developers.txt Wed Jan 10 00:18:33 2007 @@ -17,6 +17,15 @@ Permissions History ------------------- +- Josiah Carlson (SF name "josiahcarlson") added to the SourceForge Python + project 06 Jan 2007, by NCN, as a tracker tech. He will maintain asyncore. + +- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP + update access. + +- Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py + related work. + - 2006 Summer of Code entries: SoC developers are expected to work primarily in nondist/sandbox or on a branch of their own, and will have their work reviewed before changes are accepted into the trunk. Modified: python/branches/p3yk/Modules/_bsddb.c ============================================================================== --- python/branches/p3yk/Modules/_bsddb.c (original) +++ python/branches/p3yk/Modules/_bsddb.c Wed Jan 10 00:18:33 2007 @@ -98,7 +98,7 @@ #error "eek! DBVER can't handle minor versions > 9" #endif -#define PY_BSDDB_VERSION "4.4.6" +#define PY_BSDDB_VERSION "4.5.0" static char *rcs_id = "$Id$"; @@ -4127,6 +4127,7 @@ } +#if (DBVER < 45) static PyObject* DBEnv_set_lk_max(DBEnvObject* self, PyObject* args) { @@ -4142,6 +4143,7 @@ RETURN_IF_ERR(); RETURN_NONE(); } +#endif #if (DBVER >= 32) @@ -5231,7 +5233,9 @@ {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, #endif {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +#if (DBVER < 45) {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, +#endif #if (DBVER >= 32) {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, @@ -5833,7 +5837,9 @@ ADD_INT(d, DB_AFTER); ADD_INT(d, DB_APPEND); ADD_INT(d, DB_BEFORE); +#if (DBVER < 45) ADD_INT(d, DB_CACHED_COUNTS); +#endif #if (DBVER >= 41) _addIntToDict(d, "DB_CHECKPOINT", 0); #else @@ -5868,7 +5874,9 @@ ADD_INT(d, DB_POSITION); ADD_INT(d, DB_PREV); ADD_INT(d, DB_PREV_NODUP); +#if (DBVER < 45) ADD_INT(d, DB_RECORDCOUNT); +#endif ADD_INT(d, DB_SET); ADD_INT(d, DB_SET_RANGE); ADD_INT(d, DB_SET_RECNO); Modified: python/branches/p3yk/Modules/bz2module.c ============================================================================== --- python/branches/p3yk/Modules/bz2module.c (original) +++ python/branches/p3yk/Modules/bz2module.c Wed Jan 10 00:18:33 2007 @@ -989,7 +989,7 @@ char small_buffer[SMALLCHUNK]; char *buffer = small_buffer; size_t buffersize = SMALLCHUNK; - int bytesread = 0; + Py_off_t bytesread = 0; size_t readsize; int chunksize; int bzerror; Modified: python/branches/p3yk/Modules/collectionsmodule.c ============================================================================== --- python/branches/p3yk/Modules/collectionsmodule.c (original) +++ python/branches/p3yk/Modules/collectionsmodule.c Wed Jan 10 00:18:33 2007 @@ -911,15 +911,14 @@ { PyObject *item; - if (it->counter == 0) - return NULL; - if (it->deque->state != it->state) { it->counter = 0; PyErr_SetString(PyExc_RuntimeError, "deque mutated during iteration"); return NULL; } + if (it->counter == 0) + return NULL; assert (!(it->b == it->deque->rightblock && it->index > it->deque->rightindex)); Modified: python/branches/p3yk/Modules/main.c ============================================================================== --- python/branches/p3yk/Modules/main.c (original) +++ python/branches/p3yk/Modules/main.c Wed Jan 10 00:18:33 2007 @@ -175,6 +175,33 @@ return 0; } +/* Wait until threading._shutdown completes, provided + the threading module was imported in the first place. + The shutdown routine will wait until all non-daemon + "threading" threads have completed. */ +#include "abstract.h" +static void +WaitForThreadShutdown(void) +{ +#ifdef WITH_THREAD + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); +#endif +} + /* Main program */ int @@ -483,6 +510,8 @@ /* XXX */ sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + WaitForThreadShutdown(); + Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Wed Jan 10 00:18:33 2007 @@ -2210,7 +2210,7 @@ /* * This is the guts of the recv() and recv_into() methods, which reads into a - * char buffer. If you have any inc/def ref to do to the objects that contain + * char buffer. If you have any inc/dec ref to do to the objects that contain * the buffer, do it in the caller. This function returns the number of bytes * succesfully read. If there was an error, it returns -1. Note that it is * also possible that we return a number of bytes smaller than the request Modified: python/branches/p3yk/Modules/timemodule.c ============================================================================== --- python/branches/p3yk/Modules/timemodule.c (original) +++ python/branches/p3yk/Modules/timemodule.c Wed Jan 10 00:18:33 2007 @@ -659,7 +659,7 @@ time_tzset. In the future, some parts of it can be moved back (for platforms that don't HAVE_WORKING_TZSET, when we know what they are), and the extranious calls to tzset(3) should be removed. - I havn't done this yet, as I don't want to change this code as + I haven't done this yet, as I don't want to change this code as little as possible when introducing the time.tzset and time.tzsetwall methods. This should simply be a method of doing the following once, at the top of this function and removing the call to tzset() from Modified: python/branches/p3yk/Objects/dictnotes.txt ============================================================================== --- python/branches/p3yk/Objects/dictnotes.txt (original) +++ python/branches/p3yk/Objects/dictnotes.txt Wed Jan 10 00:18:33 2007 @@ -44,7 +44,7 @@ d.setdefault(word, []).append(pagenumber) Note, the second example is a use case characterized by a get and set - to the same key. There are similar used cases with a __contains__ + to the same key. There are similar use cases with a __contains__ followed by a get, set, or del to the same key. Part of the justification for d.setdefault is combining the two lookups into one. Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Wed Jan 10 00:18:33 2007 @@ -573,8 +573,17 @@ char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; int literalform = 0; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return status; + fprintf(fp, "%s(...)", so->ob_type->tp_name); + return 0; + } if (!so->used) { + Py_ReprLeave((PyObject*)so); fprintf(fp, "%s()", so->ob_type->tp_name); return 0; } @@ -587,32 +596,44 @@ while (set_next(so, &pos, &entry)) { fputs(emit, fp); emit = separator; - if (PyObject_Print(entry->key, fp, 0) != 0) + if (PyObject_Print(entry->key, fp, 0) != 0) { + Py_ReprLeave((PyObject*)so); return -1; + } } if (literalform) fputs("}", fp); else fputs("])", fp); + Py_ReprLeave((PyObject*)so); return 0; } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result, *listrepr; + PyObject *keys, *result=NULL, *listrepr; + int status = Py_ReprEnter((PyObject*)so); + + if (status != 0) { + if (status < 0) + return NULL; + return PyString_FromFormat("%s(...)", so->ob_type->tp_name); + } /* shortcut for the empty set */ - if (!so->used) + if (!so->used) { + Py_ReprLeave((PyObject*)so); return PyString_FromFormat("%s()", so->ob_type->tp_name); + } keys = PySequence_List((PyObject *)so); if (keys == NULL) - return NULL; + goto done; listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) - return NULL; + goto done; if (so->ob_type == &PySet_Type) { char *s = PyString_AS_STRING(listrepr); @@ -624,6 +645,8 @@ PyString_AS_STRING(listrepr)); } Py_DECREF(listrepr); +done: + Py_ReprLeave((PyObject*)so); return result; } Modified: python/branches/p3yk/PC/python_nt.rc ============================================================================== --- python/branches/p3yk/PC/python_nt.rc (original) +++ python/branches/p3yk/PC/python_nt.rc Wed Jan 10 00:18:33 2007 @@ -61,7 +61,7 @@ VALUE "FileDescription", "Python Core\0" VALUE "FileVersion", PYTHON_VERSION VALUE "InternalName", "Python DLL\0" - VALUE "LegalCopyright", "Copyright ? 2001-2006 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" + VALUE "LegalCopyright", "Copyright ? 2001-2007 Python Software Foundation. Copyright ? 2000 BeOpen.com. Copyright ? 1995-2001 CNRI. Copyright ? 1991-1995 SMC.\0" VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" VALUE "ProductName", "Python\0" VALUE "ProductVersion", PYTHON_VERSION Modified: python/branches/p3yk/PCbuild/python20.wse ============================================================================== --- python/branches/p3yk/PCbuild/python20.wse (original) +++ python/branches/p3yk/PCbuild/python20.wse Wed Jan 10 00:18:33 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/p3yk/PCbuild8/python20.wse ============================================================================== --- python/branches/p3yk/PCbuild8/python20.wse (original) +++ python/branches/p3yk/PCbuild8/python20.wse Wed Jan 10 00:18:33 2007 @@ -24,8 +24,8 @@ Dialogs Version=8 Version File=2.4a1 Version Description=Python Programming Language - Version Copyright=?2001-2006 Python Software Foundation - Version Company=PythonLabs at Zope Corporation + Version Copyright=?2001-2007 Python Software Foundation + Version Company=Python Software Foundation Crystal Format=10111100101100000010001001001001 Step View=&All Variable Name1=_WISE_ Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Wed Jan 10 00:18:33 2007 @@ -738,7 +738,16 @@ this wasn't always true before 2.3! PyFrame_New now sets f->f_lasti to -1 (i.e. the index *before* the first instruction) and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. */ + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ next_instr = first_instr + f->f_lasti + 1; stack_pointer = f->f_stacktop; assert(stack_pointer != NULL); Modified: python/branches/p3yk/Python/errors.c ============================================================================== --- python/branches/p3yk/Python/errors.c (original) +++ python/branches/p3yk/Python/errors.c Wed Jan 10 00:18:33 2007 @@ -649,7 +649,8 @@ if (warnings_module != NULL) { dict = PyModule_GetDict(warnings_module); - func = PyDict_GetItemString(dict, "warn"); + if (dict != NULL) + func = PyDict_GetItemString(dict, "warn"); } if (func == NULL) { PySys_WriteStderr("warning: %s\n", message); Modified: python/branches/p3yk/Python/getcopyright.c ============================================================================== --- python/branches/p3yk/Python/getcopyright.c (original) +++ python/branches/p3yk/Python/getcopyright.c Wed Jan 10 00:18:33 2007 @@ -4,7 +4,7 @@ static char cprt[] = "\ -Copyright (c) 2001-2006 Python Software Foundation.\n\ +Copyright (c) 2001-2007 Python Software Foundation.\n\ All Rights Reserved.\n\ \n\ Copyright (c) 2000 BeOpen.com.\n\ Modified: python/branches/p3yk/README ============================================================================== --- python/branches/p3yk/README (original) +++ python/branches/p3yk/README Wed Jan 10 00:18:33 2007 @@ -1,7 +1,8 @@ This is Python 3000 -- unversioned (branched off 2.5 in various beta stages) ================================================================= -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 +Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Wed Jan 10 00:18:33 2007 @@ -606,7 +606,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 4) + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -623,7 +623,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -631,7 +631,7 @@ db_inc_paths.append('/pkg/db-4.%d/include' % x) db_inc_paths.append('/opt/db-4.%d/include' % x) # 3.x minor number specific paths - for x in (2,3): + for x in (3,): db_inc_paths.append('/usr/include/db3%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x) db_inc_paths.append('/usr/local/include/db3%d' % x) From python-3000-checkins at python.org Wed Jan 10 02:28:35 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 02:28:35 +0100 (CET) Subject: [Python-3000-checkins] r53335 - in python/branches/p3yk: Doc/Makefile.deps Doc/lib/lib.tex Doc/lib/libsets.tex Doc/lib/libstdtypes.tex Lib/msilib/__init__.py Lib/sets.py Lib/test/test_cookielib.py Lib/test/test_set.py Lib/test/test_sets.py Message-ID: <20070110012835.B33831E4008@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 02:28:32 2007 New Revision: 53335 Removed: python/branches/p3yk/Lib/sets.py python/branches/p3yk/Lib/test/test_sets.py Modified: python/branches/p3yk/Doc/Makefile.deps python/branches/p3yk/Doc/lib/lib.tex python/branches/p3yk/Doc/lib/libsets.tex python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Lib/msilib/__init__.py python/branches/p3yk/Lib/test/test_cookielib.py python/branches/p3yk/Lib/test/test_set.py Log: Excise the sets module. SF #1500611 by Collin Winter. Modified: python/branches/p3yk/Doc/Makefile.deps ============================================================================== --- python/branches/p3yk/Doc/Makefile.deps (original) +++ python/branches/p3yk/Doc/Makefile.deps Wed Jan 10 02:28:32 2007 @@ -109,7 +109,6 @@ lib/libplatform.tex \ lib/libfpectl.tex \ lib/libgc.tex \ - lib/libsets.tex \ lib/libweakref.tex \ lib/libinspect.tex \ lib/libpydoc.tex \ Modified: python/branches/p3yk/Doc/lib/lib.tex ============================================================================== --- python/branches/p3yk/Doc/lib/lib.tex (original) +++ python/branches/p3yk/Doc/lib/lib.tex Wed Jan 10 02:28:32 2007 @@ -104,7 +104,6 @@ \input{libheapq} \input{libbisect} \input{libarray} -\input{libsets} \input{libsched} \input{libmutex} \input{libqueue} Modified: python/branches/p3yk/Doc/lib/libsets.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsets.tex (original) +++ python/branches/p3yk/Doc/lib/libsets.tex Wed Jan 10 02:28:32 2007 @@ -1,264 +0,0 @@ -\section{\module{sets} --- - Unordered collections of unique elements} - -\declaremodule{standard}{sets} -\modulesynopsis{Implementation of sets of unique elements.} -\moduleauthor{Greg V. Wilson}{gvwilson at nevex.com} -\moduleauthor{Alex Martelli}{aleax at aleax.it} -\moduleauthor{Guido van Rossum}{guido at python.org} -\sectionauthor{Raymond D. Hettinger}{python at rcn.com} - -\versionadded{2.3} - -The \module{sets} module provides classes for constructing and manipulating -unordered collections of unique elements. Common uses include membership -testing, removing duplicates from a sequence, and computing standard math -operations on sets such as intersection, union, difference, and symmetric -difference. - -Like other collections, sets support \code{\var{x} in \var{set}}, -\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an -unordered collection, sets do not record element position or order of -insertion. Accordingly, sets do not support indexing, slicing, or -other sequence-like behavior. - -Most set applications use the \class{Set} class which provides every set -method except for \method{__hash__()}. For advanced applications requiring -a hash method, the \class{ImmutableSet} class adds a \method{__hash__()} -method but omits methods which alter the contents of the set. Both -\class{Set} and \class{ImmutableSet} derive from \class{BaseSet}, an -abstract class useful for determining whether something is a set: -\code{isinstance(\var{obj}, BaseSet)}. - -The set classes are implemented using dictionaries. Accordingly, the -requirements for set elements are the same as those for dictionary keys; -namely, that the element defines both \method{__eq__} and \method{__hash__}. -As a result, sets -cannot contain mutable elements such as lists or dictionaries. -However, they can contain immutable collections such as tuples or -instances of \class{ImmutableSet}. For convenience in implementing -sets of sets, inner sets are automatically converted to immutable -form, for example, \code{Set([Set(['dog'])])} is transformed to -\code{Set([ImmutableSet(['dog'])])}. - -\begin{classdesc}{Set}{\optional{iterable}} -Constructs a new empty \class{Set} object. If the optional \var{iterable} -parameter is supplied, updates the set with elements obtained from iteration. -All of the elements in \var{iterable} should be immutable or be transformable -to an immutable using the protocol described in -section~\ref{immutable-transforms}. -\end{classdesc} - -\begin{classdesc}{ImmutableSet}{\optional{iterable}} -Constructs a new empty \class{ImmutableSet} object. If the optional -\var{iterable} parameter is supplied, updates the set with elements obtained -from iteration. All of the elements in \var{iterable} should be immutable or -be transformable to an immutable using the protocol described in -section~\ref{immutable-transforms}. - -Because \class{ImmutableSet} objects provide a \method{__hash__()} method, -they can be used as set elements or as dictionary keys. \class{ImmutableSet} -objects do not have methods for adding or removing elements, so all of the -elements must be known when the constructor is called. -\end{classdesc} - - -\subsection{Set Objects \label{set-objects}} - -Instances of \class{Set} and \class{ImmutableSet} both provide -the following operations: - -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} - \lineiii{len(\var{s})}{}{cardinality of set \var{s}} - - \hline - \lineiii{\var{x} in \var{s}}{} - {test \var{x} for membership in \var{s}} - \lineiii{\var{x} not in \var{s}}{} - {test \var{x} for non-membership in \var{s}} - \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}} - {test whether every element in \var{s} is in \var{t}} - \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}} - {test whether every element in \var{t} is in \var{s}} - - \hline - \lineiii{\var{s}.union(\var{t})}{\var{s} \textbar{} \var{t}} - {new set with elements from both \var{s} and \var{t}} - \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}} - {new set with elements common to \var{s} and \var{t}} - \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}} - {new set with elements in \var{s} but not in \var{t}} - \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}} - {new set with elements in either \var{s} or \var{t} but not both} - \lineiii{\var{s}.copy()}{} - {new set with a shallow copy of \var{s}} -\end{tableiii} - -Note, the non-operator versions of \method{union()}, -\method{intersection()}, \method{difference()}, and -\method{symmetric_difference()} will accept any iterable as an argument. -In contrast, their operator based counterparts require their arguments to -be sets. This precludes error-prone constructions like -\code{Set('abc') \&\ 'cbs'} in favor of the more readable -\code{Set('abc').intersection('cbs')}. -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} - -In addition, both \class{Set} and \class{ImmutableSet} -support set to set comparisons. Two sets are equal if and only if -every element of each set is contained in the other (each is a subset -of the other). -A set is less than another set if and only if the first set is a proper -subset of the second set (is a subset, but is not equal). -A set is greater than another set if and only if the first set is a proper -superset of the second set (is a superset, but is not equal). - -The subset and equality comparisons do not generalize to a complete -ordering function. For example, any two disjoint sets are not equal and -are not subsets of each other, so \emph{all} of the following return -\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or -\code{\var{a}>\var{b}}. -Accordingly, sets do not implement the \method{__cmp__} method. - -Since sets only define partial ordering (subset relationships), the output -of the \method{list.sort()} method is undefined for lists of sets. - -The following table lists operations available in \class{ImmutableSet} -but not found in \class{Set}: - -\begin{tableii}{c|l}{code}{Operation}{Result} - \lineii{hash(\var{s})}{returns a hash value for \var{s}} -\end{tableii} - -The following table lists operations available in \class{Set} -but not found in \class{ImmutableSet}: - -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} - \lineiii{\var{s}.update(\var{t})} - {\var{s} \textbar= \var{t}} - {return set \var{s} with elements added from \var{t}} - \lineiii{\var{s}.intersection_update(\var{t})} - {\var{s} \&= \var{t}} - {return set \var{s} keeping only elements also found in \var{t}} - \lineiii{\var{s}.difference_update(\var{t})} - {\var{s} -= \var{t}} - {return set \var{s} after removing elements found in \var{t}} - \lineiii{\var{s}.symmetric_difference_update(\var{t})} - {\var{s} \textasciicircum= \var{t}} - {return set \var{s} with elements from \var{s} or \var{t} - but not both} - - \hline - \lineiii{\var{s}.add(\var{x})}{} - {add element \var{x} to set \var{s}} - \lineiii{\var{s}.remove(\var{x})}{} - {remove \var{x} from set \var{s}; raises \exception{KeyError} - if not present} - \lineiii{\var{s}.discard(\var{x})}{} - {removes \var{x} from set \var{s} if present} - \lineiii{\var{s}.pop()}{} - {remove and return an arbitrary element from \var{s}; raises - \exception{KeyError} if empty} - \lineiii{\var{s}.clear()}{} - {remove all elements from set \var{s}} -\end{tableiii} - -Note, the non-operator versions of \method{update()}, -\method{intersection_update()}, \method{difference_update()}, and -\method{symmetric_difference_update()} will accept any iterable as -an argument. -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} - -Also note, the module also includes a \method{union_update()} method -which is an alias for \method{update()}. The method is included for -backwards compatibility. Programmers should prefer the -\method{update()} method because it is supported by the builtin -\class{set()} and \class{frozenset()} types. - -\subsection{Example \label{set-example}} - -\begin{verbatim} ->>> from sets import Set ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) ->>> employees = engineers | programmers | managers # union ->>> engineering_management = engineers & managers # intersection ->>> fulltime_management = managers - engineers - programmers # difference ->>> engineers.add('Marvin') # add element ->>> print engineers -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) ->>> employees.issuperset(engineers) # superset test -False ->>> employees.union_update(engineers) # update from another set ->>> employees.issuperset(engineers) -True ->>> for group in [engineers, programmers, managers, employees]: -... group.discard('Susan') # unconditionally remove element -... print group -... -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) -Set(['Janice', 'Jack', 'Sam']) -Set(['Jane', 'Zack', 'Jack']) -Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack']) -\end{verbatim} - - -\subsection{Protocol for automatic conversion to immutable - \label{immutable-transforms}} - -Sets can only contain immutable elements. For convenience, mutable -\class{Set} objects are automatically copied to an \class{ImmutableSet} -before being added as a set element. - -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. - -A similar mechanism is needed by the \method{__contains__()} and -\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__()}. - -The alternate mechanism spares the need to build a separate copy of -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}. - -The two mechanisms for adding hashability are normally invisible to the -user; however, a conflict can arise in a multi-threaded environment -where one thread is updating a set while another has temporarily wrapped it -in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets -are not thread-safe. - - -\subsection{Comparison to the built-in \class{set} types - \label{comparison-to-builtin-set}} - -The built-in \class{set} and \class{frozenset} types were designed based -on lessons learned from the \module{sets} module. The key differences are: - -\begin{itemize} -\item \class{Set} and \class{ImmutableSet} were renamed to \class{set} and - \class{frozenset}. -\item There is no equivalent to \class{BaseSet}. Instead, use - \code{isinstance(x, (set, frozenset))}. -\item The hash algorithm for the built-ins performs significantly better - (fewer collisions) for most datasets. -\item The built-in versions have more space efficient pickles. -\item The built-in versions do not have a \method{union_update()} method. - Instead, use the \method{update()} method which is equivalent. -\item The built-in versions do not have a \method{_repr(sorted=True)} method. - Instead, use the built-in \function{repr()} and \function{sorted()} - functions: \code{repr(sorted(s))}. -\item The built-in version does not have a protocol for automatic conversion - to immutable. Many found this feature to be confusing and no one - in the community reported having found real uses for it. -\end{itemize} Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Wed Jan 10 02:28:32 2007 @@ -1334,16 +1334,6 @@ \method{intersection_update()}, \method{difference_update()}, and \method{symmetric_difference_update()} methods will accept any iterable as an argument. - -The design of the set types was based on lessons learned from the -\module{sets} module. - -\begin{seealso} - \seelink{comparison-to-builtin-set.html} - {Comparison to the built-in set types} - {Differences between the \module{sets} module and the - built-in set types.} -\end{seealso} \section{Mapping Types --- \class{dict} \label{typesmapping}} Modified: python/branches/p3yk/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk/Lib/msilib/__init__.py (original) +++ python/branches/p3yk/Lib/msilib/__init__.py Wed Jan 10 02:28:32 2007 @@ -2,7 +2,7 @@ # Copyright (C) 2005 Martin v. L?wis # Licensed to PSF under a Contributor Agreement. from _msi import * -import sets, os, string, re +import os, string, re Win64=0 @@ -184,7 +184,7 @@ def __init__(self, name): self.name = name self.files = [] - self.filenames = sets.Set() + self.filenames = set() self.index = 0 def gen_id(self, file): @@ -215,7 +215,7 @@ os.unlink(filename) db.Commit() -_directories = sets.Set() +_directories = set() class Directory: def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None): """Create a new directory in the Directory table. There is a current component @@ -239,8 +239,8 @@ self.physical = physical self.logical = logical self.component = None - self.short_names = sets.Set() - self.ids = sets.Set() + self.short_names = set() + self.ids = set() self.keyfiles = {} self.componentflags = componentflags if basedir: Deleted: /python/branches/p3yk/Lib/sets.py ============================================================================== --- /python/branches/p3yk/Lib/sets.py Wed Jan 10 02:28:32 2007 +++ (empty file) @@ -1,577 +0,0 @@ -"""Classes to represent arbitrary sets (including sets of sets). - -This module implements sets using dictionaries whose values are -ignored. The usual operations (union, intersection, deletion, etc.) -are provided as both methods and operators. - -Important: sets are not sequences! While they support 'x in s', -'len(s)', and 'for x in s', none of those operations are unique for -sequences; for example, mappings support all three as well. The -characteristic operation for sequences is subscripting with small -integers: s[i], for i in range(len(s)). Sets don't support -subscripting at all. Also, sequences allow multiple occurrences and -their elements have a definite order; sets on the other hand don't -record multiple occurrences and don't remember the order of element -insertion (which is why they don't support s[i]). - -The following classes are provided: - -BaseSet -- All the operations common to both mutable and immutable - sets. This is an abstract class, not meant to be directly - instantiated. - -Set -- Mutable sets, subclass of BaseSet; not hashable. - -ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. - An iterable argument is mandatory to create an ImmutableSet. - -_TemporarilyImmutableSet -- A wrapper around a Set, hashable, - giving the same hash value as the immutable set equivalent - would have. Do not use this class directly. - -Only hashable objects can be added to a Set. In particular, you cannot -really add a Set as an element to another Set; if you try, what is -actually added is an ImmutableSet built from it (it compares equal to -the one you tried adding). - -When you ask if `x in y' where x is a Set and y is a Set or -ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and -what's tested is actually `z in y'. - -""" - -# Code history: -# -# - Greg V. Wilson wrote the first version, using a different approach -# to the mutable/immutable problem, and inheriting from dict. -# -# - Alex Martelli modified Greg's version to implement the current -# Set/ImmutableSet approach, and make the data an attribute. -# -# - Guido van Rossum rewrote much of the code, made some API changes, -# and cleaned up the docstrings. -# -# - Raymond Hettinger added a number of speedups and other -# improvements. - -from __future__ import generators -try: - from itertools import ifilter, ifilterfalse -except ImportError: - # Code to make the module run under Py2.2 - def ifilter(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if predicate(x): - yield x - def ifilterfalse(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if not predicate(x): - yield x - try: - True, False - except NameError: - True, False = (0==0, 0!=0) - -__all__ = ['BaseSet', 'Set', 'ImmutableSet'] - -class BaseSet(object): - """Common base class for mutable and immutable sets.""" - - __slots__ = ['_data'] - - # Constructor - - def __init__(self): - """This is an abstract class.""" - # Don't call this from a concrete subclass! - if self.__class__ is BaseSet: - raise TypeError, ("BaseSet is an abstract class. " - "Use Set or ImmutableSet.") - - # Standard protocols: __len__, __repr__, __str__, __iter__ - - def __len__(self): - """Return the number of elements of a set.""" - return len(self._data) - - def __repr__(self): - """Return string representation of a set. - - This looks like 'Set([])'. - """ - return self._repr() - - # __str__ is the same as __repr__ - __str__ = __repr__ - - def _repr(self, sorted=False): - elements = self._data.keys() - if sorted: - elements.sort() - return '%s(%r)' % (self.__class__.__name__, elements) - - def __iter__(self): - """Return an iterator over the elements or a set. - - This is the keys iterator for the underlying dict. - """ - return self._data.iterkeys() - - # Three-way comparison is not supported. However, because __eq__ is - # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and - # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this - # case). - - def __cmp__(self, other): - raise TypeError, "can't compare sets using cmp()" - - # Equality comparisons using the underlying dicts. Mixed-type comparisons - # are allowed here, where Set == z for non-Set z always returns False, - # and Set != z always True. This allows expressions like "x in y" to - # give the expected result when y is a sequence of mixed types, not - # raising a pointless TypeError just because y contains a Set, or x is - # a Set and y contain's a non-set ("in" invokes only __eq__). - # Subtle: it would be nicer if __eq__ and __ne__ could return - # NotImplemented instead of True or False. Then the other comparand - # would get a chance to determine the result, and if the other comparand - # also returned NotImplemented then it would fall back to object address - # comparison (which would always return False for __eq__ and always - # True for __ne__). However, that doesn't work, because this type - # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, - # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. - - def __eq__(self, other): - if isinstance(other, BaseSet): - return self._data == other._data - else: - return False - - def __ne__(self, other): - if isinstance(other, BaseSet): - return self._data != other._data - else: - return True - - # Copying operations - - def copy(self): - """Return a shallow copy of a set.""" - result = self.__class__() - result._data.update(self._data) - return result - - __copy__ = copy # For the copy module - - def __deepcopy__(self, memo): - """Return a deep copy of a set; used by copy module.""" - # This pre-creates the result and inserts it in the memo - # early, in case the deep copy recurses into another reference - # to this same set. A set can't be an element of itself, but - # it can certainly contain an object that has a reference to - # itself. - from copy import deepcopy - result = self.__class__() - memo[id(self)] = result - data = result._data - value = True - for elt in self: - data[deepcopy(elt, memo)] = value - return result - - # Standard set operations: union, intersection, both differences. - # Each has an operator version (e.g. __or__, invoked with |) and a - # method version (e.g. union). - # Subtle: Each pair requires distinct code so that the outcome is - # correct when the type of other isn't suitable. For example, if - # we did "union = __or__" instead, then Set().union(3) would return - # NotImplemented instead of raising TypeError (albeit that *why* it - # raises TypeError as-is is also a bit subtle). - - def __or__(self, other): - """Return the union of two sets as a new set. - - (I.e. all elements that are in either set.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.union(other) - - def union(self, other): - """Return the union of two sets as a new set. - - (I.e. all elements that are in either set.) - """ - result = self.__class__(self) - result._update(other) - return result - - def __and__(self, other): - """Return the intersection of two sets as a new set. - - (I.e. all elements that are in both sets.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.intersection(other) - - def intersection(self, other): - """Return the intersection of two sets as a new set. - - (I.e. all elements that are in both sets.) - """ - if not isinstance(other, BaseSet): - other = Set(other) - if len(self) <= len(other): - little, big = self, other - else: - little, big = other, self - common = ifilter(big._data.__contains__, little) - return self.__class__(common) - - def __xor__(self, other): - """Return the symmetric difference of two sets as a new set. - - (I.e. all elements that are in exactly one of the sets.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.symmetric_difference(other) - - def symmetric_difference(self, other): - """Return the symmetric difference of two sets as a new set. - - (I.e. all elements that are in exactly one of the sets.) - """ - result = self.__class__() - data = result._data - value = True - selfdata = self._data - try: - otherdata = other._data - except AttributeError: - otherdata = Set(other)._data - for elt in ifilterfalse(otherdata.__contains__, selfdata): - data[elt] = value - for elt in ifilterfalse(selfdata.__contains__, otherdata): - data[elt] = value - return result - - def __sub__(self, other): - """Return the difference of two sets as a new Set. - - (I.e. all elements that are in this set and not in the other.) - """ - if not isinstance(other, BaseSet): - return NotImplemented - return self.difference(other) - - def difference(self, other): - """Return the difference of two sets as a new Set. - - (I.e. all elements that are in this set and not in the other.) - """ - result = self.__class__() - data = result._data - try: - otherdata = other._data - except AttributeError: - otherdata = Set(other)._data - value = True - for elt in ifilterfalse(otherdata.__contains__, self): - data[elt] = value - return result - - # Membership test - - def __contains__(self, element): - """Report whether an element is a member of a set. - - (Called in response to the expression `element in self'.) - """ - try: - 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 - return transform() in self._data - - # Subset and superset test - - def issubset(self, other): - """Report whether another set contains this set.""" - self._binary_sanity_check(other) - if len(self) > len(other): # Fast check for obvious cases - return False - for elt in ifilterfalse(other._data.__contains__, self): - return False - return True - - def issuperset(self, other): - """Report whether this set contains another set.""" - self._binary_sanity_check(other) - if len(self) < len(other): # Fast check for obvious cases - return False - for elt in ifilterfalse(self._data.__contains__, other): - return False - return True - - # Inequality comparisons using the is-subset relation. - __le__ = issubset - __ge__ = issuperset - - def __lt__(self, other): - self._binary_sanity_check(other) - return len(self) < len(other) and self.issubset(other) - - def __gt__(self, other): - self._binary_sanity_check(other) - return len(self) > len(other) and self.issuperset(other) - - # Assorted helpers - - def _binary_sanity_check(self, other): - # Check that the other argument to a binary operation is also - # a set, raising a TypeError otherwise. - if not isinstance(other, BaseSet): - raise TypeError, "Binary operation only permitted between sets" - - def _compute_hash(self): - # Calculate hash code for a set by xor'ing the hash codes of - # the elements. This ensures that the hash code does not depend - # on the order in which elements are added to the set. This is - # not called __hash__ because a BaseSet should not be hashable; - # only an ImmutableSet is hashable. - result = 0 - for elt in self: - result ^= hash(elt) - return result - - def _update(self, iterable): - # The main loop for update() and the subclass __init__() methods. - data = self._data - - # Use the fast update() method when a dictionary is available. - if isinstance(iterable, BaseSet): - data.update(iterable._data) - return - - value = True - - if type(iterable) in (list, tuple, xrange): - # Optimized: we know that __iter__() and next() can't - # raise TypeError, so we can move 'try:' out of the loop. - it = iter(iterable) - while True: - try: - for element in it: - data[element] = value - return - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - else: - # Safe: only catch TypeError where intended - for element in iterable: - try: - data[element] = value - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - - -class ImmutableSet(BaseSet): - """Immutable set class.""" - - __slots__ = ['_hashcode'] - - # BaseSet + hashing - - def __init__(self, iterable=None): - """Construct an immutable set from an optional iterable.""" - self._hashcode = None - self._data = {} - if iterable is not None: - self._update(iterable) - - def __hash__(self): - if self._hashcode is None: - self._hashcode = self._compute_hash() - return self._hashcode - - def __getstate__(self): - return self._data, self._hashcode - - def __setstate__(self, state): - self._data, self._hashcode = state - -class Set(BaseSet): - """ Mutable set class.""" - - __slots__ = [] - - # BaseSet + operations requiring mutability; no hashing - - def __init__(self, iterable=None): - """Construct a set from an optional iterable.""" - self._data = {} - if iterable is not None: - self._update(iterable) - - def __getstate__(self): - # getstate's results are ignored if it is not - return self._data, - - def __setstate__(self, data): - self._data, = data - - def __hash__(self): - """A Set cannot be hashed.""" - # We inherit object.__hash__, so we must deny this explicitly - raise TypeError, "Can't hash a Set, only an ImmutableSet." - - # In-place union, intersection, differences. - # Subtle: The xyz_update() functions deliberately return None, - # as do all mutating operations on built-in container types. - # The __xyz__ spellings have to return self, though. - - def __ior__(self, other): - """Update a set with the union of itself and another.""" - self._binary_sanity_check(other) - self._data.update(other._data) - return self - - def union_update(self, other): - """Update a set with the union of itself and another.""" - self._update(other) - - def __iand__(self, other): - """Update a set with the intersection of itself and another.""" - self._binary_sanity_check(other) - self._data = (self & other)._data - return self - - def intersection_update(self, other): - """Update a set with the intersection of itself and another.""" - if isinstance(other, BaseSet): - self &= other - else: - self._data = (self.intersection(other))._data - - def __ixor__(self, other): - """Update a set with the symmetric difference of itself and another.""" - self._binary_sanity_check(other) - self.symmetric_difference_update(other) - return self - - def symmetric_difference_update(self, other): - """Update a set with the symmetric difference of itself and another.""" - data = self._data - value = True - if not isinstance(other, BaseSet): - other = Set(other) - if self is other: - self.clear() - for elt in other: - if elt in data: - del data[elt] - else: - data[elt] = value - - def __isub__(self, other): - """Remove all elements of another set from this set.""" - self._binary_sanity_check(other) - self.difference_update(other) - return self - - def difference_update(self, other): - """Remove all elements of another set from this set.""" - data = self._data - if not isinstance(other, BaseSet): - other = Set(other) - if self is other: - self.clear() - for elt in ifilter(data.__contains__, other): - del data[elt] - - # Python dict-like mass mutations: update, clear - - def update(self, iterable): - """Add all values from an iterable (such as a list or file).""" - self._update(iterable) - - def clear(self): - """Remove all elements from this set.""" - self._data.clear() - - # Single-element mutations: add, remove, discard - - def add(self, element): - """Add an element to a set. - - This has no effect if the element is already present. - """ - try: - self._data[element] = True - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - self._data[transform()] = True - - def remove(self, element): - """Remove an element from a set; it must be a member. - - If the element is not a member, raise a KeyError. - """ - try: - 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 - del self._data[transform()] - - def discard(self, element): - """Remove an element from a set if it is a member. - - If the element is not a member, do nothing. - """ - try: - self.remove(element) - except KeyError: - pass - - def pop(self): - """Remove and return an arbitrary set element.""" - 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) - - -class _TemporarilyImmutableSet(BaseSet): - # Wrap a mutable set as if it was temporarily immutable. - # This only supplies hashing and equality comparisons. - - def __init__(self, set): - self._set = set - self._data = set._data # Needed by ImmutableSet.__eq__() - - def __hash__(self): - return self._set._compute_hash() Modified: python/branches/p3yk/Lib/test/test_cookielib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cookielib.py (original) +++ python/branches/p3yk/Lib/test/test_cookielib.py Wed Jan 10 02:28:32 2007 @@ -1723,7 +1723,6 @@ def test_main(verbose=None): - from test import test_sets test_support.run_unittest( DateTimeTests, HeaderTests, Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Wed Jan 10 02:28:32 2007 @@ -1451,7 +1451,6 @@ #============================================================================== def test_main(verbose=None): - from test import test_sets test_classes = ( TestSet, TestSetSubclass, Deleted: /python/branches/p3yk/Lib/test/test_sets.py ============================================================================== --- /python/branches/p3yk/Lib/test/test_sets.py Wed Jan 10 02:28:32 2007 +++ (empty file) @@ -1,853 +0,0 @@ -#!/usr/bin/env python - -import unittest, operator, copy, pickle, random -from sets import Set, ImmutableSet -from test import test_support - -empty_set = Set() - -#============================================================================== - -class TestBasicOps(unittest.TestCase): - - def test_repr(self): - if self.repr is not None: - self.assertEqual(repr(self.set), self.repr) - - def test_length(self): - self.assertEqual(len(self.set), self.length) - - def test_self_equality(self): - self.assertEqual(self.set, self.set) - - def test_equivalent_equality(self): - self.assertEqual(self.set, self.dup) - - def test_copy(self): - self.assertEqual(self.set.copy(), self.dup) - - def test_self_union(self): - result = self.set | self.set - self.assertEqual(result, self.dup) - - def test_empty_union(self): - result = self.set | empty_set - self.assertEqual(result, self.dup) - - def test_union_empty(self): - result = empty_set | self.set - self.assertEqual(result, self.dup) - - def test_self_intersection(self): - result = self.set & self.set - self.assertEqual(result, self.dup) - - def test_empty_intersection(self): - result = self.set & empty_set - self.assertEqual(result, empty_set) - - def test_intersection_empty(self): - result = empty_set & self.set - self.assertEqual(result, empty_set) - - def test_self_symmetric_difference(self): - result = self.set ^ self.set - self.assertEqual(result, empty_set) - - def checkempty_symmetric_difference(self): - result = self.set ^ empty_set - self.assertEqual(result, self.set) - - def test_self_difference(self): - result = self.set - self.set - self.assertEqual(result, empty_set) - - def test_empty_difference(self): - result = self.set - empty_set - self.assertEqual(result, self.dup) - - def test_empty_difference_rev(self): - result = empty_set - self.set - self.assertEqual(result, empty_set) - - def test_iteration(self): - for v in self.set: - self.assert_(v in self.values) - - def test_pickling(self): - p = pickle.dumps(self.set) - copy = pickle.loads(p) - self.assertEqual(self.set, copy, - "%s != %s" % (self.set, copy)) - -#------------------------------------------------------------------------------ - -class TestBasicOpsEmpty(TestBasicOps): - def setUp(self): - self.case = "empty set" - self.values = [] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 0 - self.repr = "Set([])" - -#------------------------------------------------------------------------------ - -class TestBasicOpsSingleton(TestBasicOps): - def setUp(self): - self.case = "unit set (number)" - self.values = [3] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 1 - self.repr = "Set([3])" - - def test_in(self): - self.failUnless(3 in self.set) - - def test_not_in(self): - self.failUnless(2 not in self.set) - -#------------------------------------------------------------------------------ - -class TestBasicOpsTuple(TestBasicOps): - def setUp(self): - self.case = "unit set (tuple)" - self.values = [(0, "zero")] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 1 - self.repr = "Set([(0, 'zero')])" - - def test_in(self): - self.failUnless((0, "zero") in self.set) - - def test_not_in(self): - self.failUnless(9 not in self.set) - -#------------------------------------------------------------------------------ - -class TestBasicOpsTriple(TestBasicOps): - def setUp(self): - self.case = "triple set" - self.values = [0, "zero", operator.add] - self.set = Set(self.values) - self.dup = Set(self.values) - self.length = 3 - self.repr = None - -#============================================================================== - -def baditer(): - raise TypeError - yield True - -def gooditer(): - yield True - -class TestExceptionPropagation(unittest.TestCase): - """SF 628246: Set constructor should not trap iterator TypeErrors""" - - def test_instanceWithException(self): - self.assertRaises(TypeError, Set, baditer()) - - def test_instancesWithoutException(self): - # All of these iterables should load without exception. - Set([1,2,3]) - Set((1,2,3)) - Set({'one':1, 'two':2, 'three':3}) - Set(xrange(3)) - Set('abc') - Set(gooditer()) - -#============================================================================== - -class TestSetOfSets(unittest.TestCase): - def test_constructor(self): - inner = Set([1]) - outer = Set([inner]) - element = outer.pop() - self.assertEqual(type(element), ImmutableSet) - outer.add(inner) # Rebuild set of sets with .add method - outer.remove(inner) - self.assertEqual(outer, Set()) # Verify that remove worked - outer.discard(inner) # Absence of KeyError indicates working fine - -#============================================================================== - -class TestBinaryOps(unittest.TestCase): - def setUp(self): - self.set = Set((2, 4, 6)) - - def test_eq(self): # SF bug 643115 - self.assertEqual(self.set, Set({2:1,4:3,6:5})) - - def test_union_subset(self): - result = self.set | Set([2]) - self.assertEqual(result, Set((2, 4, 6))) - - def test_union_superset(self): - result = self.set | Set([2, 4, 6, 8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_union_overlap(self): - result = self.set | Set([3, 4, 5]) - self.assertEqual(result, Set([2, 3, 4, 5, 6])) - - def test_union_non_overlap(self): - result = self.set | Set([8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_intersection_subset(self): - result = self.set & Set((2, 4)) - self.assertEqual(result, Set((2, 4))) - - def test_intersection_superset(self): - result = self.set & Set([2, 4, 6, 8]) - self.assertEqual(result, Set([2, 4, 6])) - - def test_intersection_overlap(self): - result = self.set & Set([3, 4, 5]) - self.assertEqual(result, Set([4])) - - def test_intersection_non_overlap(self): - result = self.set & Set([8]) - self.assertEqual(result, empty_set) - - def test_sym_difference_subset(self): - result = self.set ^ Set((2, 4)) - self.assertEqual(result, Set([6])) - - def test_sym_difference_superset(self): - result = self.set ^ Set((2, 4, 6, 8)) - self.assertEqual(result, Set([8])) - - def test_sym_difference_overlap(self): - result = self.set ^ Set((3, 4, 5)) - self.assertEqual(result, Set([2, 3, 5, 6])) - - def test_sym_difference_non_overlap(self): - result = self.set ^ Set([8]) - self.assertEqual(result, Set([2, 4, 6, 8])) - - def test_cmp(self): - a, b = Set('a'), Set('b') - self.assertRaises(TypeError, cmp, a, b) - - # In py3k, this works! - self.assertRaises(TypeError, cmp, a, a) - - self.assertRaises(TypeError, cmp, a, 12) - self.assertRaises(TypeError, cmp, "abc", a) - - def test_inplace_on_self(self): - t = self.set.copy() - t |= t - self.assertEqual(t, self.set) - t &= t - self.assertEqual(t, self.set) - t -= t - self.assertEqual(len(t), 0) - t = self.set.copy() - t ^= t - self.assertEqual(len(t), 0) - - -#============================================================================== - -class TestUpdateOps(unittest.TestCase): - def setUp(self): - self.set = Set((2, 4, 6)) - - def test_union_subset(self): - self.set |= Set([2]) - self.assertEqual(self.set, Set((2, 4, 6))) - - def test_union_superset(self): - self.set |= Set([2, 4, 6, 8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_union_overlap(self): - self.set |= Set([3, 4, 5]) - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) - - def test_union_non_overlap(self): - self.set |= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_union_method_call(self): - self.set.union_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) - - def test_intersection_subset(self): - self.set &= Set((2, 4)) - self.assertEqual(self.set, Set((2, 4))) - - def test_intersection_superset(self): - self.set &= Set([2, 4, 6, 8]) - self.assertEqual(self.set, Set([2, 4, 6])) - - def test_intersection_overlap(self): - self.set &= Set([3, 4, 5]) - self.assertEqual(self.set, Set([4])) - - def test_intersection_non_overlap(self): - self.set &= Set([8]) - self.assertEqual(self.set, empty_set) - - def test_intersection_method_call(self): - self.set.intersection_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([4])) - - def test_sym_difference_subset(self): - self.set ^= Set((2, 4)) - self.assertEqual(self.set, Set([6])) - - def test_sym_difference_superset(self): - self.set ^= Set((2, 4, 6, 8)) - self.assertEqual(self.set, Set([8])) - - def test_sym_difference_overlap(self): - self.set ^= Set((3, 4, 5)) - self.assertEqual(self.set, Set([2, 3, 5, 6])) - - def test_sym_difference_non_overlap(self): - self.set ^= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6, 8])) - - def test_sym_difference_method_call(self): - self.set.symmetric_difference_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 3, 5, 6])) - - def test_difference_subset(self): - self.set -= Set((2, 4)) - self.assertEqual(self.set, Set([6])) - - def test_difference_superset(self): - self.set -= Set((2, 4, 6, 8)) - self.assertEqual(self.set, Set([])) - - def test_difference_overlap(self): - self.set -= Set((3, 4, 5)) - self.assertEqual(self.set, Set([2, 6])) - - def test_difference_non_overlap(self): - self.set -= Set([8]) - self.assertEqual(self.set, Set([2, 4, 6])) - - def test_difference_method_call(self): - self.set.difference_update(Set([3, 4, 5])) - self.assertEqual(self.set, Set([2, 6])) - -#============================================================================== - -class TestMutate(unittest.TestCase): - def setUp(self): - self.values = ["a", "b", "c"] - self.set = Set(self.values) - - def test_add_present(self): - self.set.add("c") - self.assertEqual(self.set, Set("abc")) - - def test_add_absent(self): - self.set.add("d") - self.assertEqual(self.set, Set("abcd")) - - def test_add_until_full(self): - tmp = Set() - expected_len = 0 - for v in self.values: - tmp.add(v) - expected_len += 1 - self.assertEqual(len(tmp), expected_len) - self.assertEqual(tmp, self.set) - - def test_remove_present(self): - self.set.remove("b") - self.assertEqual(self.set, Set("ac")) - - def test_remove_absent(self): - try: - self.set.remove("d") - self.fail("Removing missing element should have raised LookupError") - except LookupError: - pass - - def test_remove_until_empty(self): - expected_len = len(self.set) - for v in self.values: - self.set.remove(v) - expected_len -= 1 - self.assertEqual(len(self.set), expected_len) - - def test_discard_present(self): - self.set.discard("c") - self.assertEqual(self.set, Set("ab")) - - def test_discard_absent(self): - self.set.discard("d") - self.assertEqual(self.set, Set("abc")) - - def test_clear(self): - self.set.clear() - self.assertEqual(len(self.set), 0) - - def test_pop(self): - popped = {} - while self.set: - popped[self.set.pop()] = None - self.assertEqual(len(popped), len(self.values)) - for v in self.values: - self.failUnless(v in popped) - - def test_update_empty_tuple(self): - self.set.union_update(()) - self.assertEqual(self.set, Set(self.values)) - - def test_update_unit_tuple_overlap(self): - self.set.union_update(("a",)) - self.assertEqual(self.set, Set(self.values)) - - def test_update_unit_tuple_non_overlap(self): - self.set.union_update(("a", "z")) - self.assertEqual(self.set, Set(self.values + ["z"])) - -#============================================================================== - -class TestSubsets(unittest.TestCase): - - case2method = {"<=": "issubset", - ">=": "issuperset", - } - - reverse = {"==": "==", - "!=": "!=", - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=", - } - - def test_issubset(self): - x = self.left - y = self.right - for case in "!=", "==", "<", "<=", ">", ">=": - expected = case in self.cases - # Test the binary infix spelling. - result = eval("x" + case + "y", locals()) - self.assertEqual(result, expected) - # Test the "friendly" method-name spelling, if one exists. - if case in TestSubsets.case2method: - method = getattr(x, TestSubsets.case2method[case]) - result = method(y) - self.assertEqual(result, expected) - - # Now do the same for the operands reversed. - rcase = TestSubsets.reverse[case] - result = eval("y" + rcase + "x", locals()) - self.assertEqual(result, expected) - if rcase in TestSubsets.case2method: - method = getattr(y, TestSubsets.case2method[rcase]) - result = method(x) - self.assertEqual(result, expected) -#------------------------------------------------------------------------------ - -class TestSubsetEqualEmpty(TestSubsets): - left = Set() - right = Set() - name = "both empty" - cases = "==", "<=", ">=" - -#------------------------------------------------------------------------------ - -class TestSubsetEqualNonEmpty(TestSubsets): - left = Set([1, 2]) - right = Set([1, 2]) - name = "equal pair" - cases = "==", "<=", ">=" - -#------------------------------------------------------------------------------ - -class TestSubsetEmptyNonEmpty(TestSubsets): - left = Set() - right = Set([1, 2]) - name = "one empty, one non-empty" - cases = "!=", "<", "<=" - -#------------------------------------------------------------------------------ - -class TestSubsetPartial(TestSubsets): - left = Set([1]) - right = Set([1, 2]) - name = "one a non-empty proper subset of other" - cases = "!=", "<", "<=" - -#------------------------------------------------------------------------------ - -class TestSubsetNonOverlap(TestSubsets): - left = Set([1]) - right = Set([2]) - name = "neither empty, neither contains" - cases = "!=" - -#============================================================================== - -class TestOnlySetsInBinaryOps(unittest.TestCase): - - def test_eq_ne(self): - # Unlike the others, this is testing that == and != *are* allowed. - self.assertEqual(self.other == self.set, False) - self.assertEqual(self.set == self.other, False) - self.assertEqual(self.other != self.set, True) - self.assertEqual(self.set != self.other, True) - - def test_ge_gt_le_lt(self): - self.assertRaises(TypeError, lambda: self.set < self.other) - self.assertRaises(TypeError, lambda: self.set <= self.other) - self.assertRaises(TypeError, lambda: self.set > self.other) - self.assertRaises(TypeError, lambda: self.set >= self.other) - - self.assertRaises(TypeError, lambda: self.other < self.set) - self.assertRaises(TypeError, lambda: self.other <= self.set) - self.assertRaises(TypeError, lambda: self.other > self.set) - self.assertRaises(TypeError, lambda: self.other >= self.set) - - def test_union_update_operator(self): - try: - self.set |= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_union_update(self): - if self.otherIsIterable: - self.set.union_update(self.other) - else: - self.assertRaises(TypeError, self.set.union_update, self.other) - - def test_union(self): - self.assertRaises(TypeError, lambda: self.set | self.other) - self.assertRaises(TypeError, lambda: self.other | self.set) - if self.otherIsIterable: - self.set.union(self.other) - else: - self.assertRaises(TypeError, self.set.union, self.other) - - def test_intersection_update_operator(self): - try: - self.set &= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_intersection_update(self): - if self.otherIsIterable: - self.set.intersection_update(self.other) - else: - self.assertRaises(TypeError, - self.set.intersection_update, - self.other) - - def test_intersection(self): - self.assertRaises(TypeError, lambda: self.set & self.other) - self.assertRaises(TypeError, lambda: self.other & self.set) - if self.otherIsIterable: - self.set.intersection(self.other) - else: - self.assertRaises(TypeError, self.set.intersection, self.other) - - def test_sym_difference_update_operator(self): - try: - self.set ^= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_sym_difference_update(self): - if self.otherIsIterable: - self.set.symmetric_difference_update(self.other) - else: - self.assertRaises(TypeError, - self.set.symmetric_difference_update, - self.other) - - def test_sym_difference(self): - self.assertRaises(TypeError, lambda: self.set ^ self.other) - self.assertRaises(TypeError, lambda: self.other ^ self.set) - if self.otherIsIterable: - self.set.symmetric_difference(self.other) - else: - self.assertRaises(TypeError, self.set.symmetric_difference, self.other) - - def test_difference_update_operator(self): - try: - self.set -= self.other - except TypeError: - pass - else: - self.fail("expected TypeError") - - def test_difference_update(self): - if self.otherIsIterable: - self.set.difference_update(self.other) - else: - self.assertRaises(TypeError, - self.set.difference_update, - self.other) - - def test_difference(self): - self.assertRaises(TypeError, lambda: self.set - self.other) - self.assertRaises(TypeError, lambda: self.other - self.set) - if self.otherIsIterable: - self.set.difference(self.other) - else: - self.assertRaises(TypeError, self.set.difference, self.other) - -#------------------------------------------------------------------------------ - -class TestOnlySetsNumeric(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = 19 - self.otherIsIterable = False - -#------------------------------------------------------------------------------ - -class TestOnlySetsDict(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = {1:2, 3:4} - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsOperator(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = operator.add - self.otherIsIterable = False - -#------------------------------------------------------------------------------ - -class TestOnlySetsTuple(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = (2, 4, 6) - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsString(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = 'abc' - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsGenerator(TestOnlySetsInBinaryOps): - def setUp(self): - def gen(): - for i in xrange(0, 10, 2): - yield i - self.set = Set((1, 2, 3)) - self.other = gen() - self.otherIsIterable = True - -#------------------------------------------------------------------------------ - -class TestOnlySetsofSets(TestOnlySetsInBinaryOps): - def setUp(self): - self.set = Set((1, 2, 3)) - self.other = [Set('ab'), ImmutableSet('cd')] - self.otherIsIterable = True - -#============================================================================== - -class TestCopying(unittest.TestCase): - - def test_copy(self): - dup = self.set.copy() - dup_list = sorted(dup, key=repr) - set_list = sorted(self.set, key=repr) - self.assertEqual(len(dup_list), len(set_list)) - for i in range(len(dup_list)): - self.failUnless(dup_list[i] is set_list[i]) - - def test_deep_copy(self): - dup = copy.deepcopy(self.set) - ##print type(dup), repr(dup) - dup_list = sorted(dup, key=repr) - set_list = sorted(self.set, key=repr) - self.assertEqual(len(dup_list), len(set_list)) - for i in range(len(dup_list)): - self.assertEqual(dup_list[i], set_list[i]) - -#------------------------------------------------------------------------------ - -class TestCopyingEmpty(TestCopying): - def setUp(self): - self.set = Set() - -#------------------------------------------------------------------------------ - -class TestCopyingSingleton(TestCopying): - def setUp(self): - self.set = Set(["hello"]) - -#------------------------------------------------------------------------------ - -class TestCopyingTriple(TestCopying): - def setUp(self): - self.set = Set(["zero", 0, None]) - -#------------------------------------------------------------------------------ - -class TestCopyingTuple(TestCopying): - def setUp(self): - self.set = Set([(1, 2)]) - -#------------------------------------------------------------------------------ - -class TestCopyingNested(TestCopying): - def setUp(self): - self.set = Set([((1, 2), (3, 4))]) - -#============================================================================== - -class TestIdentities(unittest.TestCase): - def setUp(self): - self.a = Set([random.randrange(100) for i in xrange(50)]) - self.b = Set([random.randrange(100) for i in xrange(50)]) - - def test_binopsVsSubsets(self): - a, b = self.a, self.b - self.assert_(a - b <= a) - self.assert_(b - a <= b) - self.assert_(a & b <= a) - self.assert_(a & b <= b) - self.assert_(a | b >= a) - self.assert_(a | b >= b) - self.assert_(a ^ b <= a | b) - - def test_commutativity(self): - a, b = self.a, self.b - self.assertEqual(a&b, b&a) - self.assertEqual(a|b, b|a) - self.assertEqual(a^b, b^a) - if a != b: - self.assertNotEqual(a-b, b-a) - - def test_reflexsive_relations(self): - a, zero = self.a, Set() - self.assertEqual(a ^ a, zero) - self.assertEqual(a - a, zero) - self.assertEqual(a | a, a) - self.assertEqual(a & a, a) - self.assert_(a <= a) - self.assert_(a >= a) - self.assert_(a == a) - - def test_summations(self): - # check that sums of parts equal the whole - a, b = self.a, self.b - self.assertEqual((a-b)|(a&b)|(b-a), a|b) - self.assertEqual((a&b)|(a^b), a|b) - self.assertEqual(a|(b-a), a|b) - self.assertEqual((a-b)|b, a|b) - self.assertEqual((a-b)|(a&b), a) - self.assertEqual((b-a)|(a&b), b) - self.assertEqual((a-b)|(b-a), a^b) - - def test_exclusion(self): - # check that inverse operations do not overlap - a, b, zero = self.a, self.b, Set() - self.assertEqual((a-b)&b, zero) - self.assertEqual((b-a)&a, zero) - self.assertEqual((a&b)&(a^b), zero) - - def test_cardinality_relations(self): - a, b = self.a, self.b - self.assertEqual(len(a), len(a-b) + len(a&b)) - self.assertEqual(len(b), len(b-a) + len(a&b)) - self.assertEqual(len(a^b), len(a-b) + len(b-a)) - self.assertEqual(len(a|b), len(a-b) + len(a&b) + len(b-a)) - self.assertEqual(len(a^b) + len(a&b), len(a|b)) - -#============================================================================== - -libreftest = """ -Example from the Library Reference: Doc/lib/libsets.tex - ->>> from sets import Set as Base # override _repr to get sorted output ->>> class Set(Base): -... def _repr(self): -... return Base._repr(self, sorted=True) ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) ->>> employees = engineers | programmers | managers # union ->>> engineering_management = engineers & managers # intersection ->>> fulltime_management = managers - engineers - programmers # difference ->>> engineers.add('Marvin') ->>> print engineers -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) ->>> employees.issuperset(engineers) # superset test -False ->>> employees.union_update(engineers) # update from another set ->>> employees.issuperset(engineers) -True ->>> for group in [engineers, programmers, managers, employees]: -... group.discard('Susan') # unconditionally remove element -... print group -... -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) -Set(['Jack', 'Janice', 'Sam']) -Set(['Jack', 'Jane', 'Zack']) -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin', 'Sam', 'Zack']) -""" - -#============================================================================== - -__test__ = {'libreftest' : libreftest} - -def test_main(verbose=None): - import doctest - from test import test_sets - test_support.run_unittest( - TestSetOfSets, - TestExceptionPropagation, - TestBasicOpsEmpty, - TestBasicOpsSingleton, - TestBasicOpsTuple, - TestBasicOpsTriple, - TestBinaryOps, - TestUpdateOps, - TestMutate, - TestSubsetEqualEmpty, - TestSubsetEqualNonEmpty, - TestSubsetEmptyNonEmpty, - TestSubsetPartial, - TestSubsetNonOverlap, - TestOnlySetsNumeric, - TestOnlySetsDict, - TestOnlySetsOperator, - TestOnlySetsTuple, - TestOnlySetsString, - TestOnlySetsGenerator, - TestOnlySetsofSets, - TestCopyingEmpty, - TestCopyingSingleton, - TestCopyingTriple, - TestCopyingTuple, - TestCopyingNested, - TestIdentities, - doctest.DocTestSuite(test_sets), - ) - -if __name__ == "__main__": - test_main(verbose=True) From python-3000-checkins at python.org Wed Jan 10 02:29:06 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 02:29:06 +0100 (CET) Subject: [Python-3000-checkins] r53336 - python/branches/p3yk/Misc/NEWS Message-ID: <20070110012906.802181E4008@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 02:29:06 2007 New Revision: 53336 Modified: python/branches/p3yk/Misc/NEWS Log: News about removal of the sets module. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Wed Jan 10 02:29:06 2007 @@ -105,6 +105,8 @@ Library ------- +- Removed all traces of the sets module. + Build ----- From brett at python.org Wed Jan 10 04:39:23 2007 From: brett at python.org (Brett Cannon) Date: Tue, 9 Jan 2007 19:39:23 -0800 Subject: [Python-3000-checkins] r53335 - in python/branches/p3yk: Doc/Makefile.deps Doc/lib/lib.tex Doc/lib/libsets.tex Doc/lib/libstdtypes.tex Lib/msilib/__init__.py Lib/sets.py Lib/test/test_cookielib.py Lib/test/test_set.py Lib/test/test_sets.py In-Reply-To: <20070110012835.B33831E4008@bag.python.org> References: <20070110012835.B33831E4008@bag.python.org> Message-ID: Should we bother with deprecating 'sets' in the 2.x series? -Brett On 1/9/07, guido.van.rossum wrote: > Author: guido.van.rossum > Date: Wed Jan 10 02:28:32 2007 > New Revision: 53335 > > Removed: > python/branches/p3yk/Lib/sets.py > python/branches/p3yk/Lib/test/test_sets.py > Modified: > python/branches/p3yk/Doc/Makefile.deps > python/branches/p3yk/Doc/lib/lib.tex > python/branches/p3yk/Doc/lib/libsets.tex > python/branches/p3yk/Doc/lib/libstdtypes.tex > python/branches/p3yk/Lib/msilib/__init__.py > python/branches/p3yk/Lib/test/test_cookielib.py > python/branches/p3yk/Lib/test/test_set.py > Log: > Excise the sets module. SF #1500611 by Collin Winter. > > > Modified: python/branches/p3yk/Doc/Makefile.deps > ============================================================================== > --- python/branches/p3yk/Doc/Makefile.deps (original) > +++ python/branches/p3yk/Doc/Makefile.deps Wed Jan 10 02:28:32 2007 > @@ -109,7 +109,6 @@ > lib/libplatform.tex \ > lib/libfpectl.tex \ > lib/libgc.tex \ > - lib/libsets.tex \ > lib/libweakref.tex \ > lib/libinspect.tex \ > lib/libpydoc.tex \ > > Modified: python/branches/p3yk/Doc/lib/lib.tex > ============================================================================== > --- python/branches/p3yk/Doc/lib/lib.tex (original) > +++ python/branches/p3yk/Doc/lib/lib.tex Wed Jan 10 02:28:32 2007 > @@ -104,7 +104,6 @@ > \input{libheapq} > \input{libbisect} > \input{libarray} > -\input{libsets} > \input{libsched} > \input{libmutex} > \input{libqueue} > > Modified: python/branches/p3yk/Doc/lib/libsets.tex > ============================================================================== > --- python/branches/p3yk/Doc/lib/libsets.tex (original) > +++ python/branches/p3yk/Doc/lib/libsets.tex Wed Jan 10 02:28:32 2007 > @@ -1,264 +0,0 @@ > -\section{\module{sets} --- > - Unordered collections of unique elements} > - > -\declaremodule{standard}{sets} > -\modulesynopsis{Implementation of sets of unique elements.} > -\moduleauthor{Greg V. Wilson}{gvwilson at nevex.com} > -\moduleauthor{Alex Martelli}{aleax at aleax.it} > -\moduleauthor{Guido van Rossum}{guido at python.org} > -\sectionauthor{Raymond D. Hettinger}{python at rcn.com} > - > -\versionadded{2.3} > - > -The \module{sets} module provides classes for constructing and manipulating > -unordered collections of unique elements. Common uses include membership > -testing, removing duplicates from a sequence, and computing standard math > -operations on sets such as intersection, union, difference, and symmetric > -difference. > - > -Like other collections, sets support \code{\var{x} in \var{set}}, > -\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an > -unordered collection, sets do not record element position or order of > -insertion. Accordingly, sets do not support indexing, slicing, or > -other sequence-like behavior. > - > -Most set applications use the \class{Set} class which provides every set > -method except for \method{__hash__()}. For advanced applications requiring > -a hash method, the \class{ImmutableSet} class adds a \method{__hash__()} > -method but omits methods which alter the contents of the set. Both > -\class{Set} and \class{ImmutableSet} derive from \class{BaseSet}, an > -abstract class useful for determining whether something is a set: > -\code{isinstance(\var{obj}, BaseSet)}. > - > -The set classes are implemented using dictionaries. Accordingly, the > -requirements for set elements are the same as those for dictionary keys; > -namely, that the element defines both \method{__eq__} and \method{__hash__}. > -As a result, sets > -cannot contain mutable elements such as lists or dictionaries. > -However, they can contain immutable collections such as tuples or > -instances of \class{ImmutableSet}. For convenience in implementing > -sets of sets, inner sets are automatically converted to immutable > -form, for example, \code{Set([Set(['dog'])])} is transformed to > -\code{Set([ImmutableSet(['dog'])])}. > - > -\begin{classdesc}{Set}{\optional{iterable}} > -Constructs a new empty \class{Set} object. If the optional \var{iterable} > -parameter is supplied, updates the set with elements obtained from iteration. > -All of the elements in \var{iterable} should be immutable or be transformable > -to an immutable using the protocol described in > -section~\ref{immutable-transforms}. > -\end{classdesc} > - > -\begin{classdesc}{ImmutableSet}{\optional{iterable}} > -Constructs a new empty \class{ImmutableSet} object. If the optional > -\var{iterable} parameter is supplied, updates the set with elements obtained > -from iteration. All of the elements in \var{iterable} should be immutable or > -be transformable to an immutable using the protocol described in > -section~\ref{immutable-transforms}. > - > -Because \class{ImmutableSet} objects provide a \method{__hash__()} method, > -they can be used as set elements or as dictionary keys. \class{ImmutableSet} > -objects do not have methods for adding or removing elements, so all of the > -elements must be known when the constructor is called. > -\end{classdesc} > - > - > -\subsection{Set Objects \label{set-objects}} > - > -Instances of \class{Set} and \class{ImmutableSet} both provide > -the following operations: > - > -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} > - \lineiii{len(\var{s})}{}{cardinality of set \var{s}} > - > - \hline > - \lineiii{\var{x} in \var{s}}{} > - {test \var{x} for membership in \var{s}} > - \lineiii{\var{x} not in \var{s}}{} > - {test \var{x} for non-membership in \var{s}} > - \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}} > - {test whether every element in \var{s} is in \var{t}} > - \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}} > - {test whether every element in \var{t} is in \var{s}} > - > - \hline > - \lineiii{\var{s}.union(\var{t})}{\var{s} \textbar{} \var{t}} > - {new set with elements from both \var{s} and \var{t}} > - \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}} > - {new set with elements common to \var{s} and \var{t}} > - \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}} > - {new set with elements in \var{s} but not in \var{t}} > - \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}} > - {new set with elements in either \var{s} or \var{t} but not both} > - \lineiii{\var{s}.copy()}{} > - {new set with a shallow copy of \var{s}} > -\end{tableiii} > - > -Note, the non-operator versions of \method{union()}, > -\method{intersection()}, \method{difference()}, and > -\method{symmetric_difference()} will accept any iterable as an argument. > -In contrast, their operator based counterparts require their arguments to > -be sets. This precludes error-prone constructions like > -\code{Set('abc') \&\ 'cbs'} in favor of the more readable > -\code{Set('abc').intersection('cbs')}. > -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} > - > -In addition, both \class{Set} and \class{ImmutableSet} > -support set to set comparisons. Two sets are equal if and only if > -every element of each set is contained in the other (each is a subset > -of the other). > -A set is less than another set if and only if the first set is a proper > -subset of the second set (is a subset, but is not equal). > -A set is greater than another set if and only if the first set is a proper > -superset of the second set (is a superset, but is not equal). > - > -The subset and equality comparisons do not generalize to a complete > -ordering function. For example, any two disjoint sets are not equal and > -are not subsets of each other, so \emph{all} of the following return > -\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or > -\code{\var{a}>\var{b}}. > -Accordingly, sets do not implement the \method{__cmp__} method. > - > -Since sets only define partial ordering (subset relationships), the output > -of the \method{list.sort()} method is undefined for lists of sets. > - > -The following table lists operations available in \class{ImmutableSet} > -but not found in \class{Set}: > - > -\begin{tableii}{c|l}{code}{Operation}{Result} > - \lineii{hash(\var{s})}{returns a hash value for \var{s}} > -\end{tableii} > - > -The following table lists operations available in \class{Set} > -but not found in \class{ImmutableSet}: > - > -\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result} > - \lineiii{\var{s}.update(\var{t})} > - {\var{s} \textbar= \var{t}} > - {return set \var{s} with elements added from \var{t}} > - \lineiii{\var{s}.intersection_update(\var{t})} > - {\var{s} \&= \var{t}} > - {return set \var{s} keeping only elements also found in \var{t}} > - \lineiii{\var{s}.difference_update(\var{t})} > - {\var{s} -= \var{t}} > - {return set \var{s} after removing elements found in \var{t}} > - \lineiii{\var{s}.symmetric_difference_update(\var{t})} > - {\var{s} \textasciicircum= \var{t}} > - {return set \var{s} with elements from \var{s} or \var{t} > - but not both} > - > - \hline > - \lineiii{\var{s}.add(\var{x})}{} > - {add element \var{x} to set \var{s}} > - \lineiii{\var{s}.remove(\var{x})}{} > - {remove \var{x} from set \var{s}; raises \exception{KeyError} > - if not present} > - \lineiii{\var{s}.discard(\var{x})}{} > - {removes \var{x} from set \var{s} if present} > - \lineiii{\var{s}.pop()}{} > - {remove and return an arbitrary element from \var{s}; raises > - \exception{KeyError} if empty} > - \lineiii{\var{s}.clear()}{} > - {remove all elements from set \var{s}} > -\end{tableiii} > - > -Note, the non-operator versions of \method{update()}, > -\method{intersection_update()}, \method{difference_update()}, and > -\method{symmetric_difference_update()} will accept any iterable as > -an argument. > -\versionchanged[Formerly all arguments were required to be sets]{2.3.1} > - > -Also note, the module also includes a \method{union_update()} method > -which is an alias for \method{update()}. The method is included for > -backwards compatibility. Programmers should prefer the > -\method{update()} method because it is supported by the builtin > -\class{set()} and \class{frozenset()} types. > - > -\subsection{Example \label{set-example}} > - > -\begin{verbatim} > ->>> from sets import Set > ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) > ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) > ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) > ->>> employees = engineers | programmers | managers # union > ->>> engineering_management = engineers & managers # intersection > ->>> fulltime_management = managers - engineers - programmers # difference > ->>> engineers.add('Marvin') # add element > ->>> print engineers > -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) > ->>> employees.issuperset(engineers) # superset test > -False > ->>> employees.union_update(engineers) # update from another set > ->>> employees.issuperset(engineers) > -True > ->>> for group in [engineers, programmers, managers, employees]: > -... group.discard('Susan') # unconditionally remove element > -... print group > -... > -Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) > -Set(['Janice', 'Jack', 'Sam']) > -Set(['Jane', 'Zack', 'Jack']) > -Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack']) > -\end{verbatim} > - > - > -\subsection{Protocol for automatic conversion to immutable > - \label{immutable-transforms}} > - > -Sets can only contain immutable elements. For convenience, mutable > -\class{Set} objects are automatically copied to an \class{ImmutableSet} > -before being added as a set element. > - > -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. > - > -A similar mechanism is needed by the \method{__contains__()} and > -\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__()}. > - > -The alternate mechanism spares the need to build a separate copy of > -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}. > - > -The two mechanisms for adding hashability are normally invisible to the > -user; however, a conflict can arise in a multi-threaded environment > -where one thread is updating a set while another has temporarily wrapped it > -in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets > -are not thread-safe. > - > - > -\subsection{Comparison to the built-in \class{set} types > - \label{comparison-to-builtin-set}} > - > -The built-in \class{set} and \class{frozenset} types were designed based > -on lessons learned from the \module{sets} module. The key differences are: > - > -\begin{itemize} > -\item \class{Set} and \class{ImmutableSet} were renamed to \class{set} and > - \class{frozenset}. > -\item There is no equivalent to \class{BaseSet}. Instead, use > - \code{isinstance(x, (set, frozenset))}. > -\item The hash algorithm for the built-ins performs significantly better > - (fewer collisions) for most datasets. > -\item The built-in versions have more space efficient pickles. > -\item The built-in versions do not have a \method{union_update()} method. > - Instead, use the \method{update()} method which is equivalent. > -\item The built-in versions do not have a \method{_repr(sorted=True)} method. > - Instead, use the built-in \function{repr()} and \function{sorted()} > - functions: \code{repr(sorted(s))}. > -\item The built-in version does not have a protocol for automatic conversion > - to immutable. Many found this feature to be confusing and no one > - in the community reported having found real uses for it. > -\end{itemize} > > Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex > ============================================================================== > --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) > +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Wed Jan 10 02:28:32 2007 > @@ -1334,16 +1334,6 @@ > \method{intersection_update()}, \method{difference_update()}, and > \method{symmetric_difference_update()} methods will accept any iterable > as an argument. > - > -The design of the set types was based on lessons learned from the > -\module{sets} module. > - > -\begin{seealso} > - \seelink{comparison-to-builtin-set.html} > - {Comparison to the built-in set types} > - {Differences between the \module{sets} module and the > - built-in set types.} > -\end{seealso} > > > \section{Mapping Types --- \class{dict} \label{typesmapping}} > > Modified: python/branches/p3yk/Lib/msilib/__init__.py > ============================================================================== > --- python/branches/p3yk/Lib/msilib/__init__.py (original) > +++ python/branches/p3yk/Lib/msilib/__init__.py Wed Jan 10 02:28:32 2007 > @@ -2,7 +2,7 @@ > # Copyright (C) 2005 Martin v. L?wis > # Licensed to PSF under a Contributor Agreement. > from _msi import * > -import sets, os, string, re > +import os, string, re > > Win64=0 > > @@ -184,7 +184,7 @@ > def __init__(self, name): > self.name = name > self.files = [] > - self.filenames = sets.Set() > + self.filenames = set() > self.index = 0 > > def gen_id(self, file): > @@ -215,7 +215,7 @@ > os.unlink(filename) > db.Commit() > > -_directories = sets.Set() > +_directories = set() > class Directory: > def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None): > """Create a new directory in the Directory table. There is a current component > @@ -239,8 +239,8 @@ > self.physical = physical > self.logical = logical > self.component = None > - self.short_names = sets.Set() > - self.ids = sets.Set() > + self.short_names = set() > + self.ids = set() > self.keyfiles = {} > self.componentflags = componentflags > if basedir: > > Deleted: /python/branches/p3yk/Lib/sets.py > ============================================================================== > --- /python/branches/p3yk/Lib/sets.py Wed Jan 10 02:28:32 2007 > +++ (empty file) > @@ -1,577 +0,0 @@ > -"""Classes to represent arbitrary sets (including sets of sets). > - > -This module implements sets using dictionaries whose values are > -ignored. The usual operations (union, intersection, deletion, etc.) > -are provided as both methods and operators. > - > -Important: sets are not sequences! While they support 'x in s', > -'len(s)', and 'for x in s', none of those operations are unique for > -sequences; for example, mappings support all three as well. The > -characteristic operation for sequences is subscripting with small > -integers: s[i], for i in range(len(s)). Sets don't support > -subscripting at all. Also, sequences allow multiple occurrences and > -their elements have a definite order; sets on the other hand don't > -record multiple occurrences and don't remember the order of element > -insertion (which is why they don't support s[i]). > - > -The following classes are provided: > - > -BaseSet -- All the operations common to both mutable and immutable > - sets. This is an abstract class, not meant to be directly > - instantiated. > - > -Set -- Mutable sets, subclass of BaseSet; not hashable. > - > -ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. > - An iterable argument is mandatory to create an ImmutableSet. > - > -_TemporarilyImmutableSet -- A wrapper around a Set, hashable, > - giving the same hash value as the immutable set equivalent > - would have. Do not use this class directly. > - > -Only hashable objects can be added to a Set. In particular, you cannot > -really add a Set as an element to another Set; if you try, what is > -actually added is an ImmutableSet built from it (it compares equal to > -the one you tried adding). > - > -When you ask if `x in y' where x is a Set and y is a Set or > -ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and > -what's tested is actually `z in y'. > - > -""" > - > -# Code history: > -# > -# - Greg V. Wilson wrote the first version, using a different approach > -# to the mutable/immutable problem, and inheriting from dict. > -# > -# - Alex Martelli modified Greg's version to implement the current > -# Set/ImmutableSet approach, and make the data an attribute. > -# > -# - Guido van Rossum rewrote much of the code, made some API changes, > -# and cleaned up the docstrings. > -# > -# - Raymond Hettinger added a number of speedups and other > -# improvements. > - > -from __future__ import generators > -try: > - from itertools import ifilter, ifilterfalse > -except ImportError: > - # Code to make the module run under Py2.2 > - def ifilter(predicate, iterable): > - if predicate is None: > - def predicate(x): > - return x > - for x in iterable: > - if predicate(x): > - yield x > - def ifilterfalse(predicate, iterable): > - if predicate is None: > - def predicate(x): > - return x > - for x in iterable: > - if not predicate(x): > - yield x > - try: > - True, False > - except NameError: > - True, False = (0==0, 0!=0) > - > -__all__ = ['BaseSet', 'Set', 'ImmutableSet'] > - > -class BaseSet(object): > - """Common base class for mutable and immutable sets.""" > - > - __slots__ = ['_data'] > - > - # Constructor > - > - def __init__(self): > - """This is an abstract class.""" > - # Don't call this from a concrete subclass! > - if self.__class__ is BaseSet: > - raise TypeError, ("BaseSet is an abstract class. " > - "Use Set or ImmutableSet.") > - > - # Standard protocols: __len__, __repr__, __str__, __iter__ > - > - def __len__(self): > - """Return the number of elements of a set.""" > - return len(self._data) > - > - def __repr__(self): > - """Return string representation of a set. > - > - This looks like 'Set([])'. > - """ > - return self._repr() > - > - # __str__ is the same as __repr__ > - __str__ = __repr__ > - > - def _repr(self, sorted=False): > - elements = self._data.keys() > - if sorted: > - elements.sort() > - return '%s(%r)' % (self.__class__.__name__, elements) > - > - def __iter__(self): > - """Return an iterator over the elements or a set. > - > - This is the keys iterator for the underlying dict. > - """ > - return self._data.iterkeys() > - > - # Three-way comparison is not supported. However, because __eq__ is > - # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and > - # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this > - # case). > - > - def __cmp__(self, other): > - raise TypeError, "can't compare sets using cmp()" > - > - # Equality comparisons using the underlying dicts. Mixed-type comparisons > - # are allowed here, where Set == z for non-Set z always returns False, > - # and Set != z always True. This allows expressions like "x in y" to > - # give the expected result when y is a sequence of mixed types, not > - # raising a pointless TypeError just because y contains a Set, or x is > - # a Set and y contain's a non-set ("in" invokes only __eq__). > - # Subtle: it would be nicer if __eq__ and __ne__ could return > - # NotImplemented instead of True or False. Then the other comparand > - # would get a chance to determine the result, and if the other comparand > - # also returned NotImplemented then it would fall back to object address > - # comparison (which would always return False for __eq__ and always > - # True for __ne__). However, that doesn't work, because this type > - # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, > - # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. > - > - def __eq__(self, other): > - if isinstance(other, BaseSet): > - return self._data == other._data > - else: > - return False > - > - def __ne__(self, other): > - if isinstance(other, BaseSet): > - return self._data != other._data > - else: > - return True > - > - # Copying operations > - > - def copy(self): > - """Return a shallow copy of a set.""" > - result = self.__class__() > - result._data.update(self._data) > - return result > - > - __copy__ = copy # For the copy module > - > - def __deepcopy__(self, memo): > - """Return a deep copy of a set; used by copy module.""" > - # This pre-creates the result and inserts it in the memo > - # early, in case the deep copy recurses into another reference > - # to this same set. A set can't be an element of itself, but > - # it can certainly contain an object that has a reference to > - # itself. > - from copy import deepcopy > - result = self.__class__() > - memo[id(self)] = result > - data = result._data > - value = True > - for elt in self: > - data[deepcopy(elt, memo)] = value > - return result > - > - # Standard set operations: union, intersection, both differences. > - # Each has an operator version (e.g. __or__, invoked with |) and a > - # method version (e.g. union). > - # Subtle: Each pair requires distinct code so that the outcome is > - # correct when the type of other isn't suitable. For example, if > - # we did "union = __or__" instead, then Set().union(3) would return > - # NotImplemented instead of raising TypeError (albeit that *why* it > - # raises TypeError as-is is also a bit subtle). > - > - def __or__(self, other): > - """Return the union of two sets as a new set. > - > - (I.e. all elements that are in either set.) > - """ > - if not isinstance(other, BaseSet): > - return NotImplemented > - return self.union(other) > - > - def union(self, other): > - """Return the union of two sets as a new set. > - > - (I.e. all elements that are in either set.) > - """ > - result = self.__class__(self) > - result._update(other) > - return result > - > - def __and__(self, other): > - """Return the intersection of two sets as a new set. > - > - (I.e. all elements that are in both sets.) > - """ > - if not isinstance(other, BaseSet): > - return NotImplemented > - return self.intersection(other) > - > - def intersection(self, other): > - """Return the intersection of two sets as a new set. > - > - (I.e. all elements that are in both sets.) > - """ > - if not isinstance(other, BaseSet): > - other = Set(other) > - if len(self) <= len(other): > - little, big = self, other > - else: > - little, big = other, self > - common = ifilter(big._data.__contains__, little) > - return self.__class__(common) > - > - def __xor__(self, other): > - """Return the symmetric difference of two sets as a new set. > - > - (I.e. all elements that are in exactly one of the sets.) > - """ > - if not isinstance(other, BaseSet): > - return NotImplemented > - return self.symmetric_difference(other) > - > - def symmetric_difference(self, other): > - """Return the symmetric difference of two sets as a new set. > - > - (I.e. all elements that are in exactly one of the sets.) > - """ > - result = self.__class__() > - data = result._data > - value = True > - selfdata = self._data > - try: > - otherdata = other._data > - except AttributeError: > - otherdata = Set(other)._data > - for elt in ifilterfalse(otherdata.__contains__, selfdata): > - data[elt] = value > - for elt in ifilterfalse(selfdata.__contains__, otherdata): > - data[elt] = value > - return result > - > - def __sub__(self, other): > - """Return the difference of two sets as a new Set. > - > - (I.e. all elements that are in this set and not in the other.) > - """ > - if not isinstance(other, BaseSet): > - return NotImplemented > - return self.difference(other) > - > - def difference(self, other): > - """Return the difference of two sets as a new Set. > - > - (I.e. all elements that are in this set and not in the other.) > - """ > - result = self.__class__() > - data = result._data > - try: > - otherdata = other._data > - except AttributeError: > - otherdata = Set(other)._data > - value = True > - for elt in ifilterfalse(otherdata.__contains__, self): > - data[elt] = value > - return result > - > - # Membership test > - > - def __contains__(self, element): > - """Report whether an element is a member of a set. > - > - (Called in response to the expression `element in self'.) > - """ > - try: > - 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 > - return transform() in self._data > - > - # Subset and superset test > - > - def issubset(self, other): > - """Report whether another set contains this set.""" > - self._binary_sanity_check(other) > - if len(self) > len(other): # Fast check for obvious cases > - return False > - for elt in ifilterfalse(other._data.__contains__, self): > - return False > - return True > - > - def issuperset(self, other): > - """Report whether this set contains another set.""" > - self._binary_sanity_check(other) > - if len(self) < len(other): # Fast check for obvious cases > - return False > - for elt in ifilterfalse(self._data.__contains__, other): > - return False > - return True > - > - # Inequality comparisons using the is-subset relation. > - __le__ = issubset > - __ge__ = issuperset > - > - def __lt__(self, other): > - self._binary_sanity_check(other) > - return len(self) < len(other) and self.issubset(other) > - > - def __gt__(self, other): > - self._binary_sanity_check(other) > - return len(self) > len(other) and self.issuperset(other) > - > - # Assorted helpers > - > - def _binary_sanity_check(self, other): > - # Check that the other argument to a binary operation is also > - # a set, raising a TypeError otherwise. > - if not isinstance(other, BaseSet): > - raise TypeError, "Binary operation only permitted between sets" > - > - def _compute_hash(self): > - # Calculate hash code for a set by xor'ing the hash codes of > - # the elements. This ensures that the hash code does not depend > - # on the order in which elements are added to the set. This is > - # not called __hash__ because a BaseSet should not be hashable; > - # only an ImmutableSet is hashable. > - result = 0 > - for elt in self: > - result ^= hash(elt) > - return result > - > - def _update(self, iterable): > - # The main loop for update() and the subclass __init__() methods. > - data = self._data > - > - # Use the fast update() method when a dictionary is available. > - if isinstance(iterable, BaseSet): > - data.update(iterable._data) > - return > - > - value = True > - > - if type(iterable) in (list, tuple, xrange): > - # Optimized: we know that __iter__() and next() can't > - # raise TypeError, so we can move 'try:' out of the loop. > - it = iter(iterable) > - while True: > - try: > - for element in it: > - data[element] = value > - return > - except TypeError: > - transform = getattr(element, "__as_immutable__", None) > - if transform is None: > - raise # re-raise the TypeError exception we caught > - data[transform()] = value > - else: > - # Safe: only catch TypeError where intended > - for element in iterable: > - try: > - data[element] = value > - except TypeError: > - transform = getattr(element, "__as_immutable__", None) > - if transform is None: > - raise # re-raise the TypeError exception we caught > - data[transform()] = value > - > - > -class ImmutableSet(BaseSet): > - """Immutable set class.""" > - > - __slots__ = ['_hashcode'] > - > - # BaseSet + hashing > - > - def __init__(self, iterable=None): > - """Construct an immutable set from an optional iterable.""" > - self._hashcode = None > - self._data = {} > - if iterable is not None: > - self._update(iterable) > - > - def __hash__(self): > - if self._hashcode is None: > - self._hashcode = self._compute_hash() > - return self._hashcode > - > - def __getstate__(self): > - return self._data, self._hashcode > - > - def __setstate__(self, state): > - self._data, self._hashcode = state > - > -class Set(BaseSet): > - """ Mutable set class.""" > - > - __slots__ = [] > - > - # BaseSet + operations requiring mutability; no hashing > - > - def __init__(self, iterable=None): > - """Construct a set from an optional iterable.""" > - self._data = {} > - if iterable is not None: > - self._update(iterable) > - > - def __getstate__(self): > - # getstate's results are ignored if it is not > - return self._data, > - > - def __setstate__(self, data): > - self._data, = data > - > - def __hash__(self): > - """A Set cannot be hashed.""" > - # We inherit object.__hash__, so we must deny this explicitly > - raise TypeError, "Can't hash a Set, only an ImmutableSet." > - > - # In-place union, intersection, differences. > - # Subtle: The xyz_update() functions deliberately return None, > - # as do all mutating operations on built-in container types. > - # The __xyz__ spellings have to return self, though. > - > - def __ior__(self, other): > - """Update a set with the union of itself and another.""" > - self._binary_sanity_check(other) > - self._data.update(other._data) > - return self > - > - def union_update(self, other): > - """Update a set with the union of itself and another.""" > - self._update(other) > - > - def __iand__(self, other): > - """Update a set with the intersection of itself and another.""" > - self._binary_sanity_check(other) > - self._data = (self & other)._data > - return self > - > - def intersection_update(self, other): > - """Update a set with the intersection of itself and another.""" > - if isinstance(other, BaseSet): > - self &= other > - else: > - self._data = (self.intersection(other))._data > - > - def __ixor__(self, other): > - """Update a set with the symmetric difference of itself and another.""" > - self._binary_sanity_check(other) > - self.symmetric_difference_update(other) > - return self > - > - def symmetric_difference_update(self, other): > - """Update a set with the symmetric difference of itself and another.""" > - data = self._data > - value = True > - if not isinstance(other, BaseSet): > - other = Set(other) > - if self is other: > - self.clear() > - for elt in other: > - if elt in data: > - del data[elt] > - else: > - data[elt] = value > - > - def __isub__(self, other): > - """Remove all elements of another set from this set.""" > - self._binary_sanity_check(other) > - self.difference_update(other) > - return self > - > - def difference_update(self, other): > - """Remove all elements of another set from this set.""" > - data = self._data > - if not isinstance(other, BaseSet): > - other = Set(other) > - if self is other: > - self.clear() > - for elt in ifilter(data.__contains__, other): > - del data[elt] > - > - # Python dict-like mass mutations: update, clear > - > - def update(self, iterable): > - """Add all values from an iterable (such as a list or file).""" > - self._update(iterable) > - > - def clear(self): > - """Remove all elements from this set.""" > - self._data.clear() > - > - # Single-element mutations: add, remove, discard > - > - def add(self, element): > - """Add an element to a set. > - > - This has no effect if the element is already present. > - """ > - try: > - self._data[element] = True > - except TypeError: > - transform = getattr(element, "__as_immutable__", None) > - if transform is None: > - raise # re-raise the TypeError exception we caught > - self._data[transform()] = True > - > - def remove(self, element): > - """Remove an element from a set; it must be a member. > - > - If the element is not a member, raise a KeyError. > - """ > - try: > - 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 > - del self._data[transform()] > - > - def discard(self, element): > - """Remove an element from a set if it is a member. > - > - If the element is not a member, do nothing. > - """ > - try: > - self.remove(element) > - except KeyError: > - pass > - > - def pop(self): > - """Remove and return an arbitrary set element.""" > - 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) > - > - > -class _TemporarilyImmutableSet(BaseSet): > - # Wrap a mutable set as if it was temporarily immutable. > - # This only supplies hashing and equality comparisons. > - > - def __init__(self, set): > - self._set = set > - self._data = set._data # Needed by ImmutableSet.__eq__() > - > - def __hash__(self): > - return self._set._compute_hash() > > Modified: python/branches/p3yk/Lib/test/test_cookielib.py > ============================================================================== > --- python/branches/p3yk/Lib/test/test_cookielib.py (original) > +++ python/branches/p3yk/Lib/test/test_cookielib.py Wed Jan 10 02:28:32 2007 > @@ -1723,7 +1723,6 @@ > > > def test_main(verbose=None): > - from test import test_sets > test_support.run_unittest( > DateTimeTests, > HeaderTests, > > Modified: python/branches/p3yk/Lib/test/test_set.py > ============================================================================== > --- python/branches/p3yk/Lib/test/test_set.py (original) > +++ python/branches/p3yk/Lib/test/test_set.py Wed Jan 10 02:28:32 2007 > @@ -1451,7 +1451,6 @@ > #============================================================================== > > def test_main(verbose=None): > - from test import test_sets > test_classes = ( > TestSet, > TestSetSubclass, > > Deleted: /python/branches/p3yk/Lib/test/test_sets.py > ============================================================================== > --- /python/branches/p3yk/Lib/test/test_sets.py Wed Jan 10 02:28:32 2007 > +++ (empty file) > @@ -1,853 +0,0 @@ > -#!/usr/bin/env python > - > -import unittest, operator, copy, pickle, random > -from sets import Set, ImmutableSet > -from test import test_support > - > -empty_set = Set() > - > -#============================================================================== > - > -class TestBasicOps(unittest.TestCase): > - > - def test_repr(self): > - if self.repr is not None: > - self.assertEqual(repr(self.set), self.repr) > - > - def test_length(self): > - self.assertEqual(len(self.set), self.length) > - > - def test_self_equality(self): > - self.assertEqual(self.set, self.set) > - > - def test_equivalent_equality(self): > - self.assertEqual(self.set, self.dup) > - > - def test_copy(self): > - self.assertEqual(self.set.copy(), self.dup) > - > - def test_self_union(self): > - result = self.set | self.set > - self.assertEqual(result, self.dup) > - > - def test_empty_union(self): > - result = self.set | empty_set > - self.assertEqual(result, self.dup) > - > - def test_union_empty(self): > - result = empty_set | self.set > - self.assertEqual(result, self.dup) > - > - def test_self_intersection(self): > - result = self.set & self.set > - self.assertEqual(result, self.dup) > - > - def test_empty_intersection(self): > - result = self.set & empty_set > - self.assertEqual(result, empty_set) > - > - def test_intersection_empty(self): > - result = empty_set & self.set > - self.assertEqual(result, empty_set) > - > - def test_self_symmetric_difference(self): > - result = self.set ^ self.set > - self.assertEqual(result, empty_set) > - > - def checkempty_symmetric_difference(self): > - result = self.set ^ empty_set > - self.assertEqual(result, self.set) > - > - def test_self_difference(self): > - result = self.set - self.set > - self.assertEqual(result, empty_set) > - > - def test_empty_difference(self): > - result = self.set - empty_set > - self.assertEqual(result, self.dup) > - > - def test_empty_difference_rev(self): > - result = empty_set - self.set > - self.assertEqual(result, empty_set) > - > - def test_iteration(self): > - for v in self.set: > - self.assert_(v in self.values) > - > - def test_pickling(self): > - p = pickle.dumps(self.set) > - copy = pickle.loads(p) > - self.assertEqual(self.set, copy, > - "%s != %s" % (self.set, copy)) > - > -#------------------------------------------------------------------------------ > - > -class TestBasicOpsEmpty(TestBasicOps): > - def setUp(self): > - self.case = "empty set" > - self.values = [] > - self.set = Set(self.values) > - self.dup = Set(self.values) > - self.length = 0 > - self.repr = "Set([])" > - > -#------------------------------------------------------------------------------ > - > -class TestBasicOpsSingleton(TestBasicOps): > - def setUp(self): > - self.case = "unit set (number)" > - self.values = [3] > - self.set = Set(self.values) > - self.dup = Set(self.values) > - self.length = 1 > - self.repr = "Set([3])" > - > - def test_in(self): > - self.failUnless(3 in self.set) > - > - def test_not_in(self): > - self.failUnless(2 not in self.set) > - > -#------------------------------------------------------------------------------ > - > -class TestBasicOpsTuple(TestBasicOps): > - def setUp(self): > - self.case = "unit set (tuple)" > - self.values = [(0, "zero")] > - self.set = Set(self.values) > - self.dup = Set(self.values) > - self.length = 1 > - self.repr = "Set([(0, 'zero')])" > - > - def test_in(self): > - self.failUnless((0, "zero") in self.set) > - > - def test_not_in(self): > - self.failUnless(9 not in self.set) > - > -#------------------------------------------------------------------------------ > - > -class TestBasicOpsTriple(TestBasicOps): > - def setUp(self): > - self.case = "triple set" > - self.values = [0, "zero", operator.add] > - self.set = Set(self.values) > - self.dup = Set(self.values) > - self.length = 3 > - self.repr = None > - > -#============================================================================== > - > -def baditer(): > - raise TypeError > - yield True > - > -def gooditer(): > - yield True > - > -class TestExceptionPropagation(unittest.TestCase): > - """SF 628246: Set constructor should not trap iterator TypeErrors""" > - > - def test_instanceWithException(self): > - self.assertRaises(TypeError, Set, baditer()) > - > - def test_instancesWithoutException(self): > - # All of these iterables should load without exception. > - Set([1,2,3]) > - Set((1,2,3)) > - Set({'one':1, 'two':2, 'three':3}) > - Set(xrange(3)) > - Set('abc') > - Set(gooditer()) > - > -#============================================================================== > - > -class TestSetOfSets(unittest.TestCase): > - def test_constructor(self): > - inner = Set([1]) > - outer = Set([inner]) > - element = outer.pop() > - self.assertEqual(type(element), ImmutableSet) > - outer.add(inner) # Rebuild set of sets with .add method > - outer.remove(inner) > - self.assertEqual(outer, Set()) # Verify that remove worked > - outer.discard(inner) # Absence of KeyError indicates working fine > - > -#============================================================================== > - > -class TestBinaryOps(unittest.TestCase): > - def setUp(self): > - self.set = Set((2, 4, 6)) > - > - def test_eq(self): # SF bug 643115 > - self.assertEqual(self.set, Set({2:1,4:3,6:5})) > - > - def test_union_subset(self): > - result = self.set | Set([2]) > - self.assertEqual(result, Set((2, 4, 6))) > - > - def test_union_superset(self): > - result = self.set | Set([2, 4, 6, 8]) > - self.assertEqual(result, Set([2, 4, 6, 8])) > - > - def test_union_overlap(self): > - result = self.set | Set([3, 4, 5]) > - self.assertEqual(result, Set([2, 3, 4, 5, 6])) > - > - def test_union_non_overlap(self): > - result = self.set | Set([8]) > - self.assertEqual(result, Set([2, 4, 6, 8])) > - > - def test_intersection_subset(self): > - result = self.set & Set((2, 4)) > - self.assertEqual(result, Set((2, 4))) > - > - def test_intersection_superset(self): > - result = self.set & Set([2, 4, 6, 8]) > - self.assertEqual(result, Set([2, 4, 6])) > - > - def test_intersection_overlap(self): > - result = self.set & Set([3, 4, 5]) > - self.assertEqual(result, Set([4])) > - > - def test_intersection_non_overlap(self): > - result = self.set & Set([8]) > - self.assertEqual(result, empty_set) > - > - def test_sym_difference_subset(self): > - result = self.set ^ Set((2, 4)) > - self.assertEqual(result, Set([6])) > - > - def test_sym_difference_superset(self): > - result = self.set ^ Set((2, 4, 6, 8)) > - self.assertEqual(result, Set([8])) > - > - def test_sym_difference_overlap(self): > - result = self.set ^ Set((3, 4, 5)) > - self.assertEqual(result, Set([2, 3, 5, 6])) > - > - def test_sym_difference_non_overlap(self): > - result = self.set ^ Set([8]) > - self.assertEqual(result, Set([2, 4, 6, 8])) > - > - def test_cmp(self): > - a, b = Set('a'), Set('b') > - self.assertRaises(TypeError, cmp, a, b) > - > - # In py3k, this works! > - self.assertRaises(TypeError, cmp, a, a) > - > - self.assertRaises(TypeError, cmp, a, 12) > - self.assertRaises(TypeError, cmp, "abc", a) > - > - def test_inplace_on_self(self): > - t = self.set.copy() > - t |= t > - self.assertEqual(t, self.set) > - t &= t > - self.assertEqual(t, self.set) > - t -= t > - self.assertEqual(len(t), 0) > - t = self.set.copy() > - t ^= t > - self.assertEqual(len(t), 0) > - > - > -#============================================================================== > - > -class TestUpdateOps(unittest.TestCase): > - def setUp(self): > - self.set = Set((2, 4, 6)) > - > - def test_union_subset(self): > - self.set |= Set([2]) > - self.assertEqual(self.set, Set((2, 4, 6))) > - > - def test_union_superset(self): > - self.set |= Set([2, 4, 6, 8]) > - self.assertEqual(self.set, Set([2, 4, 6, 8])) > - > - def test_union_overlap(self): > - self.set |= Set([3, 4, 5]) > - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) > - > - def test_union_non_overlap(self): > - self.set |= Set([8]) > - self.assertEqual(self.set, Set([2, 4, 6, 8])) > - > - def test_union_method_call(self): > - self.set.union_update(Set([3, 4, 5])) > - self.assertEqual(self.set, Set([2, 3, 4, 5, 6])) > - > - def test_intersection_subset(self): > - self.set &= Set((2, 4)) > - self.assertEqual(self.set, Set((2, 4))) > - > - def test_intersection_superset(self): > - self.set &= Set([2, 4, 6, 8]) > - self.assertEqual(self.set, Set([2, 4, 6])) > - > - def test_intersection_overlap(self): > - self.set &= Set([3, 4, 5]) > - self.assertEqual(self.set, Set([4])) > - > - def test_intersection_non_overlap(self): > - self.set &= Set([8]) > - self.assertEqual(self.set, empty_set) > - > - def test_intersection_method_call(self): > - self.set.intersection_update(Set([3, 4, 5])) > - self.assertEqual(self.set, Set([4])) > - > - def test_sym_difference_subset(self): > - self.set ^= Set((2, 4)) > - self.assertEqual(self.set, Set([6])) > - > - def test_sym_difference_superset(self): > - self.set ^= Set((2, 4, 6, 8)) > - self.assertEqual(self.set, Set([8])) > - > - def test_sym_difference_overlap(self): > - self.set ^= Set((3, 4, 5)) > - self.assertEqual(self.set, Set([2, 3, 5, 6])) > - > - def test_sym_difference_non_overlap(self): > - self.set ^= Set([8]) > - self.assertEqual(self.set, Set([2, 4, 6, 8])) > - > - def test_sym_difference_method_call(self): > - self.set.symmetric_difference_update(Set([3, 4, 5])) > - self.assertEqual(self.set, Set([2, 3, 5, 6])) > - > - def test_difference_subset(self): > - self.set -= Set((2, 4)) > - self.assertEqual(self.set, Set([6])) > - > - def test_difference_superset(self): > - self.set -= Set((2, 4, 6, 8)) > - self.assertEqual(self.set, Set([])) > - > - def test_difference_overlap(self): > - self.set -= Set((3, 4, 5)) > - self.assertEqual(self.set, Set([2, 6])) > - > - def test_difference_non_overlap(self): > - self.set -= Set([8]) > - self.assertEqual(self.set, Set([2, 4, 6])) > - > - def test_difference_method_call(self): > - self.set.difference_update(Set([3, 4, 5])) > - self.assertEqual(self.set, Set([2, 6])) > - > -#============================================================================== > - > -class TestMutate(unittest.TestCase): > - def setUp(self): > - self.values = ["a", "b", "c"] > - self.set = Set(self.values) > - > - def test_add_present(self): > - self.set.add("c") > - self.assertEqual(self.set, Set("abc")) > - > - def test_add_absent(self): > - self.set.add("d") > - self.assertEqual(self.set, Set("abcd")) > - > - def test_add_until_full(self): > - tmp = Set() > - expected_len = 0 > - for v in self.values: > - tmp.add(v) > - expected_len += 1 > - self.assertEqual(len(tmp), expected_len) > - self.assertEqual(tmp, self.set) > - > - def test_remove_present(self): > - self.set.remove("b") > - self.assertEqual(self.set, Set("ac")) > - > - def test_remove_absent(self): > - try: > - self.set.remove("d") > - self.fail("Removing missing element should have raised LookupError") > - except LookupError: > - pass > - > - def test_remove_until_empty(self): > - expected_len = len(self.set) > - for v in self.values: > - self.set.remove(v) > - expected_len -= 1 > - self.assertEqual(len(self.set), expected_len) > - > - def test_discard_present(self): > - self.set.discard("c") > - self.assertEqual(self.set, Set("ab")) > - > - def test_discard_absent(self): > - self.set.discard("d") > - self.assertEqual(self.set, Set("abc")) > - > - def test_clear(self): > - self.set.clear() > - self.assertEqual(len(self.set), 0) > - > - def test_pop(self): > - popped = {} > - while self.set: > - popped[self.set.pop()] = None > - self.assertEqual(len(popped), len(self.values)) > - for v in self.values: > - self.failUnless(v in popped) > - > - def test_update_empty_tuple(self): > - self.set.union_update(()) > - self.assertEqual(self.set, Set(self.values)) > - > - def test_update_unit_tuple_overlap(self): > - self.set.union_update(("a",)) > - self.assertEqual(self.set, Set(self.values)) > - > - def test_update_unit_tuple_non_overlap(self): > - self.set.union_update(("a", "z")) > - self.assertEqual(self.set, Set(self.values + ["z"])) > - > -#============================================================================== > - > -class TestSubsets(unittest.TestCase): > - > - case2method = {"<=": "issubset", > - ">=": "issuperset", > - } > - > - reverse = {"==": "==", > - "!=": "!=", > - "<": ">", > - ">": "<", > - "<=": ">=", > - ">=": "<=", > - } > - > - def test_issubset(self): > - x = self.left > - y = self.right > - for case in "!=", "==", "<", "<=", ">", ">=": > - expected = case in self.cases > - # Test the binary infix spelling. > - result = eval("x" + case + "y", locals()) > - self.assertEqual(result, expected) > - # Test the "friendly" method-name spelling, if one exists. > - if case in TestSubsets.case2method: > - method = getattr(x, TestSubsets.case2method[case]) > - result = method(y) > - self.assertEqual(result, expected) > - > - # Now do the same for the operands reversed. > - rcase = TestSubsets.reverse[case] > - result = eval("y" + rcase + "x", locals()) > - self.assertEqual(result, expected) > - if rcase in TestSubsets.case2method: > - method = getattr(y, TestSubsets.case2method[rcase]) > - result = method(x) > - self.assertEqual(result, expected) > -#------------------------------------------------------------------------------ > - > -class TestSubsetEqualEmpty(TestSubsets): > - left = Set() > - right = Set() > - name = "both empty" > - cases = "==", "<=", ">=" > - > -#------------------------------------------------------------------------------ > - > -class TestSubsetEqualNonEmpty(TestSubsets): > - left = Set([1, 2]) > - right = Set([1, 2]) > - name = "equal pair" > - cases = "==", "<=", ">=" > - > -#------------------------------------------------------------------------------ > - > -class TestSubsetEmptyNonEmpty(TestSubsets): > - left = Set() > - right = Set([1, 2]) > - name = "one empty, one non-empty" > - cases = "!=", "<", "<=" > - > -#------------------------------------------------------------------------------ > - > -class TestSubsetPartial(TestSubsets): > - left = Set([1]) > - right = Set([1, 2]) > - name = "one a non-empty proper subset of other" > - cases = "!=", "<", "<=" > - > -#------------------------------------------------------------------------------ > - > -class TestSubsetNonOverlap(TestSubsets): > - left = Set([1]) > - right = Set([2]) > - name = "neither empty, neither contains" > - cases = "!=" > - > -#============================================================================== > - > -class TestOnlySetsInBinaryOps(unittest.TestCase): > - > - def test_eq_ne(self): > - # Unlike the others, this is testing that == and != *are* allowed. > - self.assertEqual(self.other == self.set, False) > - self.assertEqual(self.set == self.other, False) > - self.assertEqual(self.other != self.set, True) > - self.assertEqual(self.set != self.other, True) > - > - def test_ge_gt_le_lt(self): > - self.assertRaises(TypeError, lambda: self.set < self.other) > - self.assertRaises(TypeError, lambda: self.set <= self.other) > - self.assertRaises(TypeError, lambda: self.set > self.other) > - self.assertRaises(TypeError, lambda: self.set >= self.other) > - > - self.assertRaises(TypeError, lambda: self.other < self.set) > - self.assertRaises(TypeError, lambda: self.other <= self.set) > - self.assertRaises(TypeError, lambda: self.other > self.set) > - self.assertRaises(TypeError, lambda: self.other >= self.set) > - > - def test_union_update_operator(self): > - try: > - self.set |= self.other > - except TypeError: > - pass > - else: > - self.fail("expected TypeError") > - > - def test_union_update(self): > - if self.otherIsIterable: > - self.set.union_update(self.other) > - else: > - self.assertRaises(TypeError, self.set.union_update, self.other) > - > - def test_union(self): > - self.assertRaises(TypeError, lambda: self.set | self.other) > - self.assertRaises(TypeError, lambda: self.other | self.set) > - if self.otherIsIterable: > - self.set.union(self.other) > - else: > - self.assertRaises(TypeError, self.set.union, self.other) > - > - def test_intersection_update_operator(self): > - try: > - self.set &= self.other > - except TypeError: > - pass > - else: > - self.fail("expected TypeError") > - > - def test_intersection_update(self): > - if self.otherIsIterable: > - self.set.intersection_update(self.other) > - else: > - self.assertRaises(TypeError, > - self.set.intersection_update, > - self.other) > - > - def test_intersection(self): > - self.assertRaises(TypeError, lambda: self.set & self.other) > - self.assertRaises(TypeError, lambda: self.other & self.set) > - if self.otherIsIterable: > - self.set.intersection(self.other) > - else: > - self.assertRaises(TypeError, self.set.intersection, self.other) > - > - def test_sym_difference_update_operator(self): > - try: > - self.set ^= self.other > - except TypeError: > - pass > - else: > - self.fail("expected TypeError") > - > - def test_sym_difference_update(self): > - if self.otherIsIterable: > - self.set.symmetric_difference_update(self.other) > - else: > - self.assertRaises(TypeError, > - self.set.symmetric_difference_update, > - self.other) > - > - def test_sym_difference(self): > - self.assertRaises(TypeError, lambda: self.set ^ self.other) > - self.assertRaises(TypeError, lambda: self.other ^ self.set) > - if self.otherIsIterable: > - self.set.symmetric_difference(self.other) > - else: > - self.assertRaises(TypeError, self.set.symmetric_difference, self.other) > - > - def test_difference_update_operator(self): > - try: > - self.set -= self.other > - except TypeError: > - pass > - else: > - self.fail("expected TypeError") > - > - def test_difference_update(self): > - if self.otherIsIterable: > - self.set.difference_update(self.other) > - else: > - self.assertRaises(TypeError, > - self.set.difference_update, > - self.other) > - > - def test_difference(self): > - self.assertRaises(TypeError, lambda: self.set - self.other) > - self.assertRaises(TypeError, lambda: self.other - self.set) > - if self.otherIsIterable: > - self.set.difference(self.other) > - else: > - self.assertRaises(TypeError, self.set.difference, self.other) > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsNumeric(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = 19 > - self.otherIsIterable = False > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsDict(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = {1:2, 3:4} > - self.otherIsIterable = True > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsOperator(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = operator.add > - self.otherIsIterable = False > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsTuple(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = (2, 4, 6) > - self.otherIsIterable = True > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsString(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = 'abc' > - self.otherIsIterable = True > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsGenerator(TestOnlySetsInBinaryOps): > - def setUp(self): > - def gen(): > - for i in xrange(0, 10, 2): > - yield i > - self.set = Set((1, 2, 3)) > - self.other = gen() > - self.otherIsIterable = True > - > -#------------------------------------------------------------------------------ > - > -class TestOnlySetsofSets(TestOnlySetsInBinaryOps): > - def setUp(self): > - self.set = Set((1, 2, 3)) > - self.other = [Set('ab'), ImmutableSet('cd')] > - self.otherIsIterable = True > - > -#============================================================================== > - > -class TestCopying(unittest.TestCase): > - > - def test_copy(self): > - dup = self.set.copy() > - dup_list = sorted(dup, key=repr) > - set_list = sorted(self.set, key=repr) > - self.assertEqual(len(dup_list), len(set_list)) > - for i in range(len(dup_list)): > - self.failUnless(dup_list[i] is set_list[i]) > - > - def test_deep_copy(self): > - dup = copy.deepcopy(self.set) > - ##print type(dup), repr(dup) > - dup_list = sorted(dup, key=repr) > - set_list = sorted(self.set, key=repr) > - self.assertEqual(len(dup_list), len(set_list)) > - for i in range(len(dup_list)): > - self.assertEqual(dup_list[i], set_list[i]) > - > -#------------------------------------------------------------------------------ > - > -class TestCopyingEmpty(TestCopying): > - def setUp(self): > - self.set = Set() > - > -#------------------------------------------------------------------------------ > - > -class TestCopyingSingleton(TestCopying): > - def setUp(self): > - self.set = Set(["hello"]) > - > -#------------------------------------------------------------------------------ > - > -class TestCopyingTriple(TestCopying): > - def setUp(self): > - self.set = Set(["zero", 0, None]) > - > -#------------------------------------------------------------------------------ > - > -class TestCopyingTuple(TestCopying): > - def setUp(self): > - self.set = Set([(1, 2)]) > - > -#------------------------------------------------------------------------------ > - > -class TestCopyingNested(TestCopying): > - def setUp(self): > - self.set = Set([((1, 2), (3, 4))]) > - > -#============================================================================== > - > -class TestIdentities(unittest.TestCase): > - def setUp(self): > - self.a = Set([random.randrange(100) for i in xrange(50)]) > - self.b = Set([random.randrange(100) for i in xrange(50)]) > - > - def test_binopsVsSubsets(self): > - a, b = self.a, self.b > - self.assert_(a - b <= a) > - self.assert_(b - a <= b) > - self.assert_(a & b <= a) > - self.assert_(a & b <= b) > - self.assert_(a | b >= a) > - self.assert_(a | b >= b) > - self.assert_(a ^ b <= a | b) > - > - def test_commutativity(self): > - a, b = self.a, self.b > - self.assertEqual(a&b, b&a) > - self.assertEqual(a|b, b|a) > - self.assertEqual(a^b, b^a) > - if a != b: > - self.assertNotEqual(a-b, b-a) > - > - def test_reflexsive_relations(self): > - a, zero = self.a, Set() > - self.assertEqual(a ^ a, zero) > - self.assertEqual(a - a, zero) > - self.assertEqual(a | a, a) > - self.assertEqual(a & a, a) > - self.assert_(a <= a) > - self.assert_(a >= a) > - self.assert_(a == a) > - > - def test_summations(self): > - # check that sums of parts equal the whole > - a, b = self.a, self.b > - self.assertEqual((a-b)|(a&b)|(b-a), a|b) > - self.assertEqual((a&b)|(a^b), a|b) > - self.assertEqual(a|(b-a), a|b) > - self.assertEqual((a-b)|b, a|b) > - self.assertEqual((a-b)|(a&b), a) > - self.assertEqual((b-a)|(a&b), b) > - self.assertEqual((a-b)|(b-a), a^b) > - > - def test_exclusion(self): > - # check that inverse operations do not overlap > - a, b, zero = self.a, self.b, Set() > - self.assertEqual((a-b)&b, zero) > - self.assertEqual((b-a)&a, zero) > - self.assertEqual((a&b)&(a^b), zero) > - > - def test_cardinality_relations(self): > - a, b = self.a, self.b > - self.assertEqual(len(a), len(a-b) + len(a&b)) > - self.assertEqual(len(b), len(b-a) + len(a&b)) > - self.assertEqual(len(a^b), len(a-b) + len(b-a)) > - self.assertEqual(len(a|b), len(a-b) + len(a&b) + len(b-a)) > - self.assertEqual(len(a^b) + len(a&b), len(a|b)) > - > -#============================================================================== > - > -libreftest = """ > -Example from the Library Reference: Doc/lib/libsets.tex > - > ->>> from sets import Set as Base # override _repr to get sorted output > ->>> class Set(Base): > -... def _repr(self): > -... return Base._repr(self, sorted=True) > ->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) > ->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) > ->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack']) > ->>> employees = engineers | programmers | managers # union > ->>> engineering_management = engineers & managers # intersection > ->>> fulltime_management = managers - engineers - programmers # difference > ->>> engineers.add('Marvin') > ->>> print engineers > -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) > ->>> employees.issuperset(engineers) # superset test > -False > ->>> employees.union_update(engineers) # update from another set > ->>> employees.issuperset(engineers) > -True > ->>> for group in [engineers, programmers, managers, employees]: > -... group.discard('Susan') # unconditionally remove element > -... print group > -... > -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin']) > -Set(['Jack', 'Janice', 'Sam']) > -Set(['Jack', 'Jane', 'Zack']) > -Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin', 'Sam', 'Zack']) > -""" > - > -#============================================================================== > - > -__test__ = {'libreftest' : libreftest} > - > -def test_main(verbose=None): > - import doctest > - from test import test_sets > - test_support.run_unittest( > - TestSetOfSets, > - TestExceptionPropagation, > - TestBasicOpsEmpty, > - TestBasicOpsSingleton, > - TestBasicOpsTuple, > - TestBasicOpsTriple, > - TestBinaryOps, > - TestUpdateOps, > - TestMutate, > - TestSubsetEqualEmpty, > - TestSubsetEqualNonEmpty, > - TestSubsetEmptyNonEmpty, > - TestSubsetPartial, > - TestSubsetNonOverlap, > - TestOnlySetsNumeric, > - TestOnlySetsDict, > - TestOnlySetsOperator, > - TestOnlySetsTuple, > - TestOnlySetsString, > - TestOnlySetsGenerator, > - TestOnlySetsofSets, > - TestCopyingEmpty, > - TestCopyingSingleton, > - TestCopyingTriple, > - TestCopyingTuple, > - TestCopyingNested, > - TestIdentities, > - doctest.DocTestSuite(test_sets), > - ) > - > -if __name__ == "__main__": > - test_main(verbose=True) > > > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > From python-3000-checkins at python.org Wed Jan 10 19:51:37 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 19:51:37 +0100 (CET) Subject: [Python-3000-checkins] r53349 - in python/branches/p3yk: Grammar/Grammar Include/Python-ast.h Lib/compiler/pycodegen.py Lib/compiler/transformer.py Parser/Python.asdl Python/Python-ast.c Python/ast.c Python/compile.c Python/graminit.c Python/symtable.c Message-ID: <20070110185137.112231E400A@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 19:51:35 2007 New Revision: 53349 Modified: python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/graminit.c python/branches/p3yk/Python/symtable.c Log: Some more changes related to the new except syntax and semantics, by Collin Winter. Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Wed Jan 10 19:51:35 2007 @@ -79,7 +79,7 @@ with_stmt: 'with' test [ with_var ] ':' suite with_var: 'as' expr # NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test ['as' test]] +except_clause: 'except' [test ['as' NAME]] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT # Backward compatibility cruft to support: Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Wed Jan 10 19:51:35 2007 @@ -322,7 +322,7 @@ struct _excepthandler { expr_ty type; - expr_ty name; + identifier name; asdl_seq *body; int lineno; int col_offset; @@ -448,8 +448,8 @@ slice_ty Index(expr_ty value, PyArena *arena); comprehension_ty comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, PyArena *arena); -excepthandler_ty excepthandler(expr_ty type, expr_ty name, asdl_seq * body, int - lineno, int col_offset, PyArena *arena); +excepthandler_ty excepthandler(expr_ty type, identifier name, asdl_seq * body, + int lineno, int col_offset, PyArena *arena); arguments_ty arguments(asdl_seq * args, identifier vararg, expr_ty varargannotation, asdl_seq * kwonlyargs, identifier kwarg, expr_ty kwargannotation, asdl_seq * defaults, Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Wed Jan 10 19:51:35 2007 @@ -825,11 +825,33 @@ self.emit('POP_TOP') self.emit('POP_TOP') if target: - self.visit(target) + cleanup_body = self.newBlock() + cleanup_final = self.newBlock() + target_name = target[1] + + self.storeName(target_name) + self.emit('POP_TOP') + self.emit('SETUP_FINALLY', cleanup_final) + self.nextBlock(cleanup_body) + self.setups.push((TRY_FINALLY, cleanup_body)) + self.visit(body) + self.emit('POP_BLOCK') + self.setups.pop() + self.emit('LOAD_CONST', None) + self.nextBlock(cleanup_final) + self.setups.push((END_FINALLY, cleanup_final)) + + + self.emit('LOAD_CONST', None) + self.storeName(target_name) + self._implicitNameOp('DELETE', target_name) + + self.emit('END_FINALLY') + self.setups.pop() else: self.emit('POP_TOP') - self.emit('POP_TOP') - self.visit(body) + self.emit('POP_TOP') + self.visit(body) self.emit('JUMP_FORWARD', end) if expr: self.nextBlock(next) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Wed Jan 10 19:51:35 2007 @@ -988,16 +988,16 @@ for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: - # except_clause: 'except' [expr [',' expr]] */ + # except_clause: 'except' [expr ['as' NAME]] */ if len(node) > 2: - expr1 = self.com_node(node[2]) + expr = self.com_node(node[2]) if len(node) > 4: - expr2 = self.com_assign(node[4], OP_ASSIGN) + expr_name = node[4] else: - expr2 = None + expr_name = None else: - expr1 = expr2 = None - clauses.append((expr1, expr2, self.com_node(nodelist[i+2]))) + expr = expr_name = None + clauses.append((expr, expr_name, self.com_node(nodelist[i+2]))) if node[0] == token.NAME: if node[1] == 'else': Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Wed Jan 10 19:51:35 2007 @@ -97,7 +97,7 @@ -- TODO(jhylton): Figure out if there is a better way to handle -- lineno and col_offset fields, particularly when -- ast is exposed to Python. - excepthandler = (expr? type, expr? name, stmt* body, int lineno, + excepthandler = (expr? type, identifier? name, stmt* body, int lineno, int col_offset) arguments = (arg* args, identifier? vararg, expr? varargannotation, Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Wed Jan 10 19:51:35 2007 @@ -1836,7 +1836,7 @@ } excepthandler_ty -excepthandler(expr_ty type, expr_ty name, asdl_seq * body, int lineno, int +excepthandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena) { excepthandler_ty p; @@ -2928,7 +2928,7 @@ if (PyObject_SetAttrString(result, "type", value) == -1) goto failed; Py_DECREF(value); - value = ast2obj_expr(o->name); + value = ast2obj_identifier(o->name); if (!value) goto failed; if (PyObject_SetAttrString(result, "name", value) == -1) goto failed; Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Wed Jan 10 19:51:35 2007 @@ -2899,11 +2899,9 @@ else if (NCH(exc) == 4) { asdl_seq *suite_seq; expr_ty expression; - expr_ty e = ast_for_expr(c, CHILD(exc, 3)); + identifier e = NEW_IDENTIFIER(CHILD(exc, 3)); if (!e) return NULL; - if (!set_context(e, Store, CHILD(exc, 3))) - return NULL; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Wed Jan 10 19:51:35 2007 @@ -1956,16 +1956,13 @@ ADDOP(c, POP_TOP); if (handler->name) { basicblock *cleanup_end, *cleanup_body; - expr_context_ty orig_ctx; - - assert(handler->name->kind == Name_kind); cleanup_end = compiler_new_block(c); cleanup_body = compiler_new_block(c); if(!(cleanup_end || cleanup_body)) return 0; - VISIT(c, expr, handler->name); + compiler_nameop(c, handler->name, Store); ADDOP(c, POP_TOP); /* @@ -1998,14 +1995,10 @@ /* name = None */ ADDOP_O(c, LOAD_CONST, Py_None, consts); - orig_ctx = handler->name->v.Name.ctx; - handler->name->v.Name.ctx = Store; - VISIT(c, expr, handler->name); - - /* del name */ - handler->name->v.Name.ctx = Del; - VISIT(c, expr, handler->name); - handler->name->v.Name.ctx = orig_ctx; + compiler_nameop(c, handler->name, Store); + + /* del name */ + compiler_nameop(c, handler->name, Del); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, cleanup_end); Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Wed Jan 10 19:51:35 2007 @@ -1053,7 +1053,7 @@ {0, 2}, }; static arc arcs_46_3[1] = { - {22, 4}, + {19, 4}, }; static arc arcs_46_4[1] = { {0, 4}, Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Wed Jan 10 19:51:35 2007 @@ -1335,7 +1335,8 @@ if (eh->type) VISIT(st, expr, eh->type); if (eh->name) - VISIT(st, expr, eh->name); + if (!symtable_add_def(st, eh->name, DEF_LOCAL)) + return 0; VISIT_SEQ(st, stmt, eh->body); return 1; } From python-3000-checkins at python.org Wed Jan 10 17:20:35 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 10 Jan 2007 17:20:35 +0100 (CET) Subject: [Python-3000-checkins] r53342 - in python/branches/p3yk: Demo/cgi/wiki.py Demo/comparisons/regextest.py Demo/comparisons/systemtest.py Demo/parser/test_parser.py Demo/parser/unparse.py Demo/pdist/FSProxy.py Demo/pdist/cmdfw.py Demo/pdist/cmptree.py Demo/pdist/cvslock.py Demo/pdist/rrcs.py Demo/pysvr/pysvr.py Demo/rpc/nfsclient.py Demo/rpc/rpc.py Demo/scripts/eqfix.py Demo/scripts/ftpstats.py Demo/scripts/mboxconvert.py Demo/scripts/newslist.py Demo/scripts/pp.py Demo/scripts/update.py Demo/sockets/gopher.py Demo/sockets/telnet.py Demo/threads/find.py Demo/threads/telnet.py Demo/tkinter/guido/AttrDialog.py Demo/tkinter/guido/ManPage.py Demo/tkinter/guido/mbox.py Demo/tkinter/guido/tkman.py Demo/tkinter/guido/wish.py Doc/howto/urllib2.rst Doc/lib/email-unpack.py Doc/lib/libcsv.tex Doc/lib/libgetopt.tex Doc/lib/libshutil.tex Doc/lib/libsocket.tex Doc/lib/libsubprocess.tex Doc/lib/libxdrlib.tex Doc/lib/libxmlrpclib.tex Doc/lib/sqlite3/complete_statement.py Doc/tools/findcsyms Doc/tools/listmodules Doc/tools/mkhowto Doc/tools/mksourcepkg Doc/tools/prechm.py Doc/tools/sgmlconv/docfixer.py Doc/tools/sgmlconv/esis2sgml.py Doc/tools/sgmlconv/esistools.py Doc/tools/sgmlconv/latex2esis.py Doc/tut/tut.tex Grammar/Grammar Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/SimpleXMLRPCServer.py Lib/_strptime.py Lib/asynchat.py Lib/asyncore.py Lib/base64.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compare.py Lib/bsddb/test/test_pickle.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cgi.py Lib/codecs.py Lib/codeop.py Lib/compileall.py Lib/compiler/pycodegen.py Lib/contextlib.py Lib/csv.py Lib/ctypes/macholib/dyld.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_bitfields.py Lib/ctypes/test/test_structures.py Lib/ctypes/util.py Lib/dis.py Lib/distutils/bcppcompiler.py Lib/distutils/command/register.py Lib/distutils/command/sdist.py Lib/distutils/command/upload.py Lib/distutils/core.py Lib/distutils/cygwinccompiler.py Lib/distutils/dir_util.py Lib/distutils/dist.py Lib/distutils/emxccompiler.py Lib/distutils/fancy_getopt.py Lib/distutils/file_util.py Lib/distutils/msvccompiler.py Lib/distutils/spawn.py Lib/distutils/sysconfig.py Lib/distutils/unixccompiler.py Lib/distutils/util.py Lib/doctest.py Lib/encodings/uu_codec.py Lib/filecmp.py Lib/ftplib.py Lib/hotshot/stones.py Lib/htmllib.py Lib/httplib.py Lib/idlelib/ClassBrowser.py Lib/idlelib/EditorWindow.py Lib/idlelib/GrepDialog.py Lib/idlelib/IOBinding.py Lib/idlelib/PyShell.py Lib/idlelib/ScriptBinding.py Lib/idlelib/SearchEngine.py Lib/idlelib/run.py Lib/imaplib.py Lib/lib-tk/Tkinter.py Lib/linecache.py Lib/logging/config.py Lib/mailbox.py Lib/mhlib.py Lib/mimetypes.py Lib/modulefinder.py Lib/msilib/__init__.py Lib/nntplib.py Lib/optparse.py Lib/os.py Lib/pdb.py Lib/pickle.py Lib/pkgutil.py Lib/plat-irix5/torgb.py Lib/plat-irix6/torgb.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/MiniAEFrame.py Lib/plat-mac/aetools.py Lib/plat-mac/applesingle.py Lib/plat-mac/argvemulator.py Lib/plat-mac/buildtools.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/macresource.py Lib/plat-mac/pimp.py Lib/plat-mac/terminalcommand.py Lib/platform.py Lib/poplib.py Lib/pstats.py Lib/pty.py Lib/py_compile.py Lib/pydoc.py Lib/quopri.py Lib/re.py Lib/rexec.py Lib/sgmllib.py Lib/shutil.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/hooks.py Lib/sqlite3/test/userfunctions.py Lib/subprocess.py Lib/tabnanny.py Lib/tarfile.py Lib/telnetlib.py Lib/tempfile.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/sortperf.py Lib/test/string_tests.py Lib/test/test_bool.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_class.py Lib/test/test_codecs.py Lib/test/test_compiler.py Lib/test/test_contextlib.py Lib/test/test_cookielib.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_defaultdict.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_dl.py Lib/test/test_eof.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_file.py Lib/test/test_format.py Lib/test/test_frozen.py Lib/test/test_future.py Lib/test/test_generators.py Lib/test/test_grammar.py Lib/test/test_import.py Lib/test/test_linuxaudiodev.py Lib/test/test_nis.py Lib/test/test_opcodes.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_ossaudiodev.py Lib/test/test_parser.py Lib/test/test_pep277.py Lib/test/test_pyexpat.py Lib/test/test_re.py Lib/test/test_runpy.py Lib/test/test_sax.py Lib/test/test_set.py Lib/test/test_socket.py Lib/test/test_socket_ssl.py Lib/test/test_socketserver.py Lib/test/test_strftime.py Lib/test/test_string.py Lib/test/test_strptime.py Lib/test/test_subprocess.py Lib/test/test_sunaudiodev.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_tcl.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_urllib2net.py Lib/test/test_userdict.py Lib/test/test_uu.py Lib/test/test_winreg.py Lib/timeit.py Lib/toaiff.py Lib/token.py Lib/trace.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/uu.py Lib/warnings.py Lib/webbrowser.py Lib/xdrlib.py Lib/xml/sax/__init__.py Lib/xml/sax/expatreader.py Lib/xmllib.py Lib/xmlrpclib.py Lib/zipfile.py Mac/BuildScript/build-installer.py Mac/Demo/applescript/makedisk.py Mac/Demo/imgbrowse/imgbrowse.py Mac/Demo/mlte/mlted.py Mac/Demo/resources/copyres.py Mac/Demo/textedit/ped.py Mac/scripts/BuildApplet.py Mac/scripts/buildpkg.py Misc/BeOS-setup.py Modules/parsermodule.c Python/compile.c Python/graminit.c Tools/audiopy/audiopy Tools/bgen/bgen/scantools.py Tools/compiler/compile.py Tools/compiler/regrtest.py Tools/faqwiz/faqw.py Tools/faqwiz/faqwiz.py Tools/freeze/checkextensions_win32.py Tools/freeze/freeze.py Tools/i18n/msgfmt.py Tools/i18n/pygettext.py Tools/pybench/CommandLine.py Tools/pybench/pybench.py Tools/pynche/Main.py Tools/scripts/byext.py Tools/scripts/byteyears.py Tools/scripts/checkappend.py Tools/scripts/classfix.py Tools/scripts/cleanfuture.py Tools/scripts/cvsfiles.py Tools/scripts/dutree.py Tools/scripts/finddiv.py Tools/scripts/findlinksto.py Tools/scripts/findnocoding.py Tools/scripts/fixcid.py Tools/scripts/fixdiv.py Tools/scripts/fixheader.py Tools/scripts/fixnotice.py Tools/scripts/fixps.py Tools/scripts/ftpmirror.py Tools/scripts/linktree.py Tools/scripts/logmerge.py Tools/scripts/md5sum.py Tools/scripts/methfix.py Tools/scripts/ndiff.py Tools/scripts/pathfix.py Tools/scripts/pindent.py Tools/scripts/pysource.py Tools/scripts/redemo.py Tools/scripts/reindent.py Tools/scripts/rgrep.py Tools/scripts/texi2html.py Tools/scripts/treesync.py Tools/scripts/untabify.py Tools/unicode/comparecodecs.py Tools/unicode/gencodec.py Tools/unicode/listcodecs.py Tools/versioncheck/pyversioncheck.py Tools/webchecker/wcgui.py Tools/webchecker/webchecker.py Tools/webchecker/websucker.py setup.py Message-ID: <20070110162035.C3BEA1E4018@bag.python.org> Author: guido.van.rossum Date: Wed Jan 10 17:19:56 2007 New Revision: 53342 Modified: python/branches/p3yk/Demo/cgi/wiki.py python/branches/p3yk/Demo/comparisons/regextest.py python/branches/p3yk/Demo/comparisons/systemtest.py python/branches/p3yk/Demo/parser/test_parser.py python/branches/p3yk/Demo/parser/unparse.py python/branches/p3yk/Demo/pdist/FSProxy.py python/branches/p3yk/Demo/pdist/cmdfw.py python/branches/p3yk/Demo/pdist/cmptree.py python/branches/p3yk/Demo/pdist/cvslock.py python/branches/p3yk/Demo/pdist/rrcs.py python/branches/p3yk/Demo/pysvr/pysvr.py python/branches/p3yk/Demo/rpc/nfsclient.py python/branches/p3yk/Demo/rpc/rpc.py python/branches/p3yk/Demo/scripts/eqfix.py python/branches/p3yk/Demo/scripts/ftpstats.py python/branches/p3yk/Demo/scripts/mboxconvert.py python/branches/p3yk/Demo/scripts/newslist.py python/branches/p3yk/Demo/scripts/pp.py python/branches/p3yk/Demo/scripts/update.py python/branches/p3yk/Demo/sockets/gopher.py python/branches/p3yk/Demo/sockets/telnet.py python/branches/p3yk/Demo/threads/find.py python/branches/p3yk/Demo/threads/telnet.py python/branches/p3yk/Demo/tkinter/guido/AttrDialog.py python/branches/p3yk/Demo/tkinter/guido/ManPage.py python/branches/p3yk/Demo/tkinter/guido/mbox.py python/branches/p3yk/Demo/tkinter/guido/tkman.py python/branches/p3yk/Demo/tkinter/guido/wish.py python/branches/p3yk/Doc/howto/urllib2.rst python/branches/p3yk/Doc/lib/email-unpack.py python/branches/p3yk/Doc/lib/libcsv.tex python/branches/p3yk/Doc/lib/libgetopt.tex python/branches/p3yk/Doc/lib/libshutil.tex python/branches/p3yk/Doc/lib/libsocket.tex python/branches/p3yk/Doc/lib/libsubprocess.tex python/branches/p3yk/Doc/lib/libxdrlib.tex python/branches/p3yk/Doc/lib/libxmlrpclib.tex python/branches/p3yk/Doc/lib/sqlite3/complete_statement.py python/branches/p3yk/Doc/tools/findcsyms python/branches/p3yk/Doc/tools/listmodules python/branches/p3yk/Doc/tools/mkhowto python/branches/p3yk/Doc/tools/mksourcepkg python/branches/p3yk/Doc/tools/prechm.py python/branches/p3yk/Doc/tools/sgmlconv/docfixer.py python/branches/p3yk/Doc/tools/sgmlconv/esis2sgml.py python/branches/p3yk/Doc/tools/sgmlconv/esistools.py python/branches/p3yk/Doc/tools/sgmlconv/latex2esis.py python/branches/p3yk/Doc/tut/tut.tex python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Lib/CGIHTTPServer.py python/branches/p3yk/Lib/ConfigParser.py python/branches/p3yk/Lib/SimpleXMLRPCServer.py python/branches/p3yk/Lib/_strptime.py python/branches/p3yk/Lib/asynchat.py python/branches/p3yk/Lib/asyncore.py python/branches/p3yk/Lib/base64.py python/branches/p3yk/Lib/bsddb/dbtables.py python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_compare.py python/branches/p3yk/Lib/bsddb/test/test_pickle.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/cgi.py python/branches/p3yk/Lib/codecs.py python/branches/p3yk/Lib/codeop.py python/branches/p3yk/Lib/compileall.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/contextlib.py python/branches/p3yk/Lib/csv.py python/branches/p3yk/Lib/ctypes/macholib/dyld.py python/branches/p3yk/Lib/ctypes/test/__init__.py python/branches/p3yk/Lib/ctypes/test/test_bitfields.py python/branches/p3yk/Lib/ctypes/test/test_structures.py python/branches/p3yk/Lib/ctypes/util.py python/branches/p3yk/Lib/dis.py python/branches/p3yk/Lib/distutils/bcppcompiler.py python/branches/p3yk/Lib/distutils/command/register.py python/branches/p3yk/Lib/distutils/command/sdist.py python/branches/p3yk/Lib/distutils/command/upload.py python/branches/p3yk/Lib/distutils/core.py python/branches/p3yk/Lib/distutils/cygwinccompiler.py python/branches/p3yk/Lib/distutils/dir_util.py python/branches/p3yk/Lib/distutils/dist.py python/branches/p3yk/Lib/distutils/emxccompiler.py python/branches/p3yk/Lib/distutils/fancy_getopt.py python/branches/p3yk/Lib/distutils/file_util.py python/branches/p3yk/Lib/distutils/msvccompiler.py python/branches/p3yk/Lib/distutils/spawn.py python/branches/p3yk/Lib/distutils/sysconfig.py python/branches/p3yk/Lib/distutils/unixccompiler.py python/branches/p3yk/Lib/distutils/util.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/encodings/uu_codec.py python/branches/p3yk/Lib/filecmp.py python/branches/p3yk/Lib/ftplib.py python/branches/p3yk/Lib/hotshot/stones.py python/branches/p3yk/Lib/htmllib.py python/branches/p3yk/Lib/httplib.py python/branches/p3yk/Lib/idlelib/ClassBrowser.py python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/idlelib/GrepDialog.py python/branches/p3yk/Lib/idlelib/IOBinding.py python/branches/p3yk/Lib/idlelib/PyShell.py python/branches/p3yk/Lib/idlelib/ScriptBinding.py python/branches/p3yk/Lib/idlelib/SearchEngine.py python/branches/p3yk/Lib/idlelib/run.py python/branches/p3yk/Lib/imaplib.py python/branches/p3yk/Lib/lib-tk/Tkinter.py python/branches/p3yk/Lib/linecache.py python/branches/p3yk/Lib/logging/config.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/mhlib.py python/branches/p3yk/Lib/mimetypes.py python/branches/p3yk/Lib/modulefinder.py python/branches/p3yk/Lib/msilib/__init__.py python/branches/p3yk/Lib/nntplib.py python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Lib/os.py python/branches/p3yk/Lib/pdb.py python/branches/p3yk/Lib/pickle.py python/branches/p3yk/Lib/pkgutil.py python/branches/p3yk/Lib/plat-irix5/torgb.py python/branches/p3yk/Lib/plat-irix6/torgb.py python/branches/p3yk/Lib/plat-mac/EasyDialogs.py python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py python/branches/p3yk/Lib/plat-mac/aetools.py python/branches/p3yk/Lib/plat-mac/applesingle.py python/branches/p3yk/Lib/plat-mac/argvemulator.py python/branches/p3yk/Lib/plat-mac/buildtools.py python/branches/p3yk/Lib/plat-mac/bundlebuilder.py python/branches/p3yk/Lib/plat-mac/gensuitemodule.py python/branches/p3yk/Lib/plat-mac/macresource.py python/branches/p3yk/Lib/plat-mac/pimp.py python/branches/p3yk/Lib/plat-mac/terminalcommand.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/poplib.py python/branches/p3yk/Lib/pstats.py python/branches/p3yk/Lib/pty.py python/branches/p3yk/Lib/py_compile.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/quopri.py python/branches/p3yk/Lib/re.py python/branches/p3yk/Lib/rexec.py python/branches/p3yk/Lib/sgmllib.py python/branches/p3yk/Lib/shutil.py python/branches/p3yk/Lib/site.py python/branches/p3yk/Lib/smtpd.py python/branches/p3yk/Lib/smtplib.py python/branches/p3yk/Lib/sqlite3/test/dbapi.py python/branches/p3yk/Lib/sqlite3/test/hooks.py python/branches/p3yk/Lib/sqlite3/test/userfunctions.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/tabnanny.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/telnetlib.py python/branches/p3yk/Lib/tempfile.py python/branches/p3yk/Lib/test/pickletester.py python/branches/p3yk/Lib/test/regrtest.py python/branches/p3yk/Lib/test/sortperf.py python/branches/p3yk/Lib/test/string_tests.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_cfgparser.py python/branches/p3yk/Lib/test/test_cgi.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_codecs.py python/branches/p3yk/Lib/test/test_compiler.py python/branches/p3yk/Lib/test/test_contextlib.py python/branches/p3yk/Lib/test/test_cookielib.py python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_decimal.py python/branches/p3yk/Lib/test/test_defaultdict.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Lib/test/test_dl.py python/branches/p3yk/Lib/test/test_eof.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_extcall.py python/branches/p3yk/Lib/test/test_file.py python/branches/p3yk/Lib/test/test_format.py python/branches/p3yk/Lib/test/test_frozen.py python/branches/p3yk/Lib/test/test_future.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_import.py python/branches/p3yk/Lib/test/test_linuxaudiodev.py python/branches/p3yk/Lib/test/test_nis.py python/branches/p3yk/Lib/test/test_opcodes.py python/branches/p3yk/Lib/test/test_optparse.py python/branches/p3yk/Lib/test/test_os.py python/branches/p3yk/Lib/test/test_ossaudiodev.py python/branches/p3yk/Lib/test/test_parser.py python/branches/p3yk/Lib/test/test_pep277.py python/branches/p3yk/Lib/test/test_pyexpat.py python/branches/p3yk/Lib/test/test_re.py python/branches/p3yk/Lib/test/test_runpy.py python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Lib/test/test_socket_ssl.py python/branches/p3yk/Lib/test/test_socketserver.py python/branches/p3yk/Lib/test/test_strftime.py python/branches/p3yk/Lib/test/test_string.py python/branches/p3yk/Lib/test/test_strptime.py python/branches/p3yk/Lib/test/test_subprocess.py python/branches/p3yk/Lib/test/test_sunaudiodev.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_syntax.py python/branches/p3yk/Lib/test/test_sys.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_tcl.py python/branches/p3yk/Lib/test/test_trace.py python/branches/p3yk/Lib/test/test_traceback.py python/branches/p3yk/Lib/test/test_urllib2net.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_uu.py python/branches/p3yk/Lib/test/test_winreg.py python/branches/p3yk/Lib/timeit.py python/branches/p3yk/Lib/toaiff.py python/branches/p3yk/Lib/token.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/unittest.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Lib/urllib2.py python/branches/p3yk/Lib/uu.py python/branches/p3yk/Lib/warnings.py python/branches/p3yk/Lib/webbrowser.py python/branches/p3yk/Lib/xdrlib.py python/branches/p3yk/Lib/xml/sax/__init__.py python/branches/p3yk/Lib/xml/sax/expatreader.py python/branches/p3yk/Lib/xmllib.py python/branches/p3yk/Lib/xmlrpclib.py python/branches/p3yk/Lib/zipfile.py python/branches/p3yk/Mac/BuildScript/build-installer.py python/branches/p3yk/Mac/Demo/applescript/makedisk.py python/branches/p3yk/Mac/Demo/imgbrowse/imgbrowse.py python/branches/p3yk/Mac/Demo/mlte/mlted.py python/branches/p3yk/Mac/Demo/resources/copyres.py python/branches/p3yk/Mac/Demo/textedit/ped.py python/branches/p3yk/Mac/scripts/BuildApplet.py python/branches/p3yk/Mac/scripts/buildpkg.py python/branches/p3yk/Misc/BeOS-setup.py python/branches/p3yk/Modules/parsermodule.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/graminit.c python/branches/p3yk/Tools/audiopy/audiopy python/branches/p3yk/Tools/bgen/bgen/scantools.py python/branches/p3yk/Tools/compiler/compile.py python/branches/p3yk/Tools/compiler/regrtest.py python/branches/p3yk/Tools/faqwiz/faqw.py python/branches/p3yk/Tools/faqwiz/faqwiz.py python/branches/p3yk/Tools/freeze/checkextensions_win32.py python/branches/p3yk/Tools/freeze/freeze.py python/branches/p3yk/Tools/i18n/msgfmt.py python/branches/p3yk/Tools/i18n/pygettext.py python/branches/p3yk/Tools/pybench/CommandLine.py python/branches/p3yk/Tools/pybench/pybench.py python/branches/p3yk/Tools/pynche/Main.py python/branches/p3yk/Tools/scripts/byext.py python/branches/p3yk/Tools/scripts/byteyears.py python/branches/p3yk/Tools/scripts/checkappend.py python/branches/p3yk/Tools/scripts/classfix.py python/branches/p3yk/Tools/scripts/cleanfuture.py python/branches/p3yk/Tools/scripts/cvsfiles.py python/branches/p3yk/Tools/scripts/dutree.py python/branches/p3yk/Tools/scripts/finddiv.py python/branches/p3yk/Tools/scripts/findlinksto.py python/branches/p3yk/Tools/scripts/findnocoding.py python/branches/p3yk/Tools/scripts/fixcid.py python/branches/p3yk/Tools/scripts/fixdiv.py python/branches/p3yk/Tools/scripts/fixheader.py python/branches/p3yk/Tools/scripts/fixnotice.py python/branches/p3yk/Tools/scripts/fixps.py python/branches/p3yk/Tools/scripts/ftpmirror.py python/branches/p3yk/Tools/scripts/linktree.py python/branches/p3yk/Tools/scripts/logmerge.py python/branches/p3yk/Tools/scripts/md5sum.py python/branches/p3yk/Tools/scripts/methfix.py python/branches/p3yk/Tools/scripts/ndiff.py python/branches/p3yk/Tools/scripts/pathfix.py python/branches/p3yk/Tools/scripts/pindent.py python/branches/p3yk/Tools/scripts/pysource.py python/branches/p3yk/Tools/scripts/redemo.py python/branches/p3yk/Tools/scripts/reindent.py python/branches/p3yk/Tools/scripts/rgrep.py python/branches/p3yk/Tools/scripts/texi2html.py python/branches/p3yk/Tools/scripts/treesync.py python/branches/p3yk/Tools/scripts/untabify.py python/branches/p3yk/Tools/unicode/comparecodecs.py python/branches/p3yk/Tools/unicode/gencodec.py python/branches/p3yk/Tools/unicode/listcodecs.py python/branches/p3yk/Tools/versioncheck/pyversioncheck.py python/branches/p3yk/Tools/webchecker/wcgui.py python/branches/p3yk/Tools/webchecker/webchecker.py python/branches/p3yk/Tools/webchecker/websucker.py python/branches/p3yk/setup.py Log: SF patch 1631942 by Collin Winter: (a) "except E, V" -> "except E as V" (b) V is now limited to a simple name (local variable) (c) V is now deleted at the end of the except block Modified: python/branches/p3yk/Demo/cgi/wiki.py ============================================================================== --- python/branches/p3yk/Demo/cgi/wiki.py (original) +++ python/branches/p3yk/Demo/cgi/wiki.py Wed Jan 10 17:19:56 2007 @@ -119,5 +119,5 @@ f.write('\n') f.close() return "" - except IOError, err: + except IOError as err: return "IOError: %s" % str(err) Modified: python/branches/p3yk/Demo/comparisons/regextest.py ============================================================================== --- python/branches/p3yk/Demo/comparisons/regextest.py (original) +++ python/branches/p3yk/Demo/comparisons/regextest.py Wed Jan 10 17:19:56 2007 @@ -28,7 +28,7 @@ for file in sys.argv[1:]: try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print "%s: %s" % (file, msg) continue lineno = 0 Modified: python/branches/p3yk/Demo/comparisons/systemtest.py ============================================================================== --- python/branches/p3yk/Demo/comparisons/systemtest.py (original) +++ python/branches/p3yk/Demo/comparisons/systemtest.py Wed Jan 10 17:19:56 2007 @@ -41,7 +41,7 @@ def reportboguslinks(prefix): try: names = os.listdir('.') - except os.error, msg: + except os.error as msg: print "%s%s: can't list: %s" % (prefix, '.', msg) return names.sort() @@ -62,7 +62,7 @@ elif S_ISDIR(mode): try: os.chdir(name) - except os.error, msg: + except os.error as msg: print "%s%s: can't chdir: %s" % \ (prefix, name, msg) continue Modified: python/branches/p3yk/Demo/parser/test_parser.py ============================================================================== --- python/branches/p3yk/Demo/parser/test_parser.py (original) +++ python/branches/p3yk/Demo/parser/test_parser.py Wed Jan 10 17:19:56 2007 @@ -17,7 +17,7 @@ # against a large source file like Tkinter.py. ast = None new = parser.tuple2ast(tup) - except parser.ParserError, err: + except parser.ParserError as err: print print 'parser module raised exception on input file', fileName + ':' traceback.print_exc() Modified: python/branches/p3yk/Demo/parser/unparse.py ============================================================================== --- python/branches/p3yk/Demo/parser/unparse.py (original) +++ python/branches/p3yk/Demo/parser/unparse.py Wed Jan 10 17:19:56 2007 @@ -492,7 +492,7 @@ print 'Testing %s' % fullname try: roundtrip(fullname, output) - except Exception, e: + except Exception as e: print ' Failed to compile, exception is %s' % repr(e) elif os.path.isdir(fullname): testdir(fullname) Modified: python/branches/p3yk/Demo/pdist/FSProxy.py ============================================================================== --- python/branches/p3yk/Demo/pdist/FSProxy.py (original) +++ python/branches/p3yk/Demo/pdist/FSProxy.py Wed Jan 10 17:19:56 2007 @@ -87,7 +87,7 @@ fs = macfs.FSSpec(name) c, t = fs.GetCreatorType() if t != 'TEXT': return 0 - except macfs.error, msg: + except macfs.error as msg: print "***", name, msg return 0 else: Modified: python/branches/p3yk/Demo/pdist/cmdfw.py ============================================================================== --- python/branches/p3yk/Demo/pdist/cmdfw.py (original) +++ python/branches/p3yk/Demo/pdist/cmdfw.py Wed Jan 10 17:19:56 2007 @@ -42,7 +42,7 @@ if args is None: args = sys.argv[1:] try: opts, args = getopt.getopt(args, self.GlobalFlags) - except getopt.error, msg: + except getopt.error as msg: return self.usage(msg) self.options(opts) if not args: @@ -62,7 +62,7 @@ flags = '' try: opts, args = getopt.getopt(args[1:], flags) - except getopt.error, msg: + except getopt.error as msg: return self.usage( "subcommand %s: " % cmd + str(msg)) self.ready() Modified: python/branches/p3yk/Demo/pdist/cmptree.py ============================================================================== --- python/branches/p3yk/Demo/pdist/cmptree.py (original) +++ python/branches/p3yk/Demo/pdist/cmptree.py Wed Jan 10 17:19:56 2007 @@ -135,7 +135,7 @@ def sendfile(local, remote, name): try: remote.create(name) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "cannot create:", msg return @@ -171,7 +171,7 @@ def recvfile_real(local, remote, name): try: local.create(name) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "cannot create:", msg return Modified: python/branches/p3yk/Demo/pdist/cvslock.py ============================================================================== --- python/branches/p3yk/Demo/pdist/cvslock.py (original) +++ python/branches/p3yk/Demo/pdist/cvslock.py Wed Jan 10 17:19:56 2007 @@ -129,7 +129,7 @@ self.lockdir = self.cvslck os.mkdir(self.cvslck, 0777) return - except os.error, msg: + except os.error as msg: self.lockdir = None if msg[0] == EEXIST: try: @@ -234,7 +234,7 @@ for r in repositories: try: locks.append(WriteLock(r, 0)) - except Locked, instance: + except Locked as instance: del locks break else: Modified: python/branches/p3yk/Demo/pdist/rrcs.py ============================================================================== --- python/branches/p3yk/Demo/pdist/rrcs.py (original) +++ python/branches/p3yk/Demo/pdist/rrcs.py Wed Jan 10 17:19:56 2007 @@ -22,7 +22,7 @@ raise getopt.error, "unknown command" coptset, func = commands[cmd] copts, files = getopt.getopt(rest, coptset) - except getopt.error, msg: + except getopt.error as msg: print msg print "usage: rrcs [options] command [options] [file] ..." print "where command can be:" @@ -41,7 +41,7 @@ for fn in files: try: func(x, copts, fn) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: print "%s: %s" % (fn, msg) def checkin(x, copts, fn): Modified: python/branches/p3yk/Demo/pysvr/pysvr.py ============================================================================== --- python/branches/p3yk/Demo/pysvr/pysvr.py (original) +++ python/branches/p3yk/Demo/pysvr/pysvr.py Wed Jan 10 17:19:56 2007 @@ -21,14 +21,14 @@ opts, args = getopt.getopt(sys.argv[1:], "") if len(args) > 1: raise getopt.error, "Too many arguments." - except getopt.error, msg: + except getopt.error as msg: usage(msg) for o, a in opts: pass if args: try: port = string.atoi(args[0]) - except ValueError, msg: + except ValueError as msg: usage(msg) else: port = PORT @@ -83,7 +83,7 @@ source = source + line try: code = compile_command(source) - except SyntaxError, err: + except SyntaxError as err: source = "" traceback.print_exception(SyntaxError, err, None, file=stdout) continue @@ -92,7 +92,7 @@ source = "" try: run_command(code, stdin, stdout, globals) - except SystemExit, how: + except SystemExit as how: if how: try: how = str(how) @@ -109,7 +109,7 @@ sys.stdin = stdin try: exec(code, globals) - except SystemExit, how: + except SystemExit as how: raise SystemExit, how, sys.exc_info()[2] except: type, value, tb = sys.exc_info() Modified: python/branches/p3yk/Demo/rpc/nfsclient.py ============================================================================== --- python/branches/p3yk/Demo/rpc/nfsclient.py (original) +++ python/branches/p3yk/Demo/rpc/nfsclient.py Wed Jan 10 17:19:56 2007 @@ -194,8 +194,7 @@ fh = sf[1] if fh: ncl = NFSClient(host) - as = ncl.Getattr(fh) - print as + print ncl.Getattr(fh) list = ncl.Listdir(fh) for item in list: print item mcl.Umnt(filesys) Modified: python/branches/p3yk/Demo/rpc/rpc.py ============================================================================== --- python/branches/p3yk/Demo/rpc/rpc.py (original) +++ python/branches/p3yk/Demo/rpc/rpc.py Wed Jan 10 17:19:56 2007 @@ -330,7 +330,8 @@ try: sock.bind((host, i)) return last_resv_port_tried - except socket.error, (errno, msg): + except socket.error as e: + (errno, msg) = e if errno != 114: raise socket.error, (errno, msg) raise RuntimeError, 'can\'t assign reserved port' @@ -765,7 +766,7 @@ call = recvrecord(sock) except EOFError: break - except socket.error, msg: + except socket.error as msg: print 'socket error:', msg break reply = self.handle(call) @@ -866,7 +867,7 @@ s = S('', 0x20000000, 1, 0) try: s.unregister() - except RuntimeError, msg: + except RuntimeError as msg: print 'RuntimeError:', msg, '(ignored)' s.register() print 'Service started...' Modified: python/branches/p3yk/Demo/scripts/eqfix.py ============================================================================== --- python/branches/p3yk/Demo/scripts/eqfix.py (original) +++ python/branches/p3yk/Demo/scripts/eqfix.py Wed Jan 10 17:19:56 2007 @@ -62,7 +62,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -83,7 +83,7 @@ ## dbg('fix(%r)\n' % (dirname,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -120,7 +120,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -144,17 +144,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk/Demo/scripts/ftpstats.py ============================================================================== --- python/branches/p3yk/Demo/scripts/ftpstats.py (original) +++ python/branches/p3yk/Demo/scripts/ftpstats.py Wed Jan 10 17:19:56 2007 @@ -25,7 +25,7 @@ search = None try: opts, args = getopt.getopt(sys.argv[1:], 'm:s:') - except getopt.error, msg: + except getopt.error as msg: print msg print 'usage: ftpstats [-m maxitems] [file]' sys.exit(2) @@ -41,7 +41,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ':', msg sys.exit(1) bydate = {} Modified: python/branches/p3yk/Demo/scripts/mboxconvert.py ============================================================================== --- python/branches/p3yk/Demo/scripts/mboxconvert.py (original) +++ python/branches/p3yk/Demo/scripts/mboxconvert.py Wed Jan 10 17:19:56 2007 @@ -16,7 +16,7 @@ dofile = mmdf try: opts, args = getopt.getopt(sys.argv[1:], 'f') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('%s\n' % msg) sys.exit(2) for o, a in opts: @@ -33,7 +33,7 @@ elif os.path.isfile(arg): try: f = open(arg) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: %s\n' % (arg, msg)) sts = 1 continue @@ -56,7 +56,7 @@ fn = os.path.join(dir, msg) try: f = open(fn) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: %s\n' % (fn, msg)) sts = 1 continue Modified: python/branches/p3yk/Demo/scripts/newslist.py ============================================================================== --- python/branches/p3yk/Demo/scripts/newslist.py (original) +++ python/branches/p3yk/Demo/scripts/newslist.py Wed Jan 10 17:19:56 2007 @@ -330,7 +330,7 @@ else: s = NNTP(newshost) connected = 1 - except (nntplib.error_temp, nntplib.error_perm), x: + except (nntplib.error_temp, nntplib.error_perm) as x: print 'Error connecting to host:', x print 'I\'ll try to use just the local list.' connected = 0 Modified: python/branches/p3yk/Demo/scripts/pp.py ============================================================================== --- python/branches/p3yk/Demo/scripts/pp.py (original) +++ python/branches/p3yk/Demo/scripts/pp.py Wed Jan 10 17:19:56 2007 @@ -35,7 +35,7 @@ try: optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') -except getopt.error, msg: +except getopt.error as msg: sys.stderr.write(sys.argv[0] + ': ' + msg + '\n') sys.exit(2) Modified: python/branches/p3yk/Demo/scripts/update.py ============================================================================== --- python/branches/p3yk/Demo/scripts/update.py (original) +++ python/branches/p3yk/Demo/scripts/update.py Wed Jan 10 17:19:56 2007 @@ -19,7 +19,7 @@ self.changed = 0 try: self.lines = open(filename, 'r').readlines() - except IOError, msg: + except IOError as msg: print '*** Can\'t open "%s":' % filename, msg self.lines = None return @@ -32,7 +32,7 @@ try: os.rename(self.filename, self.filename + '~') fp = open(self.filename, 'w') - except (os.error, IOError), msg: + except (os.error, IOError) as msg: print '*** Can\'t rewrite "%s":' % self.filename, msg return print 'writing', self.filename @@ -67,7 +67,7 @@ if sys.argv[1:]: try: fp = open(sys.argv[1], 'r') - except IOError, msg: + except IOError as msg: print 'Can\'t open "%s":' % sys.argv[1], msg sys.exit(1) else: Modified: python/branches/p3yk/Demo/sockets/gopher.py ============================================================================== --- python/branches/p3yk/Demo/sockets/gopher.py (original) +++ python/branches/p3yk/Demo/sockets/gopher.py Wed Jan 10 17:19:56 2007 @@ -142,7 +142,7 @@ raise RuntimeError, 'too many args' try: browse_menu(selector, host, port) - except socket.error, msg: + except socket.error as msg: print 'Socket error:', msg sys.exit(1) except KeyboardInterrupt: @@ -202,7 +202,7 @@ p = os.popen('${PAGER-more}', 'w') x = SaveLines(p) get_alt_textfile(selector, host, port, x.writeln) - except IOError, msg: + except IOError as msg: print 'IOError:', msg if x: x.close() @@ -213,7 +213,7 @@ try: get_alt_textfile(selector, host, port, x.writeln) print 'Done.' - except IOError, msg: + except IOError as msg: print 'IOError:', msg x.close() @@ -311,7 +311,7 @@ cmd = savefile[1:].strip() try: p = os.popen(cmd, 'w') - except IOError, msg: + except IOError as msg: print repr(cmd), ':', msg return None print 'Piping through', repr(cmd), '...' @@ -320,7 +320,7 @@ savefile = os.path.expanduser(savefile) try: f = open(savefile, 'w') - except IOError, msg: + except IOError as msg: print repr(savefile), ':', msg return None print 'Saving to', repr(savefile), '...' Modified: python/branches/p3yk/Demo/sockets/telnet.py ============================================================================== --- python/branches/p3yk/Demo/sockets/telnet.py (original) +++ python/branches/p3yk/Demo/sockets/telnet.py Wed Jan 10 17:19:56 2007 @@ -52,7 +52,7 @@ # try: s.connect((host, port)) - except error, msg: + except error as msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # Modified: python/branches/p3yk/Demo/threads/find.py ============================================================================== --- python/branches/p3yk/Demo/threads/find.py (original) +++ python/branches/p3yk/Demo/threads/find.py Wed Jan 10 17:19:56 2007 @@ -131,7 +131,7 @@ def find(dir, pred, wq): try: names = os.listdir(dir) - except os.error, msg: + except os.error as msg: print repr(dir), ':', msg return for name in names: @@ -139,7 +139,7 @@ fullname = os.path.join(dir, name) try: stat = os.lstat(fullname) - except os.error, msg: + except os.error as msg: print repr(fullname), ':', msg continue if pred(dir, name, fullname, stat): Modified: python/branches/p3yk/Demo/threads/telnet.py ============================================================================== --- python/branches/p3yk/Demo/threads/telnet.py (original) +++ python/branches/p3yk/Demo/threads/telnet.py Wed Jan 10 17:19:56 2007 @@ -56,7 +56,7 @@ # try: s.connect((host, port)) - except error, msg: + except error as msg: sys.stderr.write('connect failed: %r\n' % (msg,)) sys.exit(1) # Modified: python/branches/p3yk/Demo/tkinter/guido/AttrDialog.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/AttrDialog.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/AttrDialog.py Wed Jan 10 17:19:56 2007 @@ -156,7 +156,7 @@ self.current = self.var.get() try: self.dialog.widget.pack(**{self.option: self.current}) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -212,7 +212,7 @@ 'pack', 'info', self.widget)) - except TclError, msg: + except TclError as msg: print msg return dict = {} @@ -239,7 +239,7 @@ '-'+self.option, self.dialog.master.tk.merge( self.current)) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -285,7 +285,7 @@ self.current = self.var.get() try: self.dialog.widget[self.option] = self.current - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -374,7 +374,7 @@ self.master.send(self.app, self.widget, 'config')) - except TclError, msg: + except TclError as msg: print msg return dict = {} @@ -398,7 +398,7 @@ 'config', '-'+self.option, self.current) - except TclError, msg: + except TclError as msg: print msg self.refresh() @@ -445,7 +445,7 @@ if widget == '.': continue try: RemotePackDialog(list, list.app, widget) - except TclError, msg: + except TclError as msg: print msg test() Modified: python/branches/p3yk/Demo/tkinter/guido/ManPage.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/ManPage.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/ManPage.py Wed Jan 10 17:19:56 2007 @@ -95,7 +95,7 @@ self._parseline('') try: self.tk.deletefilehandler(self.fp) - except TclError, msg: + except TclError as msg: pass self.fp.close() self.fp = None Modified: python/branches/p3yk/Demo/tkinter/guido/mbox.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/mbox.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/mbox.py Wed Jan 10 17:19:56 2007 @@ -27,7 +27,7 @@ seq = 'all' try: opts, args = getopt.getopt(sys.argv[1:], '') - except getopt.error, msg: + except getopt.error as msg: print msg sys.exit(2) for arg in args: Modified: python/branches/p3yk/Demo/tkinter/guido/tkman.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/tkman.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/tkman.py Wed Jan 10 17:19:56 2007 @@ -216,7 +216,7 @@ prog = re.compile(search, map) else: prog = re.compile(search) - except re.error, msg: + except re.error as msg: self.frame.bell() print 'Regex error:', msg return Modified: python/branches/p3yk/Demo/tkinter/guido/wish.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/wish.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/wish.py Wed Jan 10 17:19:56 2007 @@ -23,7 +23,7 @@ tk.record(line) try: result = tk.call('eval', cmd) - except _tkinter.TclError, msg: + except _tkinter.TclError as msg: print 'TclError:', msg else: if result: print result Modified: python/branches/p3yk/Doc/howto/urllib2.rst ============================================================================== --- python/branches/p3yk/Doc/howto/urllib2.rst (original) +++ python/branches/p3yk/Doc/howto/urllib2.rst Wed Jan 10 17:19:56 2007 @@ -214,7 +214,7 @@ >>> req = urllib2.Request('http://www.pretend_server.org') >>> try: urllib2.urlopen(req) - >>> except URLError, e: + >>> except URLError as e: >>> print e.reason >>> (4, 'getaddrinfo failed') @@ -326,7 +326,7 @@ >>> req = urllib2.Request('http://www.python.org/fish.html') >>> try: >>> urllib2.urlopen(req) - >>> except URLError, e: + >>> except URLError as e: >>> print e.code >>> print e.read() >>> @@ -354,10 +354,10 @@ req = Request(someurl) try: response = urlopen(req) - except HTTPError, e: + except HTTPError as e: print 'The server couldn\'t fulfill the request.' print 'Error code: ', e.code - except URLError, e: + except URLError as e: print 'We failed to reach a server.' print 'Reason: ', e.reason else: @@ -378,7 +378,7 @@ req = Request(someurl) try: response = urlopen(req) - except URLError, e: + except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason Modified: python/branches/p3yk/Doc/lib/email-unpack.py ============================================================================== --- python/branches/p3yk/Doc/lib/email-unpack.py (original) +++ python/branches/p3yk/Doc/lib/email-unpack.py Wed Jan 10 17:19:56 2007 @@ -35,7 +35,7 @@ try: os.mkdir(opts.directory) - except OSError, e: + except OSError as e: # Ignore directory exists error if e.errno != errno.EEXIST: raise Modified: python/branches/p3yk/Doc/lib/libcsv.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libcsv.tex (original) +++ python/branches/p3yk/Doc/lib/libcsv.tex Wed Jan 10 17:19:56 2007 @@ -426,7 +426,7 @@ try: for row in reader: print row -except csv.Error, e: +except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) \end{verbatim} Modified: python/branches/p3yk/Doc/lib/libgetopt.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libgetopt.tex (original) +++ python/branches/p3yk/Doc/lib/libgetopt.tex Wed Jan 10 17:19:56 2007 @@ -126,7 +126,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() Modified: python/branches/p3yk/Doc/lib/libshutil.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libshutil.tex (original) +++ python/branches/p3yk/Doc/lib/libshutil.tex Wed Jan 10 17:19:56 2007 @@ -144,6 +144,6 @@ copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) - except (IOError, os.error), why: + except (IOError, os.error) as why: print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why)) \end{verbatim} Modified: python/branches/p3yk/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk/Doc/lib/libsocket.tex Wed Jan 10 17:19:56 2007 @@ -813,13 +813,13 @@ af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) - except socket.error, msg: + except socket.error as msg: s = None continue try: s.bind(sa) s.listen(1) - except socket.error, msg: + except socket.error as msg: s.close() s = None continue @@ -848,12 +848,12 @@ af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) - except socket.error, msg: + except socket.error as msg: s = None continue try: s.connect(sa) - except socket.error, msg: + except socket.error as msg: s.close() s = None continue Modified: python/branches/p3yk/Doc/lib/libsubprocess.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsubprocess.tex (original) +++ python/branches/p3yk/Doc/lib/libsubprocess.tex Wed Jan 10 17:19:56 2007 @@ -284,7 +284,7 @@ print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode -except OSError, e: +except OSError as e: print >>sys.stderr, "Execution failed:", e \end{verbatim} Modified: python/branches/p3yk/Doc/lib/libxdrlib.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libxdrlib.tex (original) +++ python/branches/p3yk/Doc/lib/libxdrlib.tex Wed Jan 10 17:19:56 2007 @@ -246,6 +246,6 @@ p = xdrlib.Packer() try: p.pack_double(8.01) -except xdrlib.ConversionError, instance: +except xdrlib.ConversionError as instance: print 'packing the double failed:', instance.msg \end{verbatim} Modified: python/branches/p3yk/Doc/lib/libxmlrpclib.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libxmlrpclib.tex (original) +++ python/branches/p3yk/Doc/lib/libxmlrpclib.tex Wed Jan 10 17:19:56 2007 @@ -358,7 +358,7 @@ try: print server.examples.getStateName(41) -except Error, v: +except Error as v: print "ERROR", v \end{verbatim} Modified: python/branches/p3yk/Doc/lib/sqlite3/complete_statement.py ============================================================================== --- python/branches/p3yk/Doc/lib/sqlite3/complete_statement.py (original) +++ python/branches/p3yk/Doc/lib/sqlite3/complete_statement.py Wed Jan 10 17:19:56 2007 @@ -23,7 +23,7 @@ if buffer.lstrip().upper().startswith("SELECT"): print cur.fetchall() - except sqlite3.Error, e: + except sqlite3.Error as e: print "An error occurred:", e.args[0] buffer = "" Modified: python/branches/p3yk/Doc/tools/findcsyms ============================================================================== --- python/branches/p3yk/Doc/tools/findcsyms (original) +++ python/branches/p3yk/Doc/tools/findcsyms Wed Jan 10 17:19:56 2007 @@ -127,7 +127,7 @@ print_list(undocumented, "Undocumented symbols") else: print_list(L) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk/Doc/tools/listmodules ============================================================================== --- python/branches/p3yk/Doc/tools/listmodules (original) +++ python/branches/p3yk/Doc/tools/listmodules Wed Jan 10 17:19:56 2007 @@ -53,7 +53,7 @@ opts, args = getopt.getopt( args, "abchi:", ["annotate", "built-in", "categorize", "help", "ignore-from="]) - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print Modified: python/branches/p3yk/Doc/tools/mkhowto ============================================================================== --- python/branches/p3yk/Doc/tools/mkhowto (original) +++ python/branches/p3yk/Doc/tools/mkhowto Wed Jan 10 17:19:56 2007 @@ -599,7 +599,7 @@ options = Options() try: args = options.parse(sys.argv[1:]) - except getopt.error, msg: + except getopt.error as msg: error(options, msg) if not args: # attempt to locate single .tex file in current directory: Modified: python/branches/p3yk/Doc/tools/mksourcepkg ============================================================================== --- python/branches/p3yk/Doc/tools/mksourcepkg (original) +++ python/branches/p3yk/Doc/tools/mksourcepkg Wed Jan 10 17:19:56 2007 @@ -45,7 +45,7 @@ opts, args = getopt.getopt(sys.argv[1:], "Aabgtzq", ["all", "bzip2", "gzip", "tools", "zip", "quiet", "anonymous"]) - except getopt.error, e: + except getopt.error as e: usage(warning=str(e)) sys.exit(2) if len(args) not in (1, 2): Modified: python/branches/p3yk/Doc/tools/prechm.py ============================================================================== --- python/branches/p3yk/Doc/tools/prechm.py (original) +++ python/branches/p3yk/Doc/tools/prechm.py Wed Jan 10 17:19:56 2007 @@ -448,7 +448,7 @@ def openfile(file): try: p = open(file, "w") - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) return p @@ -466,7 +466,7 @@ try: optlist, args = getopt.getopt(args, 'ckpv:') - except getopt.error, msg: + except getopt.error as msg: print msg usage() Modified: python/branches/p3yk/Doc/tools/sgmlconv/docfixer.py ============================================================================== --- python/branches/p3yk/Doc/tools/sgmlconv/docfixer.py (original) +++ python/branches/p3yk/Doc/tools/sgmlconv/docfixer.py Wed Jan 10 17:19:56 2007 @@ -1039,7 +1039,8 @@ # try: write_esis(fragment, ofp, knownempty) - except IOError, (err, msg): + except IOError as e: + (err, msg) = e # Ignore EPIPE; it just means that whoever we're writing to stopped # reading. The rest of the output would be ignored. All other errors # should still be reported, Modified: python/branches/p3yk/Doc/tools/sgmlconv/esis2sgml.py ============================================================================== --- python/branches/p3yk/Doc/tools/sgmlconv/esis2sgml.py (original) +++ python/branches/p3yk/Doc/tools/sgmlconv/esis2sgml.py Wed Jan 10 17:19:56 2007 @@ -255,7 +255,8 @@ if xml and xmldecl: opf.write('\n') convert(ifp, ofp, xml=xml, autoclose=autoclose, verbatims=verbatims) - except IOError, (err, msg): + except IOError as e: + (err, msg) = e if err != errno.EPIPE: raise Modified: python/branches/p3yk/Doc/tools/sgmlconv/esistools.py ============================================================================== --- python/branches/p3yk/Doc/tools/sgmlconv/esistools.py (original) +++ python/branches/p3yk/Doc/tools/sgmlconv/esistools.py Wed Jan 10 17:19:56 2007 @@ -139,7 +139,7 @@ def _get_token(self, fp): try: line = fp.readline() - except IOError, e: + except IOError as e: e = SAXException("I/O error reading input stream", e) self.getErrorHandler().fatalError(e) return Modified: python/branches/p3yk/Doc/tools/sgmlconv/latex2esis.py ============================================================================== --- python/branches/p3yk/Doc/tools/sgmlconv/latex2esis.py (original) +++ python/branches/p3yk/Doc/tools/sgmlconv/latex2esis.py Wed Jan 10 17:19:56 2007 @@ -397,7 +397,8 @@ c = Conversion(ifp, ofp, table) try: c.convert() - except IOError, (err, msg): + except IOError as e: + (err, msg) = e if err != errno.EPIPE: raise Modified: python/branches/p3yk/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk/Doc/tut/tut.tex (original) +++ python/branches/p3yk/Doc/tut/tut.tex Wed Jan 10 17:19:56 2007 @@ -3480,8 +3480,9 @@ f = open('myfile.txt') s = f.readline() i = int(s.strip()) -except IOError, (errno, strerror): - print "I/O error(%s): %s" % (errno, strerror) +except IOError as e: + (errno, strerror) = e + print "I/O error(%s): %s" % (e.errno, e.strerror) except ValueError: print "Could not convert data to an integer." except: @@ -3530,7 +3531,7 @@ \begin{verbatim} >>> try: ... raise Exception('spam', 'eggs') -... except Exception, inst: +... except Exception as inst: ... print type(inst) # the exception instance ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly @@ -3559,7 +3560,7 @@ ... >>> try: ... this_fails() -... except ZeroDivisionError, detail: +... except ZeroDivisionError as detail: ... print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo by zero @@ -3619,7 +3620,7 @@ ... >>> try: ... raise MyError(2*2) -... except MyError, e: +... except MyError as e: ... print 'My exception occurred, value:', e.value ... My exception occurred, value: 4 Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Wed Jan 10 17:19:56 2007 @@ -79,7 +79,7 @@ with_stmt: 'with' test [ with_var ] ':' suite with_var: 'as' expr # NB compile.c makes sure that the default except clause is last -except_clause: 'except' [test [',' test]] +except_clause: 'except' [test ['as' test]] suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT # Backward compatibility cruft to support: Modified: python/branches/p3yk/Lib/CGIHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/CGIHTTPServer.py (original) +++ python/branches/p3yk/Lib/CGIHTTPServer.py Wed Jan 10 17:19:56 2007 @@ -320,7 +320,7 @@ sys.stdout = save_stdout sys.stderr = save_stderr os.chdir(save_cwd) - except SystemExit, sts: + except SystemExit as sts: self.log_error("CGI script exit status %s", str(sts)) else: self.log_message("CGI script exited OK") Modified: python/branches/p3yk/Lib/ConfigParser.py ============================================================================== --- python/branches/p3yk/Lib/ConfigParser.py (original) +++ python/branches/p3yk/Lib/ConfigParser.py Wed Jan 10 17:19:56 2007 @@ -567,7 +567,7 @@ value = self._KEYCRE.sub(self._interpolation_replace, value) try: value = value % vars - except KeyError, e: + except KeyError as e: raise InterpolationMissingOptionError( option, section, rawval, e[0]) else: Modified: python/branches/p3yk/Lib/SimpleXMLRPCServer.py ============================================================================== --- python/branches/p3yk/Lib/SimpleXMLRPCServer.py (original) +++ python/branches/p3yk/Lib/SimpleXMLRPCServer.py Wed Jan 10 17:19:56 2007 @@ -259,7 +259,7 @@ response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) - except Fault, fault: + except Fault as fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: @@ -359,7 +359,7 @@ # XXX A marshalling error in any response will fail the entire # multicall. If someone cares they should fix this. results.append([self._dispatch(method_name, params)]) - except Fault, fault: + except Fault as fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} Modified: python/branches/p3yk/Lib/_strptime.py ============================================================================== --- python/branches/p3yk/Lib/_strptime.py (original) +++ python/branches/p3yk/Lib/_strptime.py Wed Jan 10 17:19:56 2007 @@ -291,7 +291,7 @@ format_regex = time_re.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it - except KeyError, err: + except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" Modified: python/branches/p3yk/Lib/asynchat.py ============================================================================== --- python/branches/p3yk/Lib/asynchat.py (original) +++ python/branches/p3yk/Lib/asynchat.py Wed Jan 10 17:19:56 2007 @@ -87,7 +87,7 @@ try: data = self.recv (self.ac_in_buffer_size) - except socket.error, why: + except socket.error as why: self.handle_error() return @@ -220,7 +220,7 @@ if num_sent: self.ac_out_buffer = self.ac_out_buffer[num_sent:] - except socket.error, why: + except socket.error as why: self.handle_error() return Modified: python/branches/p3yk/Lib/asyncore.py ============================================================================== --- python/branches/p3yk/Lib/asyncore.py (original) +++ python/branches/p3yk/Lib/asyncore.py Wed Jan 10 17:19:56 2007 @@ -119,7 +119,7 @@ else: try: r, w, e = select.select(r, w, e, timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise else: @@ -165,7 +165,7 @@ pollster.register(fd, flags) try: r = pollster.poll(timeout) - except select.error, err: + except select.error as err: if err[0] != EINTR: raise r = [] @@ -320,7 +320,7 @@ try: conn, addr = self.socket.accept() return conn, addr - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: pass else: @@ -330,7 +330,7 @@ try: result = self.socket.send(data) return result - except socket.error, why: + except socket.error as why: if why[0] == EWOULDBLOCK: return 0 else: @@ -347,7 +347,7 @@ return '' else: return data - except socket.error, why: + except socket.error as why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() Modified: python/branches/p3yk/Lib/base64.py ============================================================================== --- python/branches/p3yk/Lib/base64.py (original) +++ python/branches/p3yk/Lib/base64.py Wed Jan 10 17:19:56 2007 @@ -71,7 +71,7 @@ s = _translate(s, {altchars[0]: '+', altchars[1]: '/'}) try: return binascii.a2b_base64(s) - except binascii.Error, msg: + except binascii.Error as msg: # Transform this exception for consistency raise TypeError(msg) @@ -328,7 +328,7 @@ import sys, getopt try: opts, args = getopt.getopt(sys.argv[1:], 'deut') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print """usage: %s [-d|-e|-u|-t] [file|-] Modified: python/branches/p3yk/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/dbtables.py Wed Jan 10 17:19:56 2007 @@ -260,7 +260,7 @@ txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -338,7 +338,7 @@ txn = None self.__load_column_info(table) - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] @@ -407,7 +407,7 @@ txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: # WIBNI we could just abort the txn and re-raise the exception? # But no, because TableDBError is not related to DBError via # inheritance, so it would be backwards incompatible. Do the next @@ -466,7 +466,7 @@ txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] def Delete(self, table, conditions={}): @@ -502,11 +502,11 @@ pass txn.commit() txn = None - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] @@ -526,7 +526,7 @@ if columns is None: columns = self.__tablecolumns[table] matching_rowids = self.__Select(table, columns, conditions) - except DBError, dberror: + except DBError as dberror: raise TableDBError, dberror[1] # return the matches as a list of dictionaries return matching_rowids.values() @@ -616,7 +616,7 @@ key, data = cur.next() - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise continue @@ -636,7 +636,7 @@ try: rowdata[column] = self.db.get( _data_key(table, column, rowid)) - except DBError, dberror: + except DBError as dberror: if dberror[0] != DB_NOTFOUND: raise rowdata[column] = None @@ -700,7 +700,7 @@ if table in self.__tablecolumns: del self.__tablecolumns[table] - except DBError, dberror: + except DBError as dberror: if txn: txn.abort() raise TableDBError, dberror[1] Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Wed Jan 10 17:19:56 2007 @@ -58,7 +58,7 @@ self.homeDir = homeDir try: shutil.rmtree(homeDir) - except OSError, e: + except OSError as e: # unix returns ENOENT, windows returns ESRCH if e.errno not in (errno.ENOENT, errno.ESRCH): raise os.mkdir(homeDir) @@ -162,7 +162,7 @@ # set_get_returns_none() to change it. try: d.delete('abcd') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -181,7 +181,7 @@ try: d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE) - except db.DBKeyExistError, val: + except db.DBKeyExistError as val: assert val[0] == db.DB_KEYEXIST if verbose: print val else: @@ -313,7 +313,7 @@ print rec try: rec = c.next() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -333,7 +333,7 @@ print rec try: rec = c.prev() - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_raises_error: assert val[0] == db.DB_NOTFOUND if verbose: print val @@ -357,7 +357,7 @@ try: n = c.set('bad key') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -371,7 +371,7 @@ try: n = c.get_both('0404', 'bad data') - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: assert val[0] == db.DB_NOTFOUND if verbose: print val else: @@ -399,7 +399,7 @@ c.delete() try: rec = c.current() - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_raises_error: assert val[0] == db.DB_KEYEMPTY if verbose: print val @@ -445,7 +445,7 @@ method # a bug may cause a NULL pointer dereference... getattr(c, method)(*args) - except db.DBError, val: + except db.DBError as val: assert val[0] == 0 if verbose: print val else: @@ -730,7 +730,7 @@ txn.abort() try: txn.abort() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.abort() called after DB_TXN no longer valid w/o an exception" @@ -739,7 +739,7 @@ txn.commit() try: txn.commit() - except db.DBError, e: + except db.DBError as e: pass else: raise RuntimeError, "DBTxn.commit() called after DB_TXN no longer valid w/o an exception" Modified: python/branches/p3yk/Lib/bsddb/test/test_compare.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_compare.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_compare.py Wed Jan 10 17:19:56 2007 @@ -234,7 +234,7 @@ self.db.set_bt_compare (my_compare) assert False, "this set should fail" - except RuntimeError, msg: + except RuntimeError as msg: pass def test_suite (): Modified: python/branches/p3yk/Lib/bsddb/test/test_pickle.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_pickle.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_pickle.py Wed Jan 10 17:19:56 2007 @@ -11,7 +11,7 @@ try: # For Pythons w/distutils pybsddb from bsddb3 import db -except ImportError, e: +except ImportError as e: # For Python 2.3 from bsddb import db @@ -47,7 +47,7 @@ assert self.db['spam'] == 'eggs' try: self.db.put('spam', 'ham', flags=db.DB_NOOVERWRITE) - except db.DBError, egg: + except db.DBError as egg: pickledEgg = pickle.dumps(egg) #print repr(pickledEgg) rottenEgg = pickle.loads(pickledEgg) Modified: python/branches/p3yk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_recno.py Wed Jan 10 17:19:56 2007 @@ -29,7 +29,7 @@ def tearDown(self): try: os.remove(self.filename) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise def test01_basic(self): @@ -63,7 +63,7 @@ try: data = d[0] # This should raise a KeyError!?!?! - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: @@ -72,7 +72,7 @@ # test that has_key raises DB exceptions (fixed in pybsddb 4.3.2) try: d.has_key(0) - except db.DBError, val: + except db.DBError as val: pass else: self.fail("has_key did not raise a proper exception") @@ -86,7 +86,7 @@ try: data = d.get(100) - except db.DBNotFoundError, val: + except db.DBNotFoundError as val: if get_returns_none: self.fail("unexpected exception") else: @@ -177,7 +177,7 @@ try: d.get(99) - except db.DBKeyEmptyError, val: + except db.DBKeyEmptyError as val: if get_returns_none: self.fail("unexpected DBKeyEmptyError exception") else: @@ -267,7 +267,7 @@ try: # this one will fail d.append('bad' * 20) - except db.DBInvalidArgError, val: + except db.DBInvalidArgError as val: assert val[0] == db.EINVAL if verbose: print val else: Modified: python/branches/p3yk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_thread.py Wed Jan 10 17:19:56 2007 @@ -57,7 +57,7 @@ self.homeDir = homeDir try: os.mkdir(homeDir) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() @@ -247,7 +247,7 @@ # flush them try: dbutils.DeadlockWrap(d.sync, max_retries=12) - except db.DBIncompleteError, val: + except db.DBIncompleteError as val: if verbose: print "could not complete sync()..." @@ -360,7 +360,7 @@ print "%s: records %d - %d finished" % (name, start, x) txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -398,7 +398,7 @@ finished = True if verbose: print "%s: deleted records %s" % (name, recs) - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() @@ -428,7 +428,7 @@ c.close() txn.commit() finished = True - except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: + except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) c.close() Modified: python/branches/p3yk/Lib/cgi.py ============================================================================== --- python/branches/p3yk/Lib/cgi.py (original) +++ python/branches/p3yk/Lib/cgi.py Wed Jan 10 17:19:56 2007 @@ -982,7 +982,7 @@ print "

Current Working Directory:

" try: pwd = os.getcwd() - except os.error, msg: + except os.error as msg: print "os.error:", escape(str(msg)) else: print escape(pwd) Modified: python/branches/p3yk/Lib/codecs.py ============================================================================== --- python/branches/p3yk/Lib/codecs.py (original) +++ python/branches/p3yk/Lib/codecs.py Wed Jan 10 17:19:56 2007 @@ -13,7 +13,7 @@ try: from _codecs import * -except ImportError, why: +except ImportError as why: raise SystemError('Failed to load the builtin codecs: %s' % why) __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE", @@ -422,7 +422,7 @@ data = self.bytebuffer + newdata try: newchars, decodedbytes = self.decode(data, self.errors) - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: if firstline: newchars, decodedbytes = self.decode(data[:exc.start], self.errors) lines = newchars.splitlines(True) Modified: python/branches/p3yk/Lib/codeop.py ============================================================================== --- python/branches/p3yk/Lib/codeop.py (original) +++ python/branches/p3yk/Lib/codeop.py Wed Jan 10 17:19:56 2007 @@ -80,18 +80,18 @@ try: code = compiler(source, filename, symbol) - except SyntaxError, err: + except SyntaxError as err: pass try: code1 = compiler(source + "\n", filename, symbol) - except SyntaxError, err1: - pass + except SyntaxError as e: + err1 = e try: code2 = compiler(source + "\n\n", filename, symbol) - except SyntaxError, err2: - pass + except SyntaxError as e: + err2 = e if code: return code Modified: python/branches/p3yk/Lib/compileall.py ============================================================================== --- python/branches/p3yk/Lib/compileall.py (original) +++ python/branches/p3yk/Lib/compileall.py Wed Jan 10 17:19:56 2007 @@ -65,12 +65,12 @@ ok = py_compile.compile(fullname, None, dfile, True) except KeyboardInterrupt: raise KeyboardInterrupt - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 - except IOError, e: + except IOError as e: print "Sorry", e success = 0 else: @@ -109,7 +109,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:') - except getopt.error, msg: + except getopt.error as msg: print msg print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ "[-x regexp] [directory ...]" Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Wed Jan 10 17:19:56 2007 @@ -227,7 +227,7 @@ assert getattr(self, 'NameFinder') assert getattr(self, 'FunctionGen') assert getattr(self, 'ClassGen') - except AssertionError, msg: + except AssertionError as msg: intro = "Bad class construction for %s" % self.__class__.__name__ raise AssertionError, intro Modified: python/branches/p3yk/Lib/contextlib.py ============================================================================== --- python/branches/p3yk/Lib/contextlib.py (original) +++ python/branches/p3yk/Lib/contextlib.py Wed Jan 10 17:19:56 2007 @@ -28,7 +28,7 @@ try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") - except StopIteration, exc: + except StopIteration as exc: # Suppress the exception *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed Modified: python/branches/p3yk/Lib/csv.py ============================================================================== --- python/branches/p3yk/Lib/csv.py (original) +++ python/branches/p3yk/Lib/csv.py Wed Jan 10 17:19:56 2007 @@ -48,7 +48,7 @@ def _validate(self): try: _Dialect(self) - except TypeError, e: + except TypeError as e: # We do this for compatibility with py2.3 raise Error(str(e)) Modified: python/branches/p3yk/Lib/ctypes/macholib/dyld.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/macholib/dyld.py (original) +++ python/branches/p3yk/Lib/ctypes/macholib/dyld.py Wed Jan 10 17:19:56 2007 @@ -148,7 +148,7 @@ """ try: return dyld_find(fn, executable_path=executable_path, env=env) - except ValueError, e: + except ValueError as e: pass fmwk_index = fn.rfind('.framework') if fmwk_index == -1: Modified: python/branches/p3yk/Lib/ctypes/test/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/test/__init__.py Wed Jan 10 17:19:56 2007 @@ -57,12 +57,12 @@ for modname in find_package_modules(package, mask): try: mod = __import__(modname, globals(), locals(), ['*']) - except ResourceDenied, detail: + except ResourceDenied as detail: skipped.append(modname) if verbosity > 1: print >> sys.stderr, "Skipped %s: %s" % (modname, detail) continue - except Exception, detail: + except Exception as detail: print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail) continue for name in dir(mod): Modified: python/branches/p3yk/Lib/ctypes/test/test_bitfields.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_bitfields.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_bitfields.py Wed Jan 10 17:19:56 2007 @@ -191,7 +191,7 @@ def get_except(self, func, *args, **kw): try: func(*args, **kw) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) def test_mixed_1(self): Modified: python/branches/p3yk/Lib/ctypes/test/test_structures.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_structures.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_structures.py Wed Jan 10 17:19:56 2007 @@ -313,7 +313,7 @@ def get_except(self, func, *args): try: func(*args) - except Exception, detail: + except Exception as detail: return detail.__class__, str(detail) @@ -388,7 +388,7 @@ try: Recursive._fields_ = [("next", Recursive)] - except AttributeError, details: + except AttributeError as details: self.failUnless("Structure or union cannot contain itself" in str(details)) else: @@ -405,7 +405,7 @@ try: Second._fields_ = [("first", First)] - except AttributeError, details: + except AttributeError as details: self.failUnless("_fields_ is final" in str(details)) else: Modified: python/branches/p3yk/Lib/ctypes/util.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/util.py (original) +++ python/branches/p3yk/Lib/ctypes/util.py Wed Jan 10 17:19:56 2007 @@ -60,12 +60,12 @@ finally: try: os.unlink(outfile) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise try: os.unlink(ccout) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise res = re.search(expr, trace) Modified: python/branches/p3yk/Lib/dis.py ============================================================================== --- python/branches/p3yk/Lib/dis.py (original) +++ python/branches/p3yk/Lib/dis.py Wed Jan 10 17:19:56 2007 @@ -33,7 +33,7 @@ print "Disassembly of %s:" % name try: dis(x1) - except TypeError, msg: + except TypeError as msg: print "Sorry:", msg print elif hasattr(x, 'co_code'): Modified: python/branches/p3yk/Lib/distutils/bcppcompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/bcppcompiler.py (original) +++ python/branches/p3yk/Lib/distutils/bcppcompiler.py Wed Jan 10 17:19:56 2007 @@ -115,7 +115,7 @@ # This needs to be compiled to a .res file -- do it now. try: self.spawn (["brcc32", "-fo", obj, src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue # the 'for' loop @@ -139,7 +139,7 @@ self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs + [src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -164,7 +164,7 @@ pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -298,7 +298,7 @@ self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: @@ -391,7 +391,7 @@ self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: print msg raise CompileError, msg Modified: python/branches/p3yk/Lib/distutils/command/register.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/register.py (original) +++ python/branches/p3yk/Lib/distutils/command/register.py Wed Jan 10 17:19:56 2007 @@ -284,11 +284,11 @@ data = '' try: result = opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if self.show_response: data = e.fp.read() result = e.code, e.msg - except urllib2.URLError, e: + except urllib2.URLError as e: result = 500, str(e) else: if self.show_response: Modified: python/branches/p3yk/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/sdist.py (original) +++ python/branches/p3yk/Lib/distutils/command/sdist.py Wed Jan 10 17:19:56 2007 @@ -333,7 +333,7 @@ try: self.filelist.process_template_line(line) - except DistutilsTemplateError, msg: + except DistutilsTemplateError as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) Modified: python/branches/p3yk/Lib/distutils/command/upload.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/upload.py (original) +++ python/branches/p3yk/Lib/distutils/command/upload.py Wed Jan 10 17:19:56 2007 @@ -184,7 +184,7 @@ http.putheader('Authorization', auth) http.endheaders() http.send(body) - except socket.error, e: + except socket.error as e: self.announce(str(e), log.ERROR) return Modified: python/branches/p3yk/Lib/distutils/core.py ============================================================================== --- python/branches/p3yk/Lib/distutils/core.py (original) +++ python/branches/p3yk/Lib/distutils/core.py Wed Jan 10 17:19:56 2007 @@ -110,7 +110,7 @@ # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) - except DistutilsSetupError, msg: + except DistutilsSetupError as msg: if 'name' not in attrs: raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) @@ -135,7 +135,7 @@ # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() - except DistutilsArgError, msg: + except DistutilsArgError as msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: @@ -151,7 +151,7 @@ dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" - except (IOError, os.error), exc: + except (IOError, os.error) as exc: error = grok_environment_error(exc) if DEBUG: @@ -161,7 +161,7 @@ raise SystemExit, error except (DistutilsError, - CCompilerError), msg: + CCompilerError) as msg: if DEBUG: raise else: Modified: python/branches/p3yk/Lib/distutils/cygwinccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/cygwinccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/cygwinccompiler.py Wed Jan 10 17:19:56 2007 @@ -142,13 +142,13 @@ # gcc needs '.res' and '.rc' compiled to object files !!! try: self.spawn(["windres", "-i", src, "-o", obj]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -379,7 +379,7 @@ s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, Modified: python/branches/p3yk/Lib/distutils/dir_util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/dir_util.py (original) +++ python/branches/p3yk/Lib/distutils/dir_util.py Wed Jan 10 17:19:56 2007 @@ -75,7 +75,7 @@ try: os.mkdir(head) created_dirs.append(head) - except OSError, exc: + except OSError as exc: raise DistutilsFileError, \ "could not create '%s': %s" % (head, exc[-1]) @@ -142,7 +142,8 @@ "cannot copy tree '%s': not a directory" % src try: names = os.listdir(src) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e if dry_run: names = [] else: @@ -209,7 +210,7 @@ abspath = os.path.abspath(cmd[1]) if abspath in _path_created: del _path_created[abspath] - except (IOError, OSError), exc: + except (IOError, OSError) as exc: log.warn(grok_environment_error( exc, "error removing %s: " % directory)) Modified: python/branches/p3yk/Lib/distutils/dist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/dist.py (original) +++ python/branches/p3yk/Lib/distutils/dist.py Wed Jan 10 17:19:56 2007 @@ -398,7 +398,7 @@ setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg # parse_config_files () @@ -515,7 +515,7 @@ # it takes. try: cmd_class = self.get_command_class(command) - except DistutilsModuleError, msg: + except DistutilsModuleError as msg: raise DistutilsArgError, msg # Require that the command class be derived from Command -- want @@ -917,7 +917,7 @@ raise DistutilsOptionError, \ ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) - except ValueError, msg: + except ValueError as msg: raise DistutilsOptionError, msg def reinitialize_command (self, command, reinit_subcommands=0): Modified: python/branches/p3yk/Lib/distutils/emxccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/emxccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/emxccompiler.py Wed Jan 10 17:19:56 2007 @@ -79,13 +79,13 @@ # gcc requires '.rc' compiled to binary ('.res') files !!! try: self.spawn(["rc", "-r", src]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def link (self, @@ -275,7 +275,7 @@ s = f.read() f.close() - except IOError, exc: + except IOError as exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, Modified: python/branches/p3yk/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/p3yk/Lib/distutils/fancy_getopt.py (original) +++ python/branches/p3yk/Lib/distutils/fancy_getopt.py Wed Jan 10 17:19:56 2007 @@ -256,7 +256,7 @@ short_opts = string.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) - except getopt.error, msg: + except getopt.error as msg: raise DistutilsArgError, msg for opt, val in opts: Modified: python/branches/p3yk/Lib/distutils/file_util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/file_util.py (original) +++ python/branches/p3yk/Lib/distutils/file_util.py Wed Jan 10 17:19:56 2007 @@ -32,27 +32,31 @@ try: try: fsrc = open(src, 'rb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not open '%s': %s" % (src, errstr) if os.path.exists(dst): try: os.unlink(dst) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not delete '%s': %s" % (dst, errstr) try: fdst = open(dst, 'wb') - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not create '%s': %s" % (dst, errstr) while 1: try: buf = fsrc.read(buffer_size) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not read from '%s': %s" % (src, errstr) @@ -61,7 +65,8 @@ try: fdst.write(buf) - except os.error, (errno, errstr): + except os.error as e: + (errno, errstr) = e raise DistutilsFileError, \ "could not write to '%s': %s" % (dst, errstr) @@ -146,7 +151,7 @@ import macostools try: macostools.copy(src, dst, 0, preserve_times) - except os.error, exc: + except os.error as exc: raise DistutilsFileError, \ "could not copy '%s' to '%s': %s" % (src, dst, exc[-1]) @@ -217,7 +222,8 @@ copy_it = 0 try: os.rename(src, dst) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e if num == errno.EXDEV: copy_it = 1 else: @@ -228,7 +234,8 @@ copy_file(src, dst) try: os.unlink(src) - except os.error, (num, msg): + except os.error as e: + (num, msg) = e try: os.unlink(dst) except os.error: Modified: python/branches/p3yk/Lib/distutils/msvccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/msvccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/msvccompiler.py Wed Jan 10 17:19:56 2007 @@ -129,7 +129,7 @@ self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") - except KeyError, exc: # + except KeyError as exc: # raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. @@ -371,7 +371,7 @@ try: self.spawn ([self.rc] + pp_opts + [output_opt] + [input_opt]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue elif ext in self._mc_extensions: @@ -400,7 +400,7 @@ self.spawn ([self.rc] + ["/fo" + obj] + [rc_file]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg continue else: @@ -414,7 +414,7 @@ self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg return objects @@ -440,7 +440,7 @@ pass # XXX what goes here? try: self.spawn ([self.lib] + lib_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: @@ -519,7 +519,7 @@ self.mkpath (os.path.dirname (output_filename)) try: self.spawn ([self.linker] + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: Modified: python/branches/p3yk/Lib/distutils/spawn.py ============================================================================== --- python/branches/p3yk/Lib/distutils/spawn.py (original) +++ python/branches/p3yk/Lib/distutils/spawn.py Wed Jan 10 17:19:56 2007 @@ -78,7 +78,7 @@ # spawn for NT requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -103,7 +103,7 @@ # spawnv for OS/2 EMX requires a full path to the .exe try: rc = os.spawnv(os.P_WAIT, executable, cmd) - except OSError, exc: + except OSError as exc: # this seems to happen when the command isn't found raise DistutilsExecError, \ "command '%s' failed: %s" % (cmd[0], exc[-1]) @@ -131,7 +131,7 @@ #print "cmd[0] =", cmd[0] #print "cmd =", cmd exec_fn(cmd[0], cmd) - except OSError, e: + except OSError as e: sys.stderr.write("unable to execute %s: %s\n" % (cmd[0], e.strerror)) os._exit(1) @@ -146,7 +146,7 @@ while 1: try: (pid, status) = os.waitpid(pid, 0) - except OSError, exc: + except OSError as exc: import errno if exc.errno == errno.EINTR: continue Modified: python/branches/p3yk/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk/Lib/distutils/sysconfig.py Wed Jan 10 17:19:56 2007 @@ -344,7 +344,7 @@ try: filename = get_makefile_filename() parse_makefile(filename, g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror @@ -355,7 +355,7 @@ try: filename = get_config_h_filename() parse_config_h(open(filename), g) - except IOError, msg: + except IOError as msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): my_msg = my_msg + " (%s)" % msg.strerror Modified: python/branches/p3yk/Lib/distutils/unixccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/unixccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/unixccompiler.py Wed Jan 10 17:19:56 2007 @@ -162,7 +162,7 @@ self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): @@ -172,7 +172,7 @@ try: self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise CompileError, msg def create_static_lib(self, objects, output_libname, @@ -196,7 +196,7 @@ if self.ranlib: try: self.spawn(self.ranlib + [output_filename]) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LibError, msg else: log.debug("skipping %s (up-to-date)", output_filename) @@ -250,7 +250,7 @@ linker = _darwin_compiler_fixup(linker, ld_args) self.spawn(linker + ld_args) - except DistutilsExecError, msg: + except DistutilsExecError as msg: raise LinkError, msg else: log.debug("skipping %s (up-to-date)", output_filename) Modified: python/branches/p3yk/Lib/distutils/util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/util.py (original) +++ python/branches/p3yk/Lib/distutils/util.py Wed Jan 10 17:19:56 2007 @@ -229,7 +229,7 @@ try: return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s) - except KeyError, var: + except KeyError as var: raise ValueError, "invalid variable '$%s'" % var # subst_vars () Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Wed Jan 10 17:19:56 2007 @@ -1604,8 +1604,8 @@ ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f >>> failure.test is test True @@ -1632,8 +1632,8 @@ >>> try: ... runner.run(test) - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: @@ -2141,8 +2141,8 @@ >>> case = DocTestCase(test) >>> try: ... case.debug() - ... except UnexpectedException, failure: - ... pass + ... except UnexpectedException as f: + ... failure = f The UnexpectedException contains the test, the example, and the original exception: @@ -2170,8 +2170,8 @@ >>> try: ... case.debug() - ... except DocTestFailure, failure: - ... pass + ... except DocTestFailure as f: + ... failure = f DocTestFailure objects provide access to the test: Modified: python/branches/p3yk/Lib/encodings/uu_codec.py ============================================================================== --- python/branches/p3yk/Lib/encodings/uu_codec.py (original) +++ python/branches/p3yk/Lib/encodings/uu_codec.py Wed Jan 10 17:19:56 2007 @@ -81,7 +81,7 @@ break try: data = a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 data = a2b_uu(s[:nbytes]) Modified: python/branches/p3yk/Lib/filecmp.py ============================================================================== --- python/branches/p3yk/Lib/filecmp.py (original) +++ python/branches/p3yk/Lib/filecmp.py Wed Jan 10 17:19:56 2007 @@ -148,12 +148,12 @@ ok = 1 try: a_stat = os.stat(a_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', a_path, ':', why[1] ok = 0 try: b_stat = os.stat(b_path) - except os.error, why: + except os.error as why: # print 'Can\'t stat', b_path, ':', why[1] ok = 0 Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Wed Jan 10 17:19:56 2007 @@ -119,7 +119,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -277,7 +277,7 @@ try: sock = socket.socket(af, socktype, proto) sock.bind(sa) - except socket.error, msg: + except socket.error as msg: if sock: sock.close() sock = None @@ -496,7 +496,7 @@ if dirname == '..': try: return self.voidcmd('CDUP') - except error_perm, msg: + except error_perm as msg: if msg.args[0][:3] != '500': raise elif dirname == '': Modified: python/branches/p3yk/Lib/hotshot/stones.py ============================================================================== --- python/branches/p3yk/Lib/hotshot/stones.py (original) +++ python/branches/p3yk/Lib/hotshot/stones.py Wed Jan 10 17:19:56 2007 @@ -19,7 +19,7 @@ stats.sort_stats('time', 'calls') try: stats.print_stats(20) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk/Lib/htmllib.py ============================================================================== --- python/branches/p3yk/Lib/htmllib.py (original) +++ python/branches/p3yk/Lib/htmllib.py Wed Jan 10 17:19:56 2007 @@ -463,7 +463,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) Modified: python/branches/p3yk/Lib/httplib.py ============================================================================== --- python/branches/p3yk/Lib/httplib.py (original) +++ python/branches/p3yk/Lib/httplib.py Wed Jan 10 17:19:56 2007 @@ -667,7 +667,7 @@ if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: @@ -713,7 +713,7 @@ data=str.read(blocksize) else: self.sock.sendall(str) - except socket.error, v: + except socket.error as v: if v[0] == 32: # Broken pipe self.close() raise @@ -868,7 +868,7 @@ try: self._send_request(method, url, body, headers) - except socket.error, v: + except socket.error as v: # trap 'Broken pipe' if we're allowed to automatically reconnect if v[0] != 32 or not self.auto_open: raise @@ -890,7 +890,7 @@ thelen=None try: thelen=str(len(body)) - except TypeError, te: + except TypeError as te: # If this is a file-like object, try to # fstat its file descriptor import os @@ -1019,7 +1019,7 @@ while True: try: buf = self._ssl.read(self._bufsize) - except socket.sslerror, err: + except socket.sslerror as err: if (err[0] == socket.SSL_ERROR_WANT_READ or err[0] == socket.SSL_ERROR_WANT_WRITE): continue @@ -1027,7 +1027,7 @@ or err[0] == socket.SSL_ERROR_EOF): break raise - except socket.error, err: + except socket.error as err: if err[0] == errno.EINTR: continue if err[0] == errno.EBADF: @@ -1215,7 +1215,7 @@ """ try: response = self._conn.getresponse() - except BadStatusLine, e: + except BadStatusLine as e: ### hmm. if getresponse() ever closes the socket on a bad request, ### then we are going to have problems with self.sock Modified: python/branches/p3yk/Lib/idlelib/ClassBrowser.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ClassBrowser.py (original) +++ python/branches/p3yk/Lib/idlelib/ClassBrowser.py Wed Jan 10 17:19:56 2007 @@ -94,7 +94,7 @@ return [] try: dict = pyclbr.readmodule_ex(name, [dir] + sys.path) - except ImportError, msg: + except ImportError as msg: return [] items = [] self.classes = {} Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/EditorWindow.py Wed Jan 10 17:19:56 2007 @@ -505,7 +505,7 @@ # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) - except (NameError, ImportError), msg: + except (NameError, ImportError) as msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: Modified: python/branches/p3yk/Lib/idlelib/GrepDialog.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/GrepDialog.py (original) +++ python/branches/p3yk/Lib/idlelib/GrepDialog.py Wed Jan 10 17:19:56 2007 @@ -82,7 +82,7 @@ for fn in list: try: f = open(fn) - except IOError, msg: + except IOError as msg: print msg continue lineno = 0 @@ -110,7 +110,7 @@ def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) - except os.error, msg: + except os.error as msg: print msg return [] list = [] Modified: python/branches/p3yk/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/IOBinding.py (original) +++ python/branches/p3yk/Lib/idlelib/IOBinding.py Wed Jan 10 17:19:56 2007 @@ -246,7 +246,7 @@ f = open(filename,'rb') chars = f.read() f.close() - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -289,7 +289,7 @@ # Next look for coding specification try: enc = coding_spec(chars) - except LookupError, name: + except LookupError as name: tkMessageBox.showerror( title="Error loading the file", message="The encoding '%s' is not known to this Python "\ @@ -380,7 +380,7 @@ f.flush() f.close() return True - except IOError, msg: + except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False @@ -400,7 +400,7 @@ try: enc = coding_spec(chars) failed = None - except LookupError, msg: + except LookupError as msg: failed = msg enc = None if enc: Modified: python/branches/p3yk/Lib/idlelib/PyShell.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PyShell.py (original) +++ python/branches/p3yk/Lib/idlelib/PyShell.py Wed Jan 10 17:19:56 2007 @@ -380,7 +380,7 @@ try: self.rpcclt = MyRPCClient(addr) break - except socket.error, err: + except socket.error as err: pass else: self.display_port_binding_error() @@ -389,7 +389,7 @@ self.rpcclt.listening_sock.settimeout(10) try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.rpcclt.register("stdin", self.tkconsole) @@ -423,7 +423,7 @@ self.spawn_subprocess() try: self.rpcclt.accept() - except socket.timeout, err: + except socket.timeout as err: self.display_no_subprocess_error() return None self.transfer_path() @@ -1324,7 +1324,7 @@ startup = False try: opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:") - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.stderr.write(usage_msg) sys.exit(2) Modified: python/branches/p3yk/Lib/idlelib/ScriptBinding.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ScriptBinding.py (original) +++ python/branches/p3yk/Lib/idlelib/ScriptBinding.py Wed Jan 10 17:19:56 2007 @@ -66,13 +66,13 @@ f = open(filename, 'r') try: tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: msgtxt, (lineno, start) = msg self.editwin.gotoline(lineno) self.errorbox("Tabnanny Tokenizing Error", "Token Error: %s" % msgtxt) return False - except tabnanny.NannyNag, nag: + except tabnanny.NannyNag as nag: # The error messages from tabnanny are too confusing... self.editwin.gotoline(nag.get_lineno()) self.errorbox("Tab/space error", indent_message) @@ -97,7 +97,7 @@ try: # If successful, return the compiled code return compile(source, filename, "exec") - except (SyntaxError, OverflowError), err: + except (SyntaxError, OverflowError) as err: try: msg, (errorfilename, lineno, offset, line) = err if not errorfilename: Modified: python/branches/p3yk/Lib/idlelib/SearchEngine.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/SearchEngine.py (original) +++ python/branches/p3yk/Lib/idlelib/SearchEngine.py Wed Jan 10 17:19:56 2007 @@ -66,7 +66,7 @@ flags = flags | re.IGNORECASE try: prog = re.compile(pat, flags) - except re.error, what: + except re.error as what: try: msg, col = what except: Modified: python/branches/p3yk/Lib/idlelib/run.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/run.py (original) +++ python/branches/p3yk/Lib/idlelib/run.py Wed Jan 10 17:19:56 2007 @@ -114,7 +114,7 @@ try: server = MyRPCServer(address, MyHandler) break - except socket.error, err: + except socket.error as err: print>>sys.__stderr__,"IDLE Subprocess: socket error: "\ + err[1] + ", retrying...." else: Modified: python/branches/p3yk/Lib/imaplib.py ============================================================================== --- python/branches/p3yk/Lib/imaplib.py (original) +++ python/branches/p3yk/Lib/imaplib.py Wed Jan 10 17:19:56 2007 @@ -845,7 +845,7 @@ try: self.send('%s%s' % (data, CRLF)) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if literal is None: @@ -870,7 +870,7 @@ try: self.send(literal) self.send(CRLF) - except (socket.error, OSError), val: + except (socket.error, OSError) as val: raise self.abort('socket error: %s' % val) if not literator: @@ -883,9 +883,9 @@ self._check_bye() try: typ, data = self._get_tagged_response(tag) - except self.abort, val: + except self.abort as val: raise self.abort('command: %s => %s' % (name, val)) - except self.error, val: + except self.error as val: raise self.error('command: %s => %s' % (name, val)) self._check_bye() if typ == 'BAD': @@ -984,7 +984,7 @@ try: self._get_response() - except self.abort, val: + except self.abort as val: if __debug__: if self.debug >= 1: self.print_log() @@ -1402,7 +1402,7 @@ try: optlist, args = getopt.getopt(sys.argv[1:], 'd:s:') - except getopt.error, val: + except getopt.error as val: optlist, args = (), () stream_command = None Modified: python/branches/p3yk/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Tkinter.py (original) +++ python/branches/p3yk/Lib/lib-tk/Tkinter.py Wed Jan 10 17:19:56 2007 @@ -85,7 +85,7 @@ for c in _flatten(cnfs): try: cnf.update(c) - except (AttributeError, TypeError), msg: + except (AttributeError, TypeError) as msg: print "_cnfmerge: fallback due to:", msg for k, v in c.items(): cnf[k] = v @@ -1401,7 +1401,7 @@ if self.subst: args = self.subst(*args) return self.func(*args) - except SystemExit, msg: + except SystemExit as msg: raise SystemExit, msg except: self.widget._report_exception() Modified: python/branches/p3yk/Lib/linecache.py ============================================================================== --- python/branches/p3yk/Lib/linecache.py (original) +++ python/branches/p3yk/Lib/linecache.py Wed Jan 10 17:19:56 2007 @@ -78,7 +78,7 @@ fullname = filename try: stat = os.stat(fullname) - except os.error, msg: + except os.error as msg: basename = os.path.split(filename)[1] # Try for a __loader__, if available @@ -128,7 +128,7 @@ fp = open(fullname, 'rU') lines = fp.readlines() fp.close() - except IOError, msg: + except IOError as msg: ## print '*** Cannot open', fullname, ':', msg return [] size, mtime = stat.st_size, stat.st_mtime Modified: python/branches/p3yk/Lib/logging/config.py ============================================================================== --- python/branches/p3yk/Lib/logging/config.py (original) +++ python/branches/p3yk/Lib/logging/config.py Wed Jan 10 17:19:56 2007 @@ -288,7 +288,7 @@ except: traceback.print_exc() os.remove(file) - except socket.error, e: + except socket.error as e: if type(e.args) != types.TupleType: raise else: Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Wed Jan 10 17:19:56 2007 @@ -258,7 +258,7 @@ os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) - except OSError, e: + except OSError as e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' @@ -280,7 +280,7 @@ self.remove(key) except KeyError: pass - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -437,12 +437,12 @@ path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: Maildir._count += 1 try: return _create_carefully(path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise else: @@ -495,7 +495,7 @@ Mailbox.__init__(self, path, factory, create) try: f = open(self._path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: if create: f = open(self._path, 'wb+') @@ -605,7 +605,7 @@ self._file.close() try: os.rename(new_file.name, self._path) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) @@ -837,7 +837,7 @@ path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -859,7 +859,7 @@ path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -885,7 +885,7 @@ f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -912,7 +912,7 @@ f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -932,7 +932,7 @@ """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: @@ -1843,7 +1843,7 @@ if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except IOError, e: + except IOError as e: if e.errno in (errno.EAGAIN, errno.EACCES): raise ExternalClashError('lockf: lock unavailable: %s' % f.name) @@ -1853,7 +1853,7 @@ try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() - except IOError, e: + except IOError as e: if e.errno == errno.EACCES: return # Without write access, just skip dotlocking. else: @@ -1866,7 +1866,7 @@ else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(pre_lock.name) Modified: python/branches/p3yk/Lib/mhlib.py ============================================================================== --- python/branches/p3yk/Lib/mhlib.py (original) +++ python/branches/p3yk/Lib/mhlib.py Wed Jan 10 17:19:56 2007 @@ -370,7 +370,7 @@ count = len(all) try: anchor = self._parseindex(head, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not head in seqs: if not msg: @@ -407,7 +407,7 @@ # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) - except Error, msg: + except Error as msg: seqs = self.getsequences() if not seq in seqs: if not msg: @@ -471,7 +471,7 @@ pass try: os.rename(path, commapath) - except os.error, msg: + except os.error as msg: errors.append(msg) else: deleted.append(n) @@ -499,7 +499,7 @@ try: shutil.copy2(path, topath) os.unlink(path) - except (IOError, os.error), msg: + except (IOError, os.error) as msg: errors.append(msg) try: os.unlink(topath) @@ -989,7 +989,7 @@ 'all'): try: do('f.parsesequence(%r)' % (seq,)) - except Error, msg: + except Error as msg: print "Error:", msg stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read() list = map(int, stuff.split()) Modified: python/branches/p3yk/Lib/mimetypes.py ============================================================================== --- python/branches/p3yk/Lib/mimetypes.py (original) +++ python/branches/p3yk/Lib/mimetypes.py Wed Jan 10 17:19:56 2007 @@ -510,7 +510,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'hle', ['help', 'lenient', 'extension']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) strict = 1 Modified: python/branches/p3yk/Lib/modulefinder.py ============================================================================== --- python/branches/p3yk/Lib/modulefinder.py (original) +++ python/branches/p3yk/Lib/modulefinder.py Wed Jan 10 17:19:56 2007 @@ -317,7 +317,7 @@ return try: self.import_hook(name, caller, level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) self._add_badmodule(name, caller) else: @@ -328,7 +328,7 @@ continue try: self.import_hook(name, caller, [sub], level=level) - except ImportError, msg: + except ImportError as msg: self.msg(2, "ImportError:", str(msg)) fullname = name + "." + sub self._add_badmodule(fullname, caller) @@ -602,7 +602,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") - except getopt.error, msg: + except getopt.error as msg: print msg return Modified: python/branches/p3yk/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk/Lib/msilib/__init__.py (original) +++ python/branches/p3yk/Lib/msilib/__init__.py Wed Jan 10 17:19:56 2007 @@ -111,7 +111,7 @@ raise TypeError, "Unsupported type %s" % field.__class__.__name__ try: v.Modify(MSIMODIFY_INSERT, r) - except Exception, e: + except Exception as e: raise MSIError("Could not insert "+repr(values)+" into "+table) r.ClearData() Modified: python/branches/p3yk/Lib/nntplib.py ============================================================================== --- python/branches/p3yk/Lib/nntplib.py (original) +++ python/branches/p3yk/Lib/nntplib.py Wed Jan 10 17:19:56 2007 @@ -127,7 +127,7 @@ except NNTPPermanentError: # error 500, probably 'not implemented' pass - except NNTPTemporaryError, e: + except NNTPTemporaryError as e: if user and e.response[:3] == '480': # Need authorization before 'mode reader' readermode_afterauth = 1 Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Wed Jan 10 17:19:56 2007 @@ -1376,7 +1376,7 @@ try: stop = self._process_args(largs, rargs, values) - except (BadOptionError, OptionValueError), err: + except (BadOptionError, OptionValueError) as err: self.error(str(err)) args = largs + rargs Modified: python/branches/p3yk/Lib/os.py ============================================================================== --- python/branches/p3yk/Lib/os.py (original) +++ python/branches/p3yk/Lib/os.py Wed Jan 10 17:19:56 2007 @@ -163,7 +163,7 @@ if head and tail and not path.exists(head): try: makedirs(head, mode) - except OSError, e: + except OSError as e: # be happy if someone already created the path if e.errno != EEXIST: raise @@ -284,7 +284,7 @@ # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) - except error, err: + except error as err: if onerror is not None: onerror(err) return @@ -390,7 +390,7 @@ fullname = path.join(dir, file) try: func(fullname, *argrest) - except error, e: + except error as e: tb = sys.exc_info()[2] if (e.errno != ENOENT and e.errno != ENOTDIR and saved_exc is None): Modified: python/branches/p3yk/Lib/pdb.py ============================================================================== --- python/branches/p3yk/Lib/pdb.py (original) +++ python/branches/p3yk/Lib/pdb.py Wed Jan 10 17:19:56 2007 @@ -330,7 +330,7 @@ arg = arg[colon+1:].lstrip() try: lineno = int(arg) - except ValueError, msg: + except ValueError as msg: print >>self.stdout, '*** Bad lineno:', arg return else: @@ -618,7 +618,7 @@ self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) - except ValueError, e: + except ValueError as e: print >>self.stdout, '*** Jump failed:', e do_j = do_jump Modified: python/branches/p3yk/Lib/pickle.py ============================================================================== --- python/branches/p3yk/Lib/pickle.py (original) +++ python/branches/p3yk/Lib/pickle.py Wed Jan 10 17:19:56 2007 @@ -816,7 +816,7 @@ while 1: key = read(1) dispatch[key](self) - except _Stop, stopinst: + except _Stop as stopinst: return stopinst.value # Return largest index k such that self.stack[k] is self.mark. @@ -1018,7 +1018,7 @@ if not instantiated: try: value = klass(*args) - except TypeError, err: + except TypeError as err: raise TypeError, "in constructor for %s: %s" % ( klass.__name__, str(err)), sys.exc_info()[2] self.append(value) Modified: python/branches/p3yk/Lib/pkgutil.py ============================================================================== --- python/branches/p3yk/Lib/pkgutil.py (original) +++ python/branches/p3yk/Lib/pkgutil.py Wed Jan 10 17:19:56 2007 @@ -532,7 +532,7 @@ if os.path.isfile(pkgfile): try: f = open(pkgfile) - except IOError, msg: + except IOError as msg: sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg)) else: Modified: python/branches/p3yk/Lib/plat-irix5/torgb.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/torgb.py (original) +++ python/branches/p3yk/Lib/plat-irix5/torgb.py Wed Jan 10 17:19:56 2007 @@ -80,7 +80,7 @@ fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk/Lib/plat-irix6/torgb.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/torgb.py (original) +++ python/branches/p3yk/Lib/plat-irix6/torgb.py Wed Jan 10 17:19:56 2007 @@ -80,7 +80,7 @@ fname = filename try: ftype = imghdr.what(fname) - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/EasyDialogs.py (original) +++ python/branches/p3yk/Lib/plat-mac/EasyDialogs.py Wed Jan 10 17:19:56 2007 @@ -651,7 +651,7 @@ try: rr = Nav.NavChooseFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -704,7 +704,7 @@ try: rr = Nav.NavPutFile(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None @@ -764,7 +764,7 @@ try: rr = Nav.NavChooseFolder(args) good = 1 - except Nav.error, arg: + except Nav.error as arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None Modified: python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py (original) +++ python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py Wed Jan 10 17:19:56 2007 @@ -70,7 +70,7 @@ msg = "High Level Event: %r %r" % (code(message), code(h | (v<<16))) try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: print 'AE error: ', err print 'in', msg traceback.print_exc() Modified: python/branches/p3yk/Lib/plat-mac/aetools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aetools.py (original) +++ python/branches/p3yk/Lib/plat-mac/aetools.py Wed Jan 10 17:19:56 2007 @@ -57,7 +57,7 @@ def missed(ae): try: desc = ae.AEGetAttributeDesc('miss', 'keyw') - except AE.Error, msg: + except AE.Error as msg: return None return desc.data @@ -86,7 +86,7 @@ for key in aekeywords: try: desc = ae.AEGetAttributeDesc(key, '****') - except (AE.Error, MacOS.Error), msg: + except (AE.Error, MacOS.Error) as msg: if msg[0] != -1701 and msg[0] != -1704: raise continue Modified: python/branches/p3yk/Lib/plat-mac/applesingle.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/applesingle.py (original) +++ python/branches/p3yk/Lib/plat-mac/applesingle.py Wed Jan 10 17:19:56 2007 @@ -48,7 +48,7 @@ header = fileobj.read(AS_HEADER_LENGTH) try: magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack header error: %s" % (arg,) if verbose: print 'Magic: 0x%8.8x' % (magic,) @@ -65,7 +65,7 @@ for hdr in headers: try: restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) - except ValueError, arg: + except ValueError as arg: raise Error, "Unpack entry error: %s" % (arg,) if verbose: print "Fork %d, offset %d, length %d" % (restype, offset, length) Modified: python/branches/p3yk/Lib/plat-mac/argvemulator.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/argvemulator.py (original) +++ python/branches/p3yk/Lib/plat-mac/argvemulator.py Wed Jan 10 17:19:56 2007 @@ -52,7 +52,7 @@ if what == kHighLevelEvent: try: AE.AEProcessAppleEvent(event) - except AE.Error, err: + except AE.Error as err: msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16))) print 'AE error: ', err print 'in', msg @@ -77,7 +77,7 @@ fsref = alias.FSResolveAlias(None)[0] pathname = fsref.as_pathname() sys.argv.append(pathname) - except Exception, e: + except Exception as e: print "argvemulator.py warning: can't unpack an open document event" import traceback traceback.print_exc() Modified: python/branches/p3yk/Lib/plat-mac/buildtools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/buildtools.py (original) +++ python/branches/p3yk/Lib/plat-mac/buildtools.py Wed Jan 10 17:19:56 2007 @@ -78,7 +78,7 @@ fp.close() try: code = compile(text + '\n', filename, "exec") - except SyntaxError, arg: + except SyntaxError as arg: raise BuildError, "Syntax error in script %s: %s" % (filename, arg) except EOFError: raise BuildError, "End-of-file in script %s" % (filename,) Modified: python/branches/p3yk/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/bundlebuilder.py (original) +++ python/branches/p3yk/Lib/plat-mac/bundlebuilder.py Wed Jan 10 17:19:56 2007 @@ -764,7 +764,7 @@ directory. Don't moan if any path element already exists.""" try: os.makedirs(dir) - except OSError, why: + except OSError as why: if why.errno != errno.EEXIST: raise Modified: python/branches/p3yk/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/p3yk/Lib/plat-mac/gensuitemodule.py Wed Jan 10 17:19:56 2007 @@ -114,7 +114,7 @@ try: processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) - except MacOS.Error, arg: + except MacOS.Error as arg: print "Error getting terminology:", arg print "Retry, manually parsing resources" processfile_fromresource(filename, edit_modnames=edit_modnames, @@ -190,7 +190,7 @@ print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname) try: aedescobj, launched = OSATerminology.GetAppTerminology(fullname) - except MacOS.Error, arg: + except MacOS.Error as arg: if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound if verbose: print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually" @@ -244,7 +244,7 @@ talker = aetools.TalkTo(cr) try: talker._start() - except (MacOS.Error, aetools.Error), arg: + except (MacOS.Error, aetools.Error) as arg: if verbose: print >>verbose, 'Warning: start() failed, continuing anyway:', arg reply = talker.send("ascr", "gdte") Modified: python/branches/p3yk/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/macresource.py (original) +++ python/branches/p3yk/Lib/plat-mac/macresource.py Wed Jan 10 17:19:56 2007 @@ -76,14 +76,14 @@ AppleSingle file""" try: refno = Res.FSpOpenResFile(pathname, 1) - except Res.Error, arg: + except Res.Error as 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: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise @@ -103,14 +103,14 @@ try: refno = Res.FSpOpenResFile(pathname, 1) Res.CloseResFile(refno) - except Res.Error, arg: + except Res.Error as 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: + except Res.Error as arg: if arg[0] != -199: # -199 is "bad resource map" raise Modified: python/branches/p3yk/Lib/plat-mac/pimp.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/pimp.py (original) +++ python/branches/p3yk/Lib/plat-mac/pimp.py Wed Jan 10 17:19:56 2007 @@ -76,7 +76,7 @@ url = DEFAULT_PIMPDATABASE_FMT % (PIMP_VERSION, status, pyvers, osname, rel, machine) try: urllib2.urlopen(url) - except urllib2.HTTPError, arg: + except urllib2.HTTPError as arg: pass else: break @@ -589,13 +589,13 @@ installTest = self._dict['Install-test'].strip() + '\n' try: exec(installTest, namespace) - except ImportError, arg: + except ImportError as arg: return "no", str(arg) - except _scriptExc_NotInstalled, arg: + except _scriptExc_NotInstalled as arg: return "no", str(arg) - except _scriptExc_OldInstalled, arg: + except _scriptExc_OldInstalled as arg: return "old", str(arg) - except _scriptExc_BadInstalled, arg: + except _scriptExc_BadInstalled as arg: return "bad", str(arg) except: sys.stderr.write("-------------------------------------\n") Modified: python/branches/p3yk/Lib/plat-mac/terminalcommand.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/terminalcommand.py (original) +++ python/branches/p3yk/Lib/plat-mac/terminalcommand.py Wed Jan 10 17:19:56 2007 @@ -35,7 +35,7 @@ try: theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout) - except AE.Error, why: + except AE.Error as why: if why[0] != -600: # Terminal.app not yet running raise os.system(START_TERMINAL) Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Wed Jan 10 17:19:56 2007 @@ -404,10 +404,10 @@ raise os.error,'command failed' # XXX How can I supress shell errors from being written # to stderr ? - except os.error,why: + except os.error as why: #print 'Command %s failed: %s' % (cmd,why) continue - except IOError,why: + except IOError as why: #print 'Command %s failed: %s' % (cmd,why) continue else: Modified: python/branches/p3yk/Lib/poplib.py ============================================================================== --- python/branches/p3yk/Lib/poplib.py (original) +++ python/branches/p3yk/Lib/poplib.py Wed Jan 10 17:19:56 2007 @@ -86,7 +86,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -262,7 +262,7 @@ """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.file.close() self.sock.close() @@ -347,7 +347,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None @@ -399,7 +399,7 @@ """Signoff: commit changes on server, unlock mailbox, close connection.""" try: resp = self._shortcmd('QUIT') - except error_proto, val: + except error_proto as val: resp = val self.sock.close() del self.sslobj, self.sock Modified: python/branches/p3yk/Lib/pstats.py ============================================================================== --- python/branches/p3yk/Lib/pstats.py (original) +++ python/branches/p3yk/Lib/pstats.py Wed Jan 10 17:19:56 2007 @@ -618,7 +618,7 @@ if line: try: self.stats = Stats(line) - except IOError, args: + except IOError as args: print >> self.stream, args[1] return self.prompt = line + "% " Modified: python/branches/p3yk/Lib/pty.py ============================================================================== --- python/branches/p3yk/Lib/pty.py (original) +++ python/branches/p3yk/Lib/pty.py Wed Jan 10 17:19:56 2007 @@ -56,7 +56,7 @@ else: try: tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0) - except IOError, msg: + except IOError as msg: raise os.error, msg return master_fd, tty_name for x in 'pqrstuvwxyzPQRST': Modified: python/branches/p3yk/Lib/py_compile.py ============================================================================== --- python/branches/p3yk/Lib/py_compile.py (original) +++ python/branches/p3yk/Lib/py_compile.py Wed Jan 10 17:19:56 2007 @@ -123,7 +123,7 @@ codestring = codestring + '\n' try: codeobject = __builtin__.compile(codestring, dfile or file,'exec') - except Exception,err: + except Exception as err: py_exc = PyCompileError(err.__class__,err.args,dfile or file) if doraise: raise py_exc @@ -157,7 +157,7 @@ for filename in args: try: compile(filename, doraise=True) - except PyCompileError,err: + except PyCompileError as err: sys.stderr.write(err.msg) if __name__ == "__main__": Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Wed Jan 10 17:19:56 2007 @@ -1479,7 +1479,7 @@ object = type(object) desc += ' object' pager(title % desc + '\n\n' + text.document(object, name)) - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedoc(thing, forceload=0): @@ -1491,7 +1491,7 @@ file.write(page) file.close() print 'wrote', name + '.html' - except (ImportError, ErrorDuringImport), value: + except (ImportError, ErrorDuringImport) as value: print value def writedocs(dir, pkgpath='', done=None): @@ -1920,7 +1920,7 @@ if path and path != '.': try: obj = locate(path, forceload=1) - except ErrorDuringImport, value: + except ErrorDuringImport as value: self.send_document(path, html.escape(str(value))) return if obj: @@ -2223,7 +2223,7 @@ writedoc(arg) else: help.help(arg) - except ErrorDuringImport, value: + except ErrorDuringImport as value: print value except (getopt.error, BadUsage): Modified: python/branches/p3yk/Lib/quopri.py ============================================================================== --- python/branches/p3yk/Lib/quopri.py (original) +++ python/branches/p3yk/Lib/quopri.py Wed Jan 10 17:19:56 2007 @@ -194,7 +194,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." @@ -218,7 +218,7 @@ else: try: fp = open(file) - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue Modified: python/branches/p3yk/Lib/re.py ============================================================================== --- python/branches/p3yk/Lib/re.py (original) +++ python/branches/p3yk/Lib/re.py Wed Jan 10 17:19:56 2007 @@ -229,7 +229,7 @@ raise TypeError, "first argument must be string or compiled pattern" try: p = sre_compile.compile(pattern, flags) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache) >= _MAXCACHE: _cache.clear() @@ -244,7 +244,7 @@ repl, pattern = key try: p = sre_parse.parse_template(repl, pattern) - except error, v: + except error as v: raise error, v # invalid expression if len(_cache_repl) >= _MAXCACHE: _cache_repl.clear() Modified: python/branches/p3yk/Lib/rexec.py ============================================================================== --- python/branches/p3yk/Lib/rexec.py (original) +++ python/branches/p3yk/Lib/rexec.py Wed Jan 10 17:19:56 2007 @@ -551,7 +551,7 @@ if args and args[0] != '-': try: fp = open(args[0]) - except IOError, msg: + except IOError as msg: print "%s: can't open file %r" % (sys.argv[0], args[0]) return 1 if fp.isatty(): @@ -566,7 +566,7 @@ r.s_apply(code.InteractiveConsole.runcode, (self, co)) try: RestrictedConsole(r.modules['__main__'].__dict__).interact() - except SystemExit, n: + except SystemExit as n: return n else: text = fp.read() @@ -574,7 +574,7 @@ c = compile(text, fp.name, 'exec') try: r.s_exec(c) - except SystemExit, n: + except SystemExit as n: return n except: traceback.print_exc() Modified: python/branches/p3yk/Lib/sgmllib.py ============================================================================== --- python/branches/p3yk/Lib/sgmllib.py (original) +++ python/branches/p3yk/Lib/sgmllib.py Wed Jan 10 17:19:56 2007 @@ -530,7 +530,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) Modified: python/branches/p3yk/Lib/shutil.py ============================================================================== --- python/branches/p3yk/Lib/shutil.py (original) +++ python/branches/p3yk/Lib/shutil.py Wed Jan 10 17:19:56 2007 @@ -121,18 +121,18 @@ else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? - except (IOError, os.error), why: + except (IOError, os.error) as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files - except Error, err: + except Error as err: errors.extend(err.args[0]) try: copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass - except OSError, why: + except OSError as why: errors.extend((src, dst, str(why))) if errors: raise Error, errors @@ -157,7 +157,7 @@ names = [] try: names = os.listdir(path) - except os.error, err: + except os.error as err: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) @@ -170,7 +170,7 @@ else: try: os.remove(fullname) - except os.error, err: + except os.error as err: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) Modified: python/branches/p3yk/Lib/site.py ============================================================================== --- python/branches/p3yk/Lib/site.py (original) +++ python/branches/p3yk/Lib/site.py Wed Jan 10 17:19:56 2007 @@ -391,7 +391,7 @@ import sitecustomize except ImportError: pass - except Exception, err: + except Exception as err: if os.environ.get("PYTHONVERBOSE"): raise sys.stderr.write( Modified: python/branches/p3yk/Lib/smtpd.py ============================================================================== --- python/branches/p3yk/Lib/smtpd.py (original) +++ python/branches/p3yk/Lib/smtpd.py Wed Jan 10 17:19:56 2007 @@ -357,10 +357,10 @@ refused = s.sendmail(mailfrom, rcpttos, data) finally: s.quit() - except smtplib.SMTPRecipientsRefused, e: + except smtplib.SMTPRecipientsRefused as e: print >> DEBUGSTREAM, 'got SMTPRecipientsRefused' refused = e.recipients - except (socket.error, smtplib.SMTPException), e: + except (socket.error, smtplib.SMTPException) as e: print >> DEBUGSTREAM, 'got', e.__class__ # All recipients were refused. If the exception had an associated # error code, use it. Otherwise,fake it with a non-triggering @@ -464,7 +464,7 @@ opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) - except getopt.error, e: + except getopt.error as e: usage(1, e) options = Options() @@ -528,7 +528,7 @@ nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) - except OSError, e: + except OSError as e: if e.errno != errno.EPERM: raise print >> sys.stderr, \ 'Cannot setuid "nobody"; try running with -n option.' Modified: python/branches/p3yk/Lib/smtplib.py ============================================================================== --- python/branches/p3yk/Lib/smtplib.py (original) +++ python/branches/p3yk/Lib/smtplib.py Wed Jan 10 17:19:56 2007 @@ -306,7 +306,7 @@ af, socktype, proto, canonname, sa = res try: self._get_socket(af,socktype,proto,sa) - except socket.error, msg: + except socket.error as msg: if self.debuglevel > 0: print>>stderr, 'connect fail:', msg if self.sock: self.sock.close() Modified: python/branches/p3yk/Lib/sqlite3/test/dbapi.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/dbapi.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/dbapi.py Wed Jan 10 17:19:56 2007 @@ -326,7 +326,7 @@ self.fail("should have raised a TypeError") except TypeError: return - except Exception, e: + except Exception as e: print "raised", e.__class__ self.fail("raised wrong exception.") Modified: python/branches/p3yk/Lib/sqlite3/test/hooks.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/hooks.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/hooks.py Wed Jan 10 17:19:56 2007 @@ -36,7 +36,7 @@ try: con.create_collation("X", 42) self.fail("should have raised a TypeError") - except TypeError, e: + except TypeError as e: self.failUnlessEqual(e.args[0], "parameter must be callable") def CheckCreateCollationNotAscii(self): @@ -44,7 +44,7 @@ try: con.create_collation("coll?", cmp) self.fail("should have raised a ProgrammingError") - except sqlite.ProgrammingError, e: + except sqlite.ProgrammingError as e: pass def CheckCollationIsUsed(self): @@ -73,7 +73,7 @@ try: result = con.execute(sql).fetchall() self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0].lower(), "no such collation sequence: mycoll") def CheckCollationRegisterTwice(self): @@ -101,7 +101,7 @@ try: con.execute("select 'a' as x union select 'b' as x order by x collate mycoll") self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: if not e.args[0].startswith("no such collation sequence"): self.fail("wrong OperationalError raised") Modified: python/branches/p3yk/Lib/sqlite3/test/userfunctions.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/userfunctions.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/userfunctions.py Wed Jan 10 17:19:56 2007 @@ -205,7 +205,7 @@ cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): @@ -279,7 +279,7 @@ try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") - except AttributeError, e: + except AttributeError as e: self.failUnlessEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'") def CheckAggrNoFinalize(self): @@ -288,7 +288,7 @@ cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): @@ -297,7 +297,7 @@ cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): @@ -306,7 +306,7 @@ cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): @@ -315,7 +315,7 @@ cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") - except sqlite.OperationalError, e: + except sqlite.OperationalError as e: self.failUnlessEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): @@ -384,7 +384,7 @@ def CheckTableAccess(self): try: self.con.execute("select * from t2") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return @@ -393,7 +393,7 @@ def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") - except sqlite.DatabaseError, e: + except sqlite.DatabaseError as e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Wed Jan 10 17:19:56 2007 @@ -792,7 +792,7 @@ env, cwd, startupinfo) - except pywintypes.error, e: + except pywintypes.error as e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but @@ -1190,7 +1190,7 @@ print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" Modified: python/branches/p3yk/Lib/tabnanny.py ============================================================================== --- python/branches/p3yk/Lib/tabnanny.py (original) +++ python/branches/p3yk/Lib/tabnanny.py Wed Jan 10 17:19:56 2007 @@ -43,7 +43,7 @@ global verbose, filename_only try: opts, args = getopt.getopt(sys.argv[1:], "qv") - except getopt.error, msg: + except getopt.error as msg: errprint(msg) return for o, a in opts: @@ -95,7 +95,7 @@ try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return @@ -105,15 +105,15 @@ try: process_tokens(tokenize.generate_tokens(f.readline)) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (file, msg)) return - except IndentationError, msg: + except IndentationError as msg: errprint("%r: Indentation Error: %s" % (file, msg)) return - except NannyNag, nag: + except NannyNag as nag: badline = nag.get_lineno() line = nag.get_line() if verbose: Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Wed Jan 10 17:19:56 2007 @@ -1540,7 +1540,7 @@ self.chown(tarinfo, path) self.utime(tarinfo, path) self.chmod(tarinfo, path) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1565,7 +1565,7 @@ try: self._extract_member(tarinfo, os.path.join(path, tarinfo.name)) - except EnvironmentError, e: + except EnvironmentError as e: if self.errorlevel > 0: raise else: @@ -1573,7 +1573,7 @@ self._dbg(1, "tarfile: %s" % e.strerror) else: self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) - except ExtractError, e: + except ExtractError as e: if self.errorlevel > 1: raise else: @@ -1681,7 +1681,7 @@ """ try: os.mkdir(targetpath) - except EnvironmentError, e: + except EnvironmentError as e: if e.errno != errno.EEXIST: raise @@ -1745,11 +1745,11 @@ try: self._extract_member(self.getmember(linkpath), targetpath) - except (EnvironmentError, KeyError), e: + except (EnvironmentError, KeyError) as e: linkpath = os.path.normpath(linkpath) try: shutil.copy2(linkpath, targetpath) - except EnvironmentError, e: + except EnvironmentError as e: raise IOError("link could not be created") def chown(self, tarinfo, targetpath): @@ -1777,7 +1777,7 @@ else: if sys.platform != "os2emx": os.chown(targetpath, u, g) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change owner") def chmod(self, tarinfo, targetpath): @@ -1786,7 +1786,7 @@ if hasattr(os, 'chmod'): try: os.chmod(targetpath, tarinfo.mode) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change mode") def utime(self, tarinfo, targetpath): @@ -1800,7 +1800,7 @@ return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) - except EnvironmentError, e: + except EnvironmentError as e: raise ExtractError("could not change modification time") #-------------------------------------------------------------------------- @@ -1833,7 +1833,7 @@ tarinfo = self.proc_member(tarinfo) - except HeaderError, e: + except HeaderError as e: if self.ignore_zeros: self._dbg(2, "0x%X: %s" % (self.offset, e)) self.offset += BLOCKSIZE Modified: python/branches/p3yk/Lib/telnetlib.py ============================================================================== --- python/branches/p3yk/Lib/telnetlib.py (original) +++ python/branches/p3yk/Lib/telnetlib.py Wed Jan 10 17:19:56 2007 @@ -227,7 +227,7 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error, msg: + except socket.error as msg: if self.sock: self.sock.close() self.sock = None Modified: python/branches/p3yk/Lib/tempfile.py ============================================================================== --- python/branches/p3yk/Lib/tempfile.py (original) +++ python/branches/p3yk/Lib/tempfile.py Wed Jan 10 17:19:56 2007 @@ -201,7 +201,7 @@ _os.unlink(filename) del fp, fd return dir - except (OSError, IOError), e: + except (OSError, IOError) as e: if e[0] != _errno.EEXIST: break # no point trying more names in this directory pass @@ -236,7 +236,7 @@ fd = _os.open(file, flags, 0600) _set_cloexec(fd) return (fd, _os.path.abspath(file)) - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise @@ -327,7 +327,7 @@ try: _os.mkdir(file, 0700) return file - except OSError, e: + except OSError as e: if e.errno == _errno.EEXIST: continue # try again raise Modified: python/branches/p3yk/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk/Lib/test/pickletester.py (original) +++ python/branches/p3yk/Lib/test/pickletester.py Wed Jan 10 17:19:56 2007 @@ -585,7 +585,7 @@ badpickle = pickle.PROTO + chr(oob) + build_none try: self.loads(badpickle) - except ValueError, detail: + except ValueError as detail: self.failUnless(str(detail).startswith( "unsupported pickle protocol")) else: Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Wed Jan 10 17:19:56 2007 @@ -211,7 +211,7 @@ 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', ]) - except getopt.error, msg: + except getopt.error as msg: usage(2, msg) # Defaults @@ -556,19 +556,19 @@ dash_R(the_module, test, indirect_test, huntrleaks) finally: sys.stdout = save_stdout - except test_support.ResourceDenied, msg: + except test_support.ResourceDenied as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -2 - except (ImportError, test_support.TestSkipped), msg: + except (ImportError, test_support.TestSkipped) as msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() return -1 except KeyboardInterrupt: raise - except test_support.TestFailed, msg: + except test_support.TestFailed as msg: print "test", test, "failed --", msg sys.stdout.flush() return 0 @@ -640,7 +640,7 @@ print "%r left behind %s %r" % (testname, kind, name) try: nuker(name) - except Exception, msg: + except Exception as msg: print >> sys.stderr, ("%r left behind %s %r and it couldn't be " "removed: %s" % (testname, kind, name, msg)) Modified: python/branches/p3yk/Lib/test/sortperf.py ============================================================================== --- python/branches/p3yk/Lib/test/sortperf.py (original) +++ python/branches/p3yk/Lib/test/sortperf.py Wed Jan 10 17:19:56 2007 @@ -37,7 +37,7 @@ os.unlink(fn) except os.error: pass - except IOError, msg: + except IOError as msg: print "can't write", fn, ":", msg else: result = marshal.load(fp) Modified: python/branches/p3yk/Lib/test/string_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/string_tests.py (original) +++ python/branches/p3yk/Lib/test/string_tests.py Wed Jan 10 17:19:56 2007 @@ -970,7 +970,7 @@ def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Wed Jan 10 17:19:56 2007 @@ -373,13 +373,11 @@ return badval try: bool(A()) - except (Exception), e_bool: - pass - try: - len(A()) - except (Exception), e_len: - pass - self.assertEqual(str(e_bool), str(e_len)) + except (Exception) as e_bool: + try: + len(A()) + except (Exception) as e_len: + self.assertEqual(str(e_bool), str(e_len)) def test_main(): test_support.run_unittest(BoolTest) Modified: python/branches/p3yk/Lib/test/test_cfgparser.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cfgparser.py (original) +++ python/branches/p3yk/Lib/test/test_cfgparser.py Wed Jan 10 17:19:56 2007 @@ -181,7 +181,7 @@ def get_error(self, exc, section, option): try: self.cf.get(section, option) - except exc, e: + except exc as e: return e else: self.fail("expected exception type %s.%s" Modified: python/branches/p3yk/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cgi.py (original) +++ python/branches/p3yk/Lib/test/test_cgi.py Wed Jan 10 17:19:56 2007 @@ -50,7 +50,7 @@ raise ValueError, "unknown method: %s" % method try: return cgi.parse(fp, env, strict_parsing=1) - except StandardError, err: + except StandardError as err: return ComparableException(err) # A list of test cases. Each test case is a a two-tuple that contains Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Wed Jan 10 17:19:56 2007 @@ -372,7 +372,7 @@ a = property(booh) try: A().a # Raised AttributeError: A instance has no attribute 'a' -except AttributeError, x: +except AttributeError as x: if str(x) != "booh": print "attribute error for A().a got masked:", str(x) @@ -384,7 +384,7 @@ __init__ = property(booh) try: I() # In debug mode, printed XXX undetected error and raises AttributeError -except AttributeError, x: +except AttributeError as x: pass else: print "attribute error for I.__init__ got masked" Modified: python/branches/p3yk/Lib/test/test_codecs.py ============================================================================== --- python/branches/p3yk/Lib/test/test_codecs.py (original) +++ python/branches/p3yk/Lib/test/test_codecs.py Wed Jan 10 17:19:56 2007 @@ -595,7 +595,7 @@ if sys.maxunicode > 0xffff: try: "\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") - except UnicodeDecodeError, ex: + except UnicodeDecodeError as ex: self.assertEquals("unicode_internal", ex.encoding) self.assertEquals("\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEquals(4, ex.start) @@ -782,7 +782,7 @@ prepped = unicode(prepped, "utf-8") try: self.assertEquals(nameprep(orig), prepped) - except Exception,e: + except Exception as e: raise test_support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) class IDNACodecTest(unittest.TestCase): Modified: python/branches/p3yk/Lib/test/test_compiler.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compiler.py (original) +++ python/branches/p3yk/Lib/test/test_compiler.py Wed Jan 10 17:19:56 2007 @@ -44,7 +44,7 @@ else: try: compiler.compile(buf, basename, "exec") - except Exception, e: + except Exception as e: args = list(e.args) args[0] += "[in file %s]" % basename e.args = tuple(args) Modified: python/branches/p3yk/Lib/test/test_contextlib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_contextlib.py (original) +++ python/branches/p3yk/Lib/test/test_contextlib.py Wed Jan 10 17:19:56 2007 @@ -76,7 +76,7 @@ state.append(1) try: yield 42 - except ZeroDivisionError, e: + except ZeroDivisionError as e: state.append(e.args[0]) self.assertEqual(state, [1, 42, 999]) with woohoo() as x: Modified: python/branches/p3yk/Lib/test/test_cookielib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cookielib.py (original) +++ python/branches/p3yk/Lib/test/test_cookielib.py Wed Jan 10 17:19:56 2007 @@ -257,7 +257,7 @@ try: c.load(filename="for this test to work, a file with this " "filename should not exist") - except IOError, exc: + except IOError as exc: # exactly IOError, not LoadError self.assertEqual(exc.__class__, IOError) else: Modified: python/branches/p3yk/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dbm.py (original) +++ python/branches/p3yk/Lib/test/test_dbm.py Wed Jan 10 17:19:56 2007 @@ -16,7 +16,8 @@ for suffix in ['', '.pag', '.dir', '.db']: try: os.unlink(filename + suffix) - except OSError, (errno, strerror): + except OSError as e: + (errno, strerror) = e # if we can't delete the file because of permissions, # nothing will work, so skip the test if errno == 1: Modified: python/branches/p3yk/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decimal.py (original) +++ python/branches/p3yk/Lib/test/test_decimal.py Wed Jan 10 17:19:56 2007 @@ -146,7 +146,7 @@ print 'Error in test cases:' print line continue - except DecimalException, exception: + except DecimalException as exception: #Exception raised where there shoudn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) @@ -238,7 +238,7 @@ funct(self.context.create_decimal(v)) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -258,7 +258,7 @@ funct(*vals) except error: pass - except Signals, e: + except Signals as e: self.fail("Raised %s in %s when %s disabled" % \ (e, s, error)) else: @@ -268,7 +268,7 @@ result = str(funct(*vals)) if fname == 'same_quantum': result = str(int(eval(result))) # 'True', 'False' -> '1', '0' - except Signals, error: + except Signals as error: self.fail("Raised %s in %s" % (error, s)) except: #Catch any error long enough to state the test case. print "ERROR:", s Modified: python/branches/p3yk/Lib/test/test_defaultdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_defaultdict.py (original) +++ python/branches/p3yk/Lib/test/test_defaultdict.py Wed Jan 10 17:19:56 2007 @@ -43,7 +43,7 @@ self.assertEqual(d2.default_factory, None) try: d2[15] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (15,)) else: self.fail("d2[15] didn't raise KeyError") Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Wed Jan 10 17:19:56 2007 @@ -945,7 +945,7 @@ def raises(exc, expected, callable, *args): try: callable(*args) - except exc, msg: + except exc as msg: if not str(msg).startswith(expected): raise TestFailed, "Message %r, expected %r" % (str(msg), expected) @@ -1813,7 +1813,7 @@ no = NoWeak() try: weakref.ref(no) - except TypeError, msg: + except TypeError as msg: verify(str(msg).find("weak reference") >= 0) else: verify(0, "weakref.ref(no) should be illegal") @@ -1866,7 +1866,7 @@ for attr in "__doc__", "fget", "fset", "fdel": try: setattr(raw, attr, 42) - except TypeError, msg: + except TypeError as msg: if str(msg).find('readonly') < 0: raise TestFailed("when setting readonly attr %r on a " "property, got unexpected TypeError " @@ -2416,7 +2416,7 @@ for code in code1, code2, code3: try: sandbox.r_exec(code) - except IOError, msg: + except IOError as msg: if str(msg).find("restricted") >= 0: outcome = "OK" else: @@ -3523,7 +3523,7 @@ try: D.__bases__ = () - except TypeError, msg: + except TypeError as msg: if str(msg) == "a new-style class can't have only classic bases": raise TestFailed, "wrong error message for .__bases__ = ()" else: Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Wed Jan 10 17:19:56 2007 @@ -414,7 +414,7 @@ e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -425,7 +425,7 @@ f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -434,7 +434,7 @@ g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") @@ -444,7 +444,7 @@ d = {} try: d[(1,)] - except KeyError, e: + except KeyError as e: self.assertEqual(e.args, ((1,),)) else: self.fail("missing KeyError") Modified: python/branches/p3yk/Lib/test/test_dl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dl.py (original) +++ python/branches/p3yk/Lib/test/test_dl.py Wed Jan 10 17:19:56 2007 @@ -18,7 +18,7 @@ if verbose: print 'trying to open:', s, l = dl.open(s) - except dl.error, err: + except dl.error as err: if verbose: print 'failed', repr(str(err)) pass Modified: python/branches/p3yk/Lib/test/test_eof.py ============================================================================== --- python/branches/p3yk/Lib/test/test_eof.py (original) +++ python/branches/p3yk/Lib/test/test_eof.py Wed Jan 10 17:19:56 2007 @@ -11,7 +11,7 @@ try: eval("""'this is a test\ """) - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed @@ -20,7 +20,7 @@ expect = "EOF while scanning triple-quoted string (, line 1)" try: eval("""'''this is a test""") - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(str(msg), expect) else: raise test_support.TestFailed Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Wed Jan 10 17:19:56 2007 @@ -21,17 +21,17 @@ try: import exceptions reload(exceptions) - except ImportError, e: + except ImportError as e: self.fail("reloading exceptions: %s" % e) def raise_catch(self, exc, excname): try: raise exc, "spam" - except exc, err: + except exc as err: buf1 = str(err) try: raise exc("spam") - except exc, err: + except exc as err: buf2 = str(err) self.assertEquals(buf1, buf2) self.assertEquals(exc.__name__, excname) @@ -115,7 +115,7 @@ self.raise_catch(Exception, "Exception") try: x = 1/0 - except Exception, e: pass + except Exception as e: pass def testSyntaxErrorMessage(self): # make sure the right exception message is raised for each of @@ -124,7 +124,7 @@ def ckmsg(src, msg): try: compile(src, '', 'exec') - except SyntaxError, e: + except SyntaxError as e: if e.msg != msg: self.fail("expected %s, got %s" % (msg, e.msg)) else: @@ -163,7 +163,7 @@ import _testcapi try: _testcapi.raise_exception(BadException, 1) - except TypeError, err: + except TypeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "test_capi1") @@ -175,7 +175,7 @@ import _testcapi try: _testcapi.raise_exception(BadException, 0) - except RuntimeError, err: + except RuntimeError as err: exc, err, tb = sys.exc_info() co = tb.tb_frame.f_code self.assertEquals(co.co_name, "__init__") @@ -285,7 +285,7 @@ for exc, args, expected in exceptionList: try: raise exc(*args) - except BaseException, e: + except BaseException as e: if type(e) is not exc: raise # Verify module name @@ -344,6 +344,16 @@ self.failUnless(str(Exception('a'))) self.failUnless(unicode(Exception(u'a'))) + def testExceptionCleanup(self): + # Make sure "except V as N" exceptions are cleaned up properly + + try: + raise Exception() + except Exception as e: + self.failUnless(e) + del e + self.failIf('e' in locals()) + def test_main(): run_unittest(ExceptionTests) Modified: python/branches/p3yk/Lib/test/test_extcall.py ============================================================================== --- python/branches/p3yk/Lib/test/test_extcall.py (original) +++ python/branches/p3yk/Lib/test/test_extcall.py Wed Jan 10 17:19:56 2007 @@ -35,21 +35,21 @@ try: g() -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*()) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*(), **{}) -except TypeError, err: +except TypeError as err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" @@ -61,7 +61,7 @@ class Nothing: pass try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -71,7 +71,7 @@ return 5 try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -93,7 +93,7 @@ return self try: g(*Nothing()) -except TypeError, attr: +except TypeError as attr: pass else: print "should raise TypeError" @@ -132,77 +132,77 @@ try: g(1, 2, 3, **{'x':4, 'y':5}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keyword parameter redefined" try: f(**{1:2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: keywords must be strings" try: h(**{'e': 2}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: unexpected keyword argument: e" try: h(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: dir(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: None(*h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: * argument must be a tuple" try: h(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: None(**h) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: ** argument must be a dictionary" try: dir(b=1,**{'b':1}) -except TypeError, err: +except TypeError as err: print err else: print "should raise TypeError: dir() got multiple values for keyword argument 'b'" @@ -226,13 +226,13 @@ print Foo.method(x, *(1, 2)) try: print Foo.method(*(1, 2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' try: print Foo.method(1, *(2, 3)) -except TypeError, err: +except TypeError as err: pass else: print 'expected a TypeError for unbound method call' @@ -276,4 +276,4 @@ for k in kwargs: kwdict[k] = k + k print func.func_name, args, sortdict(kwdict), '->', try: func(*args, **kwdict) - except TypeError, err: print err + except TypeError as err: print err Modified: python/branches/p3yk/Lib/test/test_file.py ============================================================================== --- python/branches/p3yk/Lib/test/test_file.py (original) +++ python/branches/p3yk/Lib/test/test_file.py Wed Jan 10 17:19:56 2007 @@ -159,7 +159,7 @@ bad_mode = "qwerty" try: f = open(TESTFN, bad_mode) - except ValueError, msg: + except ValueError as msg: if msg[0] != 0: s = str(msg) if s.find(TESTFN) != -1 or s.find(bad_mode) == -1: @@ -183,7 +183,7 @@ d = int(f.read()) f.close() f.close() - except IOError, msg: + except IOError as msg: self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.assertEquals(d, s) Modified: python/branches/p3yk/Lib/test/test_format.py ============================================================================== --- python/branches/p3yk/Lib/test/test_format.py (original) +++ python/branches/p3yk/Lib/test/test_format.py Wed Jan 10 17:19:56 2007 @@ -199,7 +199,7 @@ def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) - except exception, exc: + except exception as exc: if str(exc) == excmsg: if verbose: print "yes" Modified: python/branches/p3yk/Lib/test/test_frozen.py ============================================================================== --- python/branches/p3yk/Lib/test/test_frozen.py (original) +++ python/branches/p3yk/Lib/test/test_frozen.py Wed Jan 10 17:19:56 2007 @@ -12,17 +12,17 @@ try: import __hello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __hello__ failed:" + str(x) try: import __phello__ -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__ failed:" + str(x) try: import __phello__.spam -except ImportError, x: +except ImportError as x: raise TestFailed, "import __phello__.spam failed:" + str(x) if sys.platform != "mac": # On the Mac this import does succeed. Modified: python/branches/p3yk/Lib/test/test_future.py ============================================================================== --- python/branches/p3yk/Lib/test/test_future.py (original) +++ python/branches/p3yk/Lib/test/test_future.py Wed Jan 10 17:19:56 2007 @@ -29,7 +29,7 @@ def test_badfuture3(self): try: from test import badsyntax_future3 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future3", '3')) else: self.fail("expected exception didn't occur") @@ -37,7 +37,7 @@ def test_badfuture4(self): try: from test import badsyntax_future4 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future4", '3')) else: self.fail("expected exception didn't occur") @@ -45,7 +45,7 @@ def test_badfuture5(self): try: from test import badsyntax_future5 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future5", '4')) else: self.fail("expected exception didn't occur") @@ -53,7 +53,7 @@ def test_badfuture6(self): try: from test import badsyntax_future6 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future6", '3')) else: self.fail("expected exception didn't occur") @@ -61,7 +61,7 @@ def test_badfuture7(self): try: from test import badsyntax_future7 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future7", '3')) else: self.fail("expected exception didn't occur") @@ -69,7 +69,7 @@ def test_badfuture8(self): try: from test import badsyntax_future8 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future8", '3')) else: self.fail("expected exception didn't occur") @@ -77,7 +77,7 @@ def test_badfuture9(self): try: from test import badsyntax_future9 - except SyntaxError, msg: + except SyntaxError as msg: self.assertEqual(get_error_location(msg), ("badsyntax_future9", '3')) else: self.fail("expected exception didn't occur") Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Wed Jan 10 17:19:56 2007 @@ -1554,7 +1554,7 @@ ... while True: ... try: ... print (yield) -... except ValueError,v: +... except ValueError as v: ... print "caught ValueError (%s)" % (v), >>> import sys >>> g = f() Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Wed Jan 10 17:19:56 2007 @@ -554,7 +554,7 @@ assert 1, lambda x:x+1 try: assert 0, "msg" - except AssertionError, e: + except AssertionError as e: self.assertEquals(e.args[0], "msg") else: if __debug__: @@ -612,7 +612,7 @@ def testTry(self): ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite - ### except_clause: 'except' [expr [',' expr]] + ### except_clause: 'except' [expr ['as' expr]] try: 1/0 except ZeroDivisionError: @@ -621,14 +621,14 @@ pass try: 1/0 except EOFError: pass - except TypeError, msg: pass - except RuntimeError, msg: pass + except TypeError as msg: pass + except RuntimeError as msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 - except (EOFError, TypeError, ZeroDivisionError), msg: pass + except (EOFError, TypeError, ZeroDivisionError) as msg: pass try: pass finally: pass Modified: python/branches/p3yk/Lib/test/test_import.py ============================================================================== --- python/branches/p3yk/Lib/test/test_import.py (original) +++ python/branches/p3yk/Lib/test/test_import.py Wed Jan 10 17:19:56 2007 @@ -55,7 +55,7 @@ try: try: mod = __import__(TESTFN) - except ImportError, err: + except ImportError as err: self.fail("import from %s failed: %s" % (ext, err)) self.assertEquals(mod.a, a, @@ -68,7 +68,7 @@ try: try: reload(mod) - except ImportError, err: + except ImportError as err: self.fail("import from .pyc/.pyo failed: %s" % err) finally: try: Modified: python/branches/p3yk/Lib/test/test_linuxaudiodev.py ============================================================================== --- python/branches/p3yk/Lib/test/test_linuxaudiodev.py (original) +++ python/branches/p3yk/Lib/test/test_linuxaudiodev.py Wed Jan 10 17:19:56 2007 @@ -27,7 +27,7 @@ try: a = linuxaudiodev.open('w') - except linuxaudiodev.error, msg: + except linuxaudiodev.error as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -62,27 +62,27 @@ nchannels = 1 try: a.setparameters(-1, size, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, -2, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, 3, fmt) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, 177) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) - except ValueError, msg: + except ValueError as msg: print msg try: a.setparameters(rate, 16, nchannels, fmt) - except ValueError, msg: + except ValueError as msg: print msg def test(): Modified: python/branches/p3yk/Lib/test/test_nis.py ============================================================================== --- python/branches/p3yk/Lib/test/test_nis.py (original) +++ python/branches/p3yk/Lib/test/test_nis.py Wed Jan 10 17:19:56 2007 @@ -6,7 +6,7 @@ def test_maps(self): try: maps = nis.maps() - except nis.error, msg: + except nis.error as msg: # NIS is probably not active, so this test isn't useful if verbose: self.fail("(failing because of verbose mode) %s" % msg) Modified: python/branches/p3yk/Lib/test/test_opcodes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_opcodes.py (original) +++ python/branches/p3yk/Lib/test/test_opcodes.py Wed Jan 10 17:19:56 2007 @@ -47,12 +47,12 @@ b = BClass() try: raise AClass, b - except BClass, v: + except BClass as v: if v != b: self.fail("v!=b") else: self.fail("no exception") try: raise b - except AClass, v: + except AClass as v: if v != b: self.fail("v!=b AClass") else: self.fail("no exception") @@ -63,7 +63,7 @@ ##else: self.fail("no exception") try: raise DClass, a - except DClass, v: + except DClass as v: self.assert_(isinstance(v, DClass)) else: self.fail("no exception") Modified: python/branches/p3yk/Lib/test/test_optparse.py ============================================================================== --- python/branches/p3yk/Lib/test/test_optparse.py (original) +++ python/branches/p3yk/Lib/test/test_optparse.py Wed Jan 10 17:19:56 2007 @@ -114,7 +114,7 @@ try: func(*args, **kwargs) - except expected_exception, err: + except expected_exception as err: actual_message = str(err) if isinstance(expected_message, retype): self.assert_(expected_message.search(actual_message), @@ -152,7 +152,7 @@ """ try: self.parser.parse_args(cmdline_args) - except InterceptedError, err: + except InterceptedError as err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") @@ -175,7 +175,7 @@ output = sys.stdout.getvalue() sys.stdout = save_stdout - except InterceptedError, err: + except InterceptedError as err: self.assert_( type(output) is types.StringType, "expected output to be an ordinary string, not %r" @@ -460,7 +460,7 @@ return int(value) else: return int(value[:-1]) * _time_units[value[-1]] - except ValueError, IndexError: + except ValueError as IndexError: raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) Modified: python/branches/p3yk/Lib/test/test_os.py ============================================================================== --- python/branches/p3yk/Lib/test/test_os.py (original) +++ python/branches/p3yk/Lib/test/test_os.py Wed Jan 10 17:19:56 2007 @@ -179,7 +179,7 @@ import statvfs try: result = os.statvfs(self.fname) - except OSError, e: + except OSError as e: # On AtheOS, glibc always returns ENOSYS import errno if e.errno == errno.ENOSYS: Modified: python/branches/p3yk/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ossaudiodev.py (original) +++ python/branches/p3yk/Lib/test/test_ossaudiodev.py Wed Jan 10 17:19:56 2007 @@ -48,7 +48,7 @@ def play_sound_file(data, rate, ssize, nchannels): try: dsp = ossaudiodev.open('w') - except IOError, msg: + except IOError as msg: if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg @@ -142,7 +142,7 @@ try: result = dsp.setparameters(fmt, channels, rate, True) raise AssertionError("setparameters: expected OSSAudioError") - except ossaudiodev.OSSAudioError, err: + except ossaudiodev.OSSAudioError as err: print "setparameters: got OSSAudioError as expected" def test(): Modified: python/branches/p3yk/Lib/test/test_parser.py ============================================================================== --- python/branches/p3yk/Lib/test/test_parser.py (original) +++ python/branches/p3yk/Lib/test/test_parser.py Wed Jan 10 17:19:56 2007 @@ -15,7 +15,7 @@ t = st1.totuple() try: st2 = parser.sequence2st(t) - except parser.ParserError, why: + except parser.ParserError as why: self.fail("could not roundtrip %r: %s" % (s, why)) self.assertEquals(t, st2.totuple(), Modified: python/branches/p3yk/Lib/test/test_pep277.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pep277.py (original) +++ python/branches/p3yk/Lib/test/test_pep277.py Wed Jan 10 17:19:56 2007 @@ -50,7 +50,7 @@ fn(filename) raise test_support.TestFailed("Expected to fail calling '%s(%r)'" % (fn.__name__, filename)) - except expected_exception, details: + except expected_exception as details: if check_fn_in_exception and details.filename != filename: raise test_support.TestFailed("Function '%s(%r) failed with " "bad filename in the exception: %r" Modified: python/branches/p3yk/Lib/test/test_pyexpat.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyexpat.py (original) +++ python/branches/p3yk/Lib/test/test_pyexpat.py Wed Jan 10 17:19:56 2007 @@ -177,7 +177,7 @@ print "Legal values tested o.k." try: expat.ParserCreate(namespace_separator=42) -except TypeError, e: +except TypeError as e: print "Caught expected TypeError:" print e else: @@ -185,7 +185,7 @@ try: expat.ParserCreate(namespace_separator='too long') -except ValueError, e: +except ValueError as e: print "Caught expected ValueError:" print e else: @@ -321,7 +321,7 @@ try: parser.Parse("", 1) -except RuntimeError, e: +except RuntimeError as e: if e.args[0] != "a": print "Expected RuntimeError for element 'a'; found %r" % e.args[0] else: Modified: python/branches/p3yk/Lib/test/test_re.py ============================================================================== --- python/branches/p3yk/Lib/test/test_re.py (original) +++ python/branches/p3yk/Lib/test/test_re.py Wed Jan 10 17:19:56 2007 @@ -633,7 +633,7 @@ else: try: result = obj.search(s) - except re.error, msg: + except re.error as msg: print '=== Unexpected exception', t, repr(msg) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. Modified: python/branches/p3yk/Lib/test/test_runpy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_runpy.py (original) +++ python/branches/p3yk/Lib/test/test_runpy.py Wed Jan 10 17:19:56 2007 @@ -117,7 +117,7 @@ entry = parts[0] try: del sys.modules[entry] - except KeyError, ex: + except KeyError as ex: if verbose: print ex # Persist with cleaning up if verbose: print " Removed sys.modules entries" del sys.path[0] @@ -126,18 +126,18 @@ for name in files: try: os.remove(os.path.join(root, name)) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up try: os.rmdir(top) if verbose: print " Removed package tree" - except OSError, ex: + except OSError as ex: if verbose: print ex # Persist with cleaning up def _check_module(self, depth): Modified: python/branches/p3yk/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sax.py (original) +++ python/branches/p3yk/Lib/test/test_sax.py Wed Jan 10 17:19:56 2007 @@ -479,7 +479,7 @@ source.setSystemId(name) try: parser.parse(source) - except SAXException, e: + except SAXException as e: return e.getSystemId() == name def test_expat_incomplete(): Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Wed Jan 10 17:19:56 2007 @@ -332,7 +332,7 @@ for v1 in ['Q', (1,)]: try: self.s.remove(v1) - except KeyError, e: + except KeyError as e: v2 = e.args[0] self.assertEqual(v1, v2) else: Modified: python/branches/p3yk/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket.py (original) +++ python/branches/p3yk/Lib/test/test_socket.py Wed Jan 10 17:19:56 2007 @@ -129,7 +129,7 @@ raise TypeError, "test_func must be a callable function" try: test_func() - except Exception, strerror: + except Exception as strerror: self.queue.put(strerror) self.clientTearDown() Modified: python/branches/p3yk/Lib/test/test_socket_ssl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket_ssl.py (original) +++ python/branches/p3yk/Lib/test/test_socket_ssl.py Wed Jan 10 17:19:56 2007 @@ -58,7 +58,7 @@ except socket.timeout: error_msg('timed out') return - except socket.error, exc: # In case connection is refused. + except socket.error as exc: # In case connection is refused. if exc.args[0] == errno.ECONNREFUSED: error_msg('was refused') return Modified: python/branches/p3yk/Lib/test/test_socketserver.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socketserver.py (original) +++ python/branches/p3yk/Lib/test/test_socketserver.py Wed Jan 10 17:19:56 2007 @@ -155,7 +155,8 @@ self.server_address = host, port TCPServer.server_bind(self) break - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ Modified: python/branches/p3yk/Lib/test/test_strftime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_strftime.py (original) +++ python/branches/p3yk/Lib/test/test_strftime.py Wed Jan 10 17:19:56 2007 @@ -119,7 +119,7 @@ for e in expectations: try: result = time.strftime(e[0], now) - except ValueError, error: + except ValueError as error: print "Standard '%s' format gave error:" % e[0], error continue if re.match(escapestr(e[1], ampm), result): continue @@ -132,7 +132,7 @@ for e in nonstandard_expectations: try: result = time.strftime(e[0], now) - except ValueError, result: + except ValueError as result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) Modified: python/branches/p3yk/Lib/test/test_string.py ============================================================================== --- python/branches/p3yk/Lib/test/test_string.py (original) +++ python/branches/p3yk/Lib/test/test_string.py Wed Jan 10 17:19:56 2007 @@ -55,7 +55,7 @@ def f(): yield 4 + "" self.fixtype(' ').join(f()) - except TypeError, e: + except TypeError as e: if '+' not in str(e): self.fail('join() ate exception message') else: Modified: python/branches/p3yk/Lib/test/test_strptime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_strptime.py (original) +++ python/branches/p3yk/Lib/test/test_strptime.py Wed Jan 10 17:19:56 2007 @@ -206,7 +206,7 @@ _strptime.strptime("2005", bad_format) except ValueError: continue - except Exception, err: + except Exception as err: self.fail("'%s' raised %s, not ValueError" % (bad_format, err.__class__.__name__)) else: Modified: python/branches/p3yk/Lib/test/test_subprocess.py ============================================================================== --- python/branches/p3yk/Lib/test/test_subprocess.py (original) +++ python/branches/p3yk/Lib/test/test_subprocess.py Wed Jan 10 17:19:56 2007 @@ -67,7 +67,7 @@ try: subprocess.check_call([sys.executable, "-c", "import sys; sys.exit(47)"]) - except subprocess.CalledProcessError, e: + except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, 47) else: self.fail("Expected CalledProcessError") @@ -475,7 +475,7 @@ try: p = subprocess.Popen([sys.executable, "-c", ""], cwd="/this/path/does/not/exist") - except OSError, e: + except OSError as e: # The attribute child_traceback should contain "os.chdir" # somewhere. self.assertNotEqual(e.child_traceback.find("os.chdir"), -1) Modified: python/branches/p3yk/Lib/test/test_sunaudiodev.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sunaudiodev.py (original) +++ python/branches/p3yk/Lib/test/test_sunaudiodev.py Wed Jan 10 17:19:56 2007 @@ -16,7 +16,7 @@ fp.close() try: a = sunaudiodev.open('w') - except sunaudiodev.error, msg: + except sunaudiodev.error as msg: raise TestFailed, msg else: a.write(data) Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Wed Jan 10 17:19:56 2007 @@ -102,7 +102,8 @@ try: sock.bind((host, port)) return port - except socket.error, (err, msg): + except socket.error as e: + (err, msg) = e if err != errno.EADDRINUSE: raise print >>sys.__stderr__, \ Modified: python/branches/p3yk/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_syntax.py (original) +++ python/branches/p3yk/Lib/test/test_syntax.py Wed Jan 10 17:19:56 2007 @@ -387,7 +387,7 @@ """ try: compile(code, filename, mode) - except SyntaxError, err: + except SyntaxError as err: if subclass and not isinstance(err, subclass): self.fail("SyntaxError is not a %s" % subclass.__name__) mo = re.search(errtext, str(err)) Modified: python/branches/p3yk/Lib/test/test_sys.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sys.py (original) +++ python/branches/p3yk/Lib/test/test_sys.py Wed Jan 10 17:19:56 2007 @@ -54,7 +54,7 @@ self.assertRaises(TypeError, eh) try: raise ValueError(42) - except ValueError, exc: + except ValueError as exc: eh(*sys.exc_info()) sys.stderr = savestderr @@ -84,7 +84,7 @@ def clear(): try: raise ValueError, 42 - except ValueError, exc: + except ValueError as exc: clear_check(exc) # Raise an exception and check that it can be cleared @@ -94,7 +94,7 @@ # unaffected by calling exc_clear in a nested frame. try: raise ValueError, 13 - except ValueError, exc: + except ValueError as exc: typ1, value1, traceback1 = sys.exc_info() clear() typ2, value2, traceback2 = sys.exc_info() @@ -104,16 +104,13 @@ self.assert_(value1 is value2) self.assert_(traceback1 is traceback2) - # Check that an exception can be cleared outside of an except block - clear_check(exc) - def test_exit(self): self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument try: sys.exit(0) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 0) except: self.fail("wrong exception") @@ -124,7 +121,7 @@ # entry will be unpacked try: sys.exit(42) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -134,7 +131,7 @@ # call with integer argument try: sys.exit((42,)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, 42) except: self.fail("wrong exception") @@ -144,7 +141,7 @@ # call with string argument try: sys.exit("exit") - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, "exit") except: self.fail("wrong exception") @@ -154,7 +151,7 @@ # call with tuple argument with two entries try: sys.exit((17, 23)) - except SystemExit, exc: + except SystemExit as exc: self.assertEquals(exc.code, (17, 23)) except: self.fail("wrong exception") Modified: python/branches/p3yk/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk/Lib/test/test_tarfile.py Wed Jan 10 17:19:56 2007 @@ -545,7 +545,7 @@ try: # Extract 1-LNKTYPE which is a hardlink to 0-REGTYPE self.tar.extract("1-LNKTYPE", dirname()) - except EnvironmentError, e: + except EnvironmentError as e: import errno if e.errno == errno.ENOENT: self.fail("hardlink not extracted properly") Modified: python/branches/p3yk/Lib/test/test_tcl.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tcl.py (original) +++ python/branches/p3yk/Lib/test/test_tcl.py Wed Jan 10 17:19:56 2007 @@ -107,7 +107,7 @@ filename = "doesnotexists" try: os.remove(filename) - except Exception,e: + except Exception as e: pass self.assertRaises(TclError,tcl.evalfile,filename) Modified: python/branches/p3yk/Lib/test/test_trace.py ============================================================================== --- python/branches/p3yk/Lib/test/test_trace.py (original) +++ python/branches/p3yk/Lib/test/test_trace.py Wed Jan 10 17:19:56 2007 @@ -97,7 +97,7 @@ def test_raise(): try: raises() - except Exception, exc: + except Exception as exc: x = 1 test_raise.events = [(0, 'call'), @@ -127,7 +127,7 @@ def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) - except RuntimeError, exc: + except RuntimeError as exc: pass settrace_and_raise.events = [(2, 'exception'), @@ -432,7 +432,7 @@ try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('after' in str(e)) no_jump_too_far_forwards.jump = (3, 6) @@ -442,7 +442,7 @@ try: output.append(2) output.append(3) - except ValueError, e: + except ValueError as e: output.append('before' in str(e)) no_jump_too_far_backwards.jump = (3, -1) @@ -472,7 +472,7 @@ def no_jump_to_except_3(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('except' in str(e)) no_jump_to_except_3.jump = (2, 3) @@ -481,7 +481,7 @@ def no_jump_to_except_4(output): try: output.append(2) - except (ValueError, RuntimeError), e: + except (ValueError, RuntimeError) as e: output.append('except' in str(e)) no_jump_to_except_4.jump = (2, 3) @@ -492,7 +492,7 @@ output.append(2) for i in 1, 2: output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_forwards_into_block.jump = (2, 4) @@ -503,7 +503,7 @@ for i in 1, 2: output.append(3) output.append(4) - except ValueError, e: + except ValueError as e: output.append('into' in str(e)) no_jump_backwards_into_block.jump = (4, 3) @@ -516,7 +516,7 @@ x = 1 finally: output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_into_finally_block.jump = (4, 6) @@ -529,7 +529,7 @@ finally: output.append(5) output.append(6) - except ValueError, e: + except ValueError as e: output.append('finally' in str(e)) no_jump_out_of_finally_block.jump = (5, 1) @@ -539,7 +539,7 @@ def no_jump_to_non_integers(output): try: output.append(2) - except ValueError, e: + except ValueError as e: output.append('integer' in str(e)) no_jump_to_non_integers.jump = (2, "Spam") @@ -551,7 +551,7 @@ try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno - except ValueError, e: + except ValueError as e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e): Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Wed Jan 10 17:19:56 2007 @@ -12,7 +12,7 @@ def get_exception_format(self, func, exc): try: func() - except exc, value: + except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError, "call did not raise exception" Modified: python/branches/p3yk/Lib/test/test_urllib2net.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib2net.py (original) +++ python/branches/p3yk/Lib/test/test_urllib2net.py Wed Jan 10 17:19:56 2007 @@ -236,7 +236,7 @@ debug(url) try: f = urllib2.urlopen(url, req) - except (IOError, socket.error, OSError), err: + except (IOError, socket.error, OSError) as err: debug(err) if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s" % Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Wed Jan 10 17:19:56 2007 @@ -168,7 +168,7 @@ e = E() try: e[42] - except RuntimeError, err: + except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail_("e[42] didn't raise RuntimeError") @@ -180,7 +180,7 @@ f = F() try: f[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("f[42] didn't raise KeyError") @@ -189,7 +189,7 @@ g = G() try: g[42] - except KeyError, err: + except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail_("g[42] didn't raise KeyError") Modified: python/branches/p3yk/Lib/test/test_uu.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uu.py (original) +++ python/branches/p3yk/Lib/test/test_uu.py Wed Jan 10 17:19:56 2007 @@ -50,7 +50,7 @@ try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "Truncated input file") def test_missingbegin(self): @@ -59,7 +59,7 @@ try: uu.decode(inp, out) self.fail("No exception thrown") - except uu.Error, e: + except uu.Error as e: self.assertEqual(str(e), "No valid begin line found in input file") class UUStdIOTest(unittest.TestCase): Modified: python/branches/p3yk/Lib/test/test_winreg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_winreg.py (original) +++ python/branches/p3yk/Lib/test/test_winreg.py Wed Jan 10 17:19:56 2007 @@ -142,7 +142,7 @@ if remote_name is not None: try: remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER) - except EnvironmentError, exc: + except EnvironmentError as exc: print "Could not connect to the remote machine -", exc.strerror remote_key = None if remote_key is not None: Modified: python/branches/p3yk/Lib/timeit.py ============================================================================== --- python/branches/p3yk/Lib/timeit.py (original) +++ python/branches/p3yk/Lib/timeit.py Wed Jan 10 17:19:56 2007 @@ -209,7 +209,7 @@ opts, args = getopt.getopt(args, "n:s:r:tcvh", ["number=", "setup=", "repeat=", "time", "clock", "verbose", "help"]) - except getopt.error, err: + except getopt.error as err: print err print "use -h/--help for command line help" return 2 Modified: python/branches/p3yk/Lib/toaiff.py ============================================================================== --- python/branches/p3yk/Lib/toaiff.py (original) +++ python/branches/p3yk/Lib/toaiff.py Wed Jan 10 17:19:56 2007 @@ -87,7 +87,7 @@ ftype = sndhdr.whathdr(fname) if ftype: ftype = ftype[0] # All we're interested in - except IOError, msg: + except IOError as msg: if type(msg) == type(()) and len(msg) == 2 and \ type(msg[0]) == type(0) and type(msg[1]) == type(''): msg = msg[1] Modified: python/branches/p3yk/Lib/token.py ============================================================================== --- python/branches/p3yk/Lib/token.py (original) +++ python/branches/p3yk/Lib/token.py Wed Jan 10 17:19:56 2007 @@ -93,7 +93,7 @@ outFileName = args[1] try: fp = open(inFileName) - except IOError, err: + except IOError as err: sys.stdout.write("I/O error: %s\n" % str(err)) sys.exit(1) lines = fp.read().split("\n") @@ -113,7 +113,7 @@ # load the output skeleton from the target: try: fp = open(outFileName) - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(2) format = fp.read().split("\n") @@ -130,7 +130,7 @@ format[start:end] = lines try: fp = open(outFileName, 'w') - except IOError, err: + except IOError as err: sys.stderr.write("I/O error: %s\n" % str(err)) sys.exit(4) fp.write("\n".join(format)) Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Wed Jan 10 17:19:56 2007 @@ -220,7 +220,7 @@ counts, calledfuncs, callers = \ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) - except (IOError, EOFError, ValueError), err: + except (IOError, EOFError, ValueError) as err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) @@ -328,7 +328,7 @@ try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) - except IOError, err: + except IOError as err: print >> sys.stderr, "Can't save counts files because %s" % err def write_results_file(self, path, lines, lnotab, lines_hit): @@ -336,7 +336,7 @@ try: outfile = open(path, "w") - except IOError, err: + except IOError as err: print >> sys.stderr, ("trace: Could not open %r for writing: %s" "- skipping" % (path, err)) return 0, 0 @@ -422,7 +422,7 @@ """Return dict where keys are line numbers in the line number table.""" try: prog = open(filename, "rU").read() - except IOError, err: + except IOError as err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} @@ -658,7 +658,7 @@ "coverdir=", "listfuncs", "trackcalls"]) - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) @@ -778,7 +778,7 @@ outfile=counts_file) try: t.run('execfile(%r)' % (progname,)) - except IOError, err: + except IOError as err: _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) except SystemExit: pass Modified: python/branches/p3yk/Lib/unittest.py ============================================================================== --- python/branches/p3yk/Lib/unittest.py (original) +++ python/branches/p3yk/Lib/unittest.py Wed Jan 10 17:19:56 2007 @@ -783,7 +783,7 @@ else: self.testNames = (self.defaultTest,) self.createTests() - except getopt.error, msg: + except getopt.error as msg: self.usageExit(msg) def createTests(self): Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Wed Jan 10 17:19:56 2007 @@ -190,7 +190,7 @@ return getattr(self, name)(url) else: return getattr(self, name)(url, data) - except socket.error, msg: + except socket.error as msg: raise IOError, ('socket error', msg), sys.exc_info()[2] def open_unknown(self, fullurl, data=None): @@ -217,7 +217,7 @@ hdrs = fp.info() del fp return url2pathname(splithost(url1)[1]), hdrs - except IOError, msg: + except IOError as msg: pass fp = self.open(url, data) headers = fp.info() @@ -461,7 +461,7 @@ localname = url2pathname(file) try: stats = os.stat(localname) - except OSError, e: + except OSError as e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size modified = email.Utils.formatdate(stats.st_mtime, usegmt=True) @@ -544,7 +544,7 @@ headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO(headers)) return addinfourl(fp, headers, "ftp:" + url) - except ftperrors(), msg: + except ftperrors() as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def open_data(self, url, data=None): @@ -861,7 +861,7 @@ try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) - except ftplib.error_perm, reason: + except ftplib.error_perm as reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: @@ -1503,7 +1503,7 @@ import getopt, sys try: opts, args = getopt.getopt(sys.argv[1:], "th") - except getopt.error, msg: + except getopt.error as msg: print msg print "Use -h for help" return Modified: python/branches/p3yk/Lib/urllib2.py ============================================================================== --- python/branches/p3yk/Lib/urllib2.py (original) +++ python/branches/p3yk/Lib/urllib2.py Wed Jan 10 17:19:56 2007 @@ -1072,7 +1072,7 @@ try: h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() - except socket.error, err: # XXX what error? + except socket.error as err: # XXX what error? raise URLError(err) # Pick apart the HTTPResponse object to get the addinfourl @@ -1254,7 +1254,7 @@ try: host = socket.gethostbyname(host) - except socket.error, msg: + except socket.error as msg: raise URLError(msg) path, attrs = splitattr(req.get_selector()) dirs = path.split('/') @@ -1280,7 +1280,7 @@ sf = StringIO(headers) headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) - except ftplib.all_errors, msg: + except ftplib.all_errors as msg: raise IOError, ('ftp error', msg), sys.exc_info()[2] def connect_ftp(self, user, passwd, host, port, dirs): Modified: python/branches/p3yk/Lib/uu.py ============================================================================== --- python/branches/p3yk/Lib/uu.py (original) +++ python/branches/p3yk/Lib/uu.py Wed Jan 10 17:19:56 2007 @@ -132,7 +132,7 @@ while s and s.strip() != 'end': try: data = binascii.a2b_uu(s) - except binascii.Error, v: + except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) Modified: python/branches/p3yk/Lib/warnings.py ============================================================================== --- python/branches/p3yk/Lib/warnings.py (original) +++ python/branches/p3yk/Lib/warnings.py Wed Jan 10 17:19:56 2007 @@ -192,7 +192,7 @@ for arg in args: try: _setoption(arg) - except _OptionError, msg: + except _OptionError as msg: print >>sys.stderr, "Invalid -W option ignored:", msg # Helper for _processoptions() Modified: python/branches/p3yk/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk/Lib/webbrowser.py (original) +++ python/branches/p3yk/Lib/webbrowser.py Wed Jan 10 17:19:56 2007 @@ -625,7 +625,7 @@ -t: open new tab""" % sys.argv[0] try: opts, args = getopt.getopt(sys.argv[1:], 'ntd') - except getopt.error, msg: + except getopt.error as msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) Modified: python/branches/p3yk/Lib/xdrlib.py ============================================================================== --- python/branches/p3yk/Lib/xdrlib.py (original) +++ python/branches/p3yk/Lib/xdrlib.py Wed Jan 10 17:19:56 2007 @@ -68,12 +68,12 @@ def pack_float(self, x): try: self.__buf.write(struct.pack('>f', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_double(self, x): try: self.__buf.write(struct.pack('>d', x)) - except struct.error, msg: + except struct.error as msg: raise ConversionError, msg def pack_fstring(self, n, s): Modified: python/branches/p3yk/Lib/xml/sax/__init__.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/__init__.py (original) +++ python/branches/p3yk/Lib/xml/sax/__init__.py Wed Jan 10 17:19:56 2007 @@ -79,7 +79,7 @@ for parser_name in parser_list + default_parser_list: try: return _create_parser(parser_name) - except ImportError,e: + except ImportError as e: import sys if parser_name in sys.modules: # The parser module was found, but importing it Modified: python/branches/p3yk/Lib/xml/sax/expatreader.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/expatreader.py (original) +++ python/branches/p3yk/Lib/xml/sax/expatreader.py Wed Jan 10 17:19:56 2007 @@ -205,7 +205,7 @@ # document. When feeding chunks, they are not normally final - # except when invoked from close. self._parser.Parse(data, isFinal) - except expat.error, e: + except expat.error as e: exc = SAXParseException(expat.ErrorString(e.code), e, self) # FIXME: when to invoke error()? self._err_handler.fatalError(exc) Modified: python/branches/p3yk/Lib/xmllib.py ============================================================================== --- python/branches/p3yk/Lib/xmllib.py (original) +++ python/branches/p3yk/Lib/xmllib.py Wed Jan 10 17:19:56 2007 @@ -896,7 +896,7 @@ else: try: f = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ":", msg sys.exit(1) @@ -914,7 +914,7 @@ for c in data: x.feed(c) x.close() - except Error, msg: + except Error as msg: t1 = time() print msg if do_time: Modified: python/branches/p3yk/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk/Lib/xmlrpclib.py (original) +++ python/branches/p3yk/Lib/xmlrpclib.py Wed Jan 10 17:19:56 2007 @@ -1454,7 +1454,7 @@ try: print server.currentTime.getCurrentTime() - except Error, v: + except Error as v: print "ERROR", v multi = MultiCall(server) @@ -1463,5 +1463,5 @@ try: for response in multi(): print response - except Error, v: + except Error as v: print "ERROR", v Modified: python/branches/p3yk/Lib/zipfile.py ============================================================================== --- python/branches/p3yk/Lib/zipfile.py (original) +++ python/branches/p3yk/Lib/zipfile.py Wed Jan 10 17:19:56 2007 @@ -812,7 +812,7 @@ print "Compiling", file_py try: py_compile.compile(file_py, file_pyc, None, True) - except py_compile.PyCompileError,err: + except py_compile.PyCompileError as err: print err.msg fname = file_pyc else: Modified: python/branches/p3yk/Mac/BuildScript/build-installer.py ============================================================================== --- python/branches/p3yk/Mac/BuildScript/build-installer.py (original) +++ python/branches/p3yk/Mac/BuildScript/build-installer.py Wed Jan 10 17:19:56 2007 @@ -335,7 +335,7 @@ try: options, args = getopt.getopt(args, '?hb', [ 'build-dir=', 'third-party=', 'sdk-path=' , 'src-dir=']) - except getopt.error, msg: + except getopt.error as msg: print msg sys.exit(1) Modified: python/branches/p3yk/Mac/Demo/applescript/makedisk.py ============================================================================== --- python/branches/p3yk/Mac/Demo/applescript/makedisk.py (original) +++ python/branches/p3yk/Mac/Demo/applescript/makedisk.py Wed Jan 10 17:19:56 2007 @@ -7,7 +7,7 @@ filespec = macfs.FSSpec('my disk image.img') try: objref = talker.create('my disk image', saving_as=filespec, leave_image_mounted=1) -except Disk_Copy.Error, arg: +except Disk_Copy.Error as arg: print "ERROR: my disk image:", arg else: print 'objref=', objref Modified: python/branches/p3yk/Mac/Demo/imgbrowse/imgbrowse.py ============================================================================== --- python/branches/p3yk/Mac/Demo/imgbrowse/imgbrowse.py (original) +++ python/branches/p3yk/Mac/Demo/imgbrowse/imgbrowse.py Wed Jan 10 17:19:56 2007 @@ -52,7 +52,7 @@ bar = EasyDialogs.ProgressBar('Reading and converting...') try: rdr = img.reader(imgformat.macrgb16, pathname) - except img.error, arg: + except img.error as arg: EasyDialogs.Message(repr(arg)) return w, h = rdr.width, rdr.height Modified: python/branches/p3yk/Mac/Demo/mlte/mlted.py ============================================================================== --- python/branches/p3yk/Mac/Demo/mlte/mlted.py (original) +++ python/branches/p3yk/Mac/Demo/mlte/mlted.py Wed Jan 10 17:19:56 2007 @@ -275,7 +275,7 @@ fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line data = fp.read() fp.close() - except IOError, arg: + except IOError as arg: EasyDialogs.Message("IOERROR: %r" % (arg,)) return else: Modified: python/branches/p3yk/Mac/Demo/resources/copyres.py ============================================================================== --- python/branches/p3yk/Mac/Demo/resources/copyres.py (original) +++ python/branches/p3yk/Mac/Demo/resources/copyres.py Wed Jan 10 17:19:56 2007 @@ -39,7 +39,7 @@ UseResFile(output) try: res2 = Get1Resource(type, id) - except (RuntimeError, Res.Error), msg: + except (RuntimeError, Res.Error) as msg: res2 = None if res2: print "Duplicate type+id, not copied" Modified: python/branches/p3yk/Mac/Demo/textedit/ped.py ============================================================================== --- python/branches/p3yk/Mac/Demo/textedit/ped.py (original) +++ python/branches/p3yk/Mac/Demo/textedit/ped.py Wed Jan 10 17:19:56 2007 @@ -273,7 +273,7 @@ fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line data = fp.read() fp.close() - except IOError, arg: + except IOError as arg: EasyDialogs.Message("IOERROR: %r" % (arg,)) return else: Modified: python/branches/p3yk/Mac/scripts/BuildApplet.py ============================================================================== --- python/branches/p3yk/Mac/scripts/BuildApplet.py (original) +++ python/branches/p3yk/Mac/scripts/BuildApplet.py Wed Jan 10 17:19:56 2007 @@ -31,7 +31,7 @@ def main(): try: buildapplet() - except buildtools.BuildError, detail: + except buildtools.BuildError as detail: EasyDialogs.Message(detail) Modified: python/branches/p3yk/Mac/scripts/buildpkg.py ============================================================================== --- python/branches/p3yk/Mac/scripts/buildpkg.py (original) +++ python/branches/p3yk/Mac/scripts/buildpkg.py Wed Jan 10 17:19:56 2007 @@ -451,7 +451,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], shortOpts, longOpts) - except getopt.GetoptError, details: + except getopt.GetoptError as details: print details printUsage() return Modified: python/branches/p3yk/Misc/BeOS-setup.py ============================================================================== --- python/branches/p3yk/Misc/BeOS-setup.py (original) +++ python/branches/p3yk/Misc/BeOS-setup.py Wed Jan 10 17:19:56 2007 @@ -127,7 +127,7 @@ try: build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError), why: + except (CCompilerError, DistutilsError) as why: self.announce('WARNING: building of extension "%s" failed: %s' % (ext.name, sys.exc_info()[1])) Modified: python/branches/p3yk/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk/Modules/parsermodule.c (original) +++ python/branches/p3yk/Modules/parsermodule.c Wed Jan 10 17:19:56 2007 @@ -2110,8 +2110,8 @@ if (res && (nch > 1)) res = validate_test(CHILD(tree, 1)); if (res && (nch == 4)) - res = (validate_comma(CHILD(tree, 2)) - && validate_test(CHILD(tree, 3))); + res = (validate_name(CHILD(tree, 2), "as") + && validate_ntype(CHILD(tree, 3), NAME)); return (res); } Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Wed Jan 10 17:19:56 2007 @@ -1955,13 +1955,66 @@ } ADDOP(c, POP_TOP); if (handler->name) { + basicblock *cleanup_end, *cleanup_body; + expr_context_ty orig_ctx; + + assert(handler->name->kind == Name_kind); + + cleanup_end = compiler_new_block(c); + cleanup_body = compiler_new_block(c); + if(!(cleanup_end || cleanup_body)) + return 0; + VISIT(c, expr, handler->name); + ADDOP(c, POP_TOP); + + /* + try: + # body + except type as name: + try: + # body + finally: + name = None + del name + */ + + /* second try: */ + ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + + /* second # body */ + VISIT_SEQ(c, stmt, handler->body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + + /* finally: */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, cleanup_end); + if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) + return 0; + + /* name = None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + orig_ctx = handler->name->v.Name.ctx; + handler->name->v.Name.ctx = Store; + VISIT(c, expr, handler->name); + + /* del name */ + handler->name->v.Name.ctx = Del; + VISIT(c, expr, handler->name); + handler->name->v.Name.ctx = orig_ctx; + + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, cleanup_end); } else { - ADDOP(c, POP_TOP); + ADDOP(c, POP_TOP); + ADDOP(c, POP_TOP); + VISIT_SEQ(c, stmt, handler->body); } - ADDOP(c, POP_TOP); - VISIT_SEQ(c, stmt, handler->body); ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, except); if (handler->type) Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Wed Jan 10 17:19:56 2007 @@ -1049,7 +1049,7 @@ {0, 1}, }; static arc arcs_46_2[2] = { - {28, 3}, + {83, 3}, {0, 2}, }; static arc arcs_46_3[1] = { Modified: python/branches/p3yk/Tools/audiopy/audiopy ============================================================================== --- python/branches/p3yk/Tools/audiopy/audiopy (original) +++ python/branches/p3yk/Tools/audiopy/audiopy Wed Jan 10 17:19:56 2007 @@ -309,7 +309,7 @@ info.o_gain = self.__scalevar.get() try: self.__devctl.setinfo(info) - except sunaudiodev.error, msg: + except sunaudiodev.error as msg: # TBD: what to do? it's probably temporary. pass @@ -496,7 +496,8 @@ # now set the values try: device.setinfo(info) - except sunaudiodev.error, (code, msg): + except sunaudiodev.error as e: + (code, msg) = e if code <> errno.EINVAL: raise device.close() Modified: python/branches/p3yk/Tools/bgen/bgen/scantools.py ============================================================================== --- python/branches/p3yk/Tools/bgen/bgen/scantools.py (original) +++ python/branches/p3yk/Tools/bgen/bgen/scantools.py Wed Jan 10 17:19:56 2007 @@ -293,7 +293,7 @@ def openrepairfile(self, filename = "REPAIR"): try: return open(filename, "rU") - except IOError, msg: + except IOError as msg: print repr(filename), ":", msg print "Cannot open repair file -- assume no repair needed" return None @@ -419,7 +419,7 @@ def openoutput(self, filename): try: file = open(filename, 'w') - except IOError, arg: + except IOError as arg: raise IOError, (filename, arg) self.setfiletype(filename) return file @@ -460,7 +460,7 @@ # If not on the path, or absolute, try default open() try: return open(filename, 'rU') - except IOError, arg: + except IOError as arg: raise IOError, (arg, filename) def getline(self): Modified: python/branches/p3yk/Tools/compiler/compile.py ============================================================================== --- python/branches/p3yk/Tools/compiler/compile.py (original) +++ python/branches/p3yk/Tools/compiler/compile.py Wed Jan 10 17:19:56 2007 @@ -40,7 +40,7 @@ else: compileFile(filename, DISPLAY) - except SyntaxError, err: + except SyntaxError as err: print err if err.lineno is not None: print err.lineno Modified: python/branches/p3yk/Tools/compiler/regrtest.py ============================================================================== --- python/branches/p3yk/Tools/compiler/regrtest.py (original) +++ python/branches/p3yk/Tools/compiler/regrtest.py Wed Jan 10 17:19:56 2007 @@ -42,7 +42,7 @@ print file, try: compileFile(source) - except SyntaxError, err: + except SyntaxError as err: print err continue # make sure the .pyc file is not over-written Modified: python/branches/p3yk/Tools/faqwiz/faqw.py ============================================================================== --- python/branches/p3yk/Tools/faqwiz/faqw.py (original) +++ python/branches/p3yk/Tools/faqwiz/faqw.py Wed Jan 10 17:19:56 2007 @@ -24,7 +24,7 @@ os.chdir(FAQDIR) sys.path.insert(0, SRCDIR) import faqwiz -except SystemExit, n: +except SystemExit as n: sys.exit(n) except: t, v, tb = sys.exc_info() Modified: python/branches/p3yk/Tools/faqwiz/faqwiz.py ============================================================================== --- python/branches/p3yk/Tools/faqwiz/faqwiz.py (original) +++ python/branches/p3yk/Tools/faqwiz/faqwiz.py Wed Jan 10 17:19:56 2007 @@ -348,7 +348,7 @@ raise InvalidFile(file) try: fp = open(file) - except IOError, msg: + except IOError as msg: raise NoSuchFile(file, msg) try: return self.entryclass(fp, file, sec_num) @@ -387,11 +387,11 @@ else: try: meth() - except InvalidFile, exc: + except InvalidFile as exc: self.error("Invalid entry file name %s" % exc.file) - except NoSuchFile, exc: + except NoSuchFile as exc: self.error("No entry with file name %s" % exc.file) - except NoSuchSection, exc: + except NoSuchSection as exc: self.error("No section number %s" % exc.section) self.epilogue() @@ -796,7 +796,7 @@ pass try: f = open(file, 'w') - except IOError, why: + except IOError as why: self.error(CANTWRITE, file=file, why=why) return date = time.ctime(now) Modified: python/branches/p3yk/Tools/freeze/checkextensions_win32.py ============================================================================== --- python/branches/p3yk/Tools/freeze/checkextensions_win32.py (original) +++ python/branches/p3yk/Tools/freeze/checkextensions_win32.py Wed Jan 10 17:19:56 2007 @@ -131,7 +131,7 @@ dsp_path, dsp_name = os.path.split(dsp) try: lines = open(dsp, "r").readlines() - except IOError, msg: + except IOError as msg: sys.stderr.write("%s: %s\n" % (dsp, msg)) return None for line in lines: Modified: python/branches/p3yk/Tools/freeze/freeze.py ============================================================================== --- python/branches/p3yk/Tools/freeze/freeze.py (original) +++ python/branches/p3yk/Tools/freeze/freeze.py Wed Jan 10 17:19:56 2007 @@ -145,7 +145,7 @@ if sys.argv[pos] == '-i': try: options = open(sys.argv[pos+1]).read().split() - except IOError, why: + except IOError as why: usage("File name '%s' specified with the -i option " "can not be read - %s" % (sys.argv[pos+1], why) ) # Replace the '-i' and the filename with the read params. @@ -156,7 +156,7 @@ # Now parse the command line with the extras inserted. try: opts, args = getopt.getopt(sys.argv[1:], 'r:a:dEe:hmo:p:P:qs:wX:x:l:') - except getopt.error, msg: + except getopt.error as msg: usage('getopt error: ' + str(msg)) # proces option arguments @@ -311,7 +311,7 @@ try: os.mkdir(odir) print "Created output directory", odir - except os.error, msg: + except os.error as msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) base = '' if odir: @@ -333,7 +333,7 @@ try: custom_entry_point, python_entry_is_main = \ winmakemakefile.get_custom_entry_point(subsystem) - except ValueError, why: + except ValueError as why: usage(why) Modified: python/branches/p3yk/Tools/i18n/msgfmt.py ============================================================================== --- python/branches/p3yk/Tools/i18n/msgfmt.py (original) +++ python/branches/p3yk/Tools/i18n/msgfmt.py Wed Jan 10 17:19:56 2007 @@ -110,7 +110,7 @@ try: lines = open(infile).readlines() - except IOError, msg: + except IOError as msg: print >> sys.stderr, msg sys.exit(1) @@ -167,7 +167,7 @@ try: open(outfile,"wb").write(output) - except IOError,msg: + except IOError as msg: print >> sys.stderr, msg @@ -176,7 +176,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'hVo:', ['help', 'version', 'output-file=']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) outfile = None Modified: python/branches/p3yk/Tools/i18n/pygettext.py ============================================================================== --- python/branches/p3yk/Tools/i18n/pygettext.py (original) +++ python/branches/p3yk/Tools/i18n/pygettext.py Wed Jan 10 17:19:56 2007 @@ -512,7 +512,7 @@ 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', 'no-docstrings', ]) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) # for holding option values @@ -635,7 +635,7 @@ eater.set_filename(filename) try: tokenize.tokenize(fp.readline, eater) - except tokenize.TokenError, e: + except tokenize.TokenError as e: print >> sys.stderr, '%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]) finally: Modified: python/branches/p3yk/Tools/pybench/CommandLine.py ============================================================================== --- python/branches/p3yk/Tools/pybench/CommandLine.py (original) +++ python/branches/p3yk/Tools/pybench/CommandLine.py Wed Jan 10 17:19:56 2007 @@ -347,7 +347,7 @@ if rc is None: rc = 0 - except SystemExit,rc: + except SystemExit as rc: pass except KeyboardInterrupt: @@ -433,7 +433,7 @@ files = l self.optionlist = optlist self.files = files + self.files - except getopt.error,why: + except getopt.error as why: self.help(why) sys.exit(1) Modified: python/branches/p3yk/Tools/pybench/pybench.py ============================================================================== --- python/branches/p3yk/Tools/pybench/pybench.py (original) +++ python/branches/p3yk/Tools/pybench/pybench.py Wed Jan 10 17:19:56 2007 @@ -865,7 +865,7 @@ bench.name = compare_to f.close() compare_to = bench - except IOError, reason: + except IOError as reason: print '* Error opening/reading file %s: %s' % ( repr(compare_to), reason) @@ -885,7 +885,7 @@ else: bench.print_benchmark(hidenoise=hidenoise, limitnames=limitnames) - except IOError, reason: + except IOError as reason: print '* Error opening/reading file %s: %s' % ( repr(show_bench), reason) @@ -931,9 +931,9 @@ bench.name = reportfile pickle.dump(bench,f) f.close() - except IOError, reason: + except IOError as reason: print '* Error opening/writing reportfile' - except IOError, reason: + except IOError as reason: print '* Error opening/writing reportfile %s: %s' % ( reportfile, reason) Modified: python/branches/p3yk/Tools/pynche/Main.py ============================================================================== --- python/branches/p3yk/Tools/pynche/Main.py (original) +++ python/branches/p3yk/Tools/pynche/Main.py Wed Jan 10 17:19:56 2007 @@ -186,7 +186,7 @@ sys.argv[1:], 'hd:i:Xv', ['database=', 'initfile=', 'ignore', 'help', 'version']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) if len(args) == 0: Modified: python/branches/p3yk/Tools/scripts/byext.py ============================================================================== --- python/branches/p3yk/Tools/scripts/byext.py (original) +++ python/branches/p3yk/Tools/scripts/byext.py Wed Jan 10 17:19:56 2007 @@ -24,7 +24,7 @@ self.addstats("", "dirs", 1) try: names = os.listdir(dir) - except os.error, err: + except os.error as err: sys.stderr.write("Can't list %s: %s\n" % (dir, err)) self.addstats("", "unlistable", 1) return @@ -53,7 +53,7 @@ self.addstats(ext, "files", 1) try: f = open(filename, "rb") - except IOError, err: + except IOError as err: sys.stderr.write("Can't open %s: %s\n" % (filename, err)) self.addstats(ext, "unopenable", 1) return Modified: python/branches/p3yk/Tools/scripts/byteyears.py ============================================================================== --- python/branches/p3yk/Tools/scripts/byteyears.py (original) +++ python/branches/p3yk/Tools/scripts/byteyears.py Wed Jan 10 17:19:56 2007 @@ -43,7 +43,7 @@ for filename in sys.argv[1:]: try: st = statfunc(filename) - except os.error, msg: + except os.error as msg: sys.stderr.write("can't stat %r: %r\n" % (filename, msg)) status = 1 st = () Modified: python/branches/p3yk/Tools/scripts/checkappend.py ============================================================================== --- python/branches/p3yk/Tools/scripts/checkappend.py (original) +++ python/branches/p3yk/Tools/scripts/checkappend.py Wed Jan 10 17:19:56 2007 @@ -50,7 +50,7 @@ global verbose try: opts, args = getopt.getopt(sys.argv[1:], "v") - except getopt.error, msg: + except getopt.error as msg: errprint(str(msg) + "\n\n" + __doc__) return for opt, optarg in opts: @@ -77,7 +77,7 @@ try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return @@ -104,7 +104,7 @@ def run(self): try: tokenize.tokenize(self.file.readline, self.tokeneater) - except tokenize.TokenError, msg: + except tokenize.TokenError as msg: errprint("%r: Token Error: %s" % (self.fname, msg)) self.nerrors = self.nerrors + 1 return self.nerrors == 0 Modified: python/branches/p3yk/Tools/scripts/classfix.py ============================================================================== --- python/branches/p3yk/Tools/scripts/classfix.py (original) +++ python/branches/p3yk/Tools/scripts/classfix.py Wed Jan 10 17:19:56 2007 @@ -62,7 +62,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -83,7 +83,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -106,7 +106,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -130,17 +130,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk/Tools/scripts/cleanfuture.py ============================================================================== --- python/branches/p3yk/Tools/scripts/cleanfuture.py (original) +++ python/branches/p3yk/Tools/scripts/cleanfuture.py Wed Jan 10 17:19:56 2007 @@ -59,7 +59,7 @@ global verbose, recurse, dryrun try: opts, args = getopt.getopt(sys.argv[1:], "drv") - except getopt.error, msg: + except getopt.error as msg: errprint(msg) return for o, a in opts: @@ -92,7 +92,7 @@ print "checking", file, "...", try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%r: I/O Error: %s" % (file, str(msg))) return Modified: python/branches/p3yk/Tools/scripts/cvsfiles.py ============================================================================== --- python/branches/p3yk/Tools/scripts/cvsfiles.py (original) +++ python/branches/p3yk/Tools/scripts/cvsfiles.py Wed Jan 10 17:19:56 2007 @@ -20,7 +20,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "n:") - except getopt.error, msg: + except getopt.error as msg: print msg print __doc__, return 1 Modified: python/branches/p3yk/Tools/scripts/dutree.py ============================================================================== --- python/branches/p3yk/Tools/scripts/dutree.py (original) +++ python/branches/p3yk/Tools/scripts/dutree.py Wed Jan 10 17:19:56 2007 @@ -18,7 +18,7 @@ total, d = store(size, comps, total, d) try: display(total, d) - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk/Tools/scripts/finddiv.py ============================================================================== --- python/branches/p3yk/Tools/scripts/finddiv.py (original) +++ python/branches/p3yk/Tools/scripts/finddiv.py Wed Jan 10 17:19:56 2007 @@ -23,7 +23,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "lh") - except getopt.error, msg: + except getopt.error as msg: usage(msg) return 2 if not args: @@ -52,7 +52,7 @@ return processdir(filename, listnames) try: fp = open(filename) - except IOError, msg: + except IOError as msg: sys.stderr.write("Can't open: %s\n" % msg) return 1 g = tokenize.generate_tokens(fp.readline) @@ -70,7 +70,7 @@ def processdir(dir, listnames): try: names = os.listdir(dir) - except os.error, msg: + except os.error as msg: sys.stderr.write("Can't list directory: %s\n" % dir) return 1 files = [] Modified: python/branches/p3yk/Tools/scripts/findlinksto.py ============================================================================== --- python/branches/p3yk/Tools/scripts/findlinksto.py (original) +++ python/branches/p3yk/Tools/scripts/findlinksto.py Wed Jan 10 17:19:56 2007 @@ -14,7 +14,7 @@ opts, args = getopt.getopt(sys.argv[1:], '') if len(args) < 2: raise getopt.GetoptError('not enough arguments', None) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: sys.stdout = sys.stderr print msg print 'usage: findlinksto pattern directory ...' Modified: python/branches/p3yk/Tools/scripts/findnocoding.py ============================================================================== --- python/branches/p3yk/Tools/scripts/findnocoding.py (original) +++ python/branches/p3yk/Tools/scripts/findnocoding.py Wed Jan 10 17:19:56 2007 @@ -78,7 +78,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'cd') -except getopt.error, msg: +except getopt.error as msg: print >>sys.stderr, msg print >>sys.stderr, usage sys.exit(1) Modified: python/branches/p3yk/Tools/scripts/fixcid.py ============================================================================== --- python/branches/p3yk/Tools/scripts/fixcid.py (original) +++ python/branches/p3yk/Tools/scripts/fixcid.py Wed Jan 10 17:19:56 2007 @@ -62,7 +62,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'crs:') - except getopt.error, msg: + except getopt.error as msg: err('Options error: ' + str(msg) + '\n') usage() sys.exit(2) @@ -97,7 +97,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err(dirname + ': cannot list directory: ' + str(msg) + '\n') return 1 names.sort() @@ -124,7 +124,7 @@ # File replacement mode try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err(filename + ': cannot open: ' + str(msg) + '\n') return 1 head, tail = os.path.split(filename) @@ -148,7 +148,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err(tempname+': cannot create: '+ str(msg)+'\n') @@ -175,17 +175,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err(tempname + ': warning: chmod failed (' + str(msg) + ')\n') # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err(filename + ': warning: backup failed (' + str(msg) + ')\n') # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err(filename + ': rename failed (' + str(msg) + ')\n') return 1 # Return succes @@ -276,7 +276,7 @@ def addsubst(substfile): try: fp = open(substfile, 'r') - except IOError, msg: + except IOError as msg: err(substfile + ': cannot read substfile: ' + str(msg) + '\n') sys.exit(1) lineno = 0 Modified: python/branches/p3yk/Tools/scripts/fixdiv.py ============================================================================== --- python/branches/p3yk/Tools/scripts/fixdiv.py (original) +++ python/branches/p3yk/Tools/scripts/fixdiv.py Wed Jan 10 17:19:56 2007 @@ -140,7 +140,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hm") - except getopt.error, msg: + except getopt.error as msg: usage(msg) return 2 for o, a in opts: @@ -181,7 +181,7 @@ prog = re.compile(PATTERN) try: f = open(warningsfile) - except IOError, msg: + except IOError as msg: sys.stderr.write("can't open: %s\n" % msg) return warnings = {} @@ -207,7 +207,7 @@ assert list # if this fails, readwarnings() is broken try: fp = open(filename) - except IOError, msg: + except IOError as msg: sys.stderr.write("can't open: %s\n" % msg) return 1 print "Index:", filename Modified: python/branches/p3yk/Tools/scripts/fixheader.py ============================================================================== --- python/branches/p3yk/Tools/scripts/fixheader.py (original) +++ python/branches/p3yk/Tools/scripts/fixheader.py Wed Jan 10 17:19:56 2007 @@ -12,7 +12,7 @@ def process(filename): try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: can\'t open: %s\n' % (filename, str(msg))) return data = f.read() @@ -22,7 +22,7 @@ return try: f = open(filename, 'w') - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: can\'t write: %s\n' % (filename, str(msg))) return sys.stderr.write('Processing %s ...\n' % filename) Modified: python/branches/p3yk/Tools/scripts/fixnotice.py ============================================================================== --- python/branches/p3yk/Tools/scripts/fixnotice.py (original) +++ python/branches/p3yk/Tools/scripts/fixnotice.py Wed Jan 10 17:19:56 2007 @@ -62,7 +62,7 @@ opts, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'oldnotice=', 'newnotice=', 'dry-run', 'verbose']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) for opt, arg in opts: Modified: python/branches/p3yk/Tools/scripts/fixps.py ============================================================================== --- python/branches/p3yk/Tools/scripts/fixps.py (original) +++ python/branches/p3yk/Tools/scripts/fixps.py Wed Jan 10 17:19:56 2007 @@ -11,7 +11,7 @@ for filename in sys.argv[1:]: try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: print filename, ': can\'t open :', msg continue line = f.readline() Modified: python/branches/p3yk/Tools/scripts/ftpmirror.py ============================================================================== --- python/branches/p3yk/Tools/scripts/ftpmirror.py (original) +++ python/branches/p3yk/Tools/scripts/ftpmirror.py Wed Jan 10 17:19:56 2007 @@ -45,7 +45,7 @@ global verbose, interactive, mac, rmok, nologin try: opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v') - except getopt.error, msg: + except getopt.error as msg: usage(msg) login = '' passwd = '' @@ -108,13 +108,13 @@ if verbose: print 'Creating local directory', repr(localdir) try: makedir(localdir) - except os.error, msg: + except os.error as msg: print "Failed to establish local directory", repr(localdir) return infofilename = os.path.join(localdir, '.mirrorinfo') try: text = open(infofilename, 'r').read() - except IOError, msg: + except IOError as msg: text = '{}' try: info = eval(text) @@ -190,13 +190,13 @@ print "Creating symlink %r -> %r" % (filename, linkto) try: os.symlink(linkto, tempname) - except IOError, msg: + except IOError as msg: print "Can't create %r: %s" % (tempname, msg) continue else: try: fp = open(tempname, 'wb') - except IOError, msg: + except IOError as msg: print "Can't create %r: %s" % (tempname, msg) continue if verbose: @@ -209,7 +209,7 @@ try: f.retrbinary('RETR ' + filename, fp1.write, 8*1024) - except ftplib.error_perm, msg: + except ftplib.error_perm as msg: print msg t1 = time.time() bytes = fp.tell() @@ -222,7 +222,7 @@ pass # Ignore the error try: os.rename(tempname, fullname) - except os.error, msg: + except os.error as msg: print "Can't rename %r to %r: %s" % (tempname, fullname, msg) continue info[filename] = infostuff @@ -292,7 +292,7 @@ print 'Remote cwd', repr(subdir) try: f.cwd(subdir) - except ftplib.error_perm, msg: + except ftplib.error_perm as msg: print "Can't chdir to", repr(subdir), ":", repr(msg) else: if verbose: print 'Mirroring as', repr(localsubdir) @@ -322,13 +322,13 @@ return 0 try: os.rmdir(fullname) - except os.error, msg: + except os.error as msg: print "Can't remove local directory %r: %s" % (fullname, msg) return 0 else: try: os.unlink(fullname) - except os.error, msg: + except os.error as msg: print "Can't remove local file %r: %s" % (fullname, msg) return 0 return 1 Modified: python/branches/p3yk/Tools/scripts/linktree.py ============================================================================== --- python/branches/p3yk/Tools/scripts/linktree.py (original) +++ python/branches/p3yk/Tools/scripts/linktree.py Wed Jan 10 17:19:56 2007 @@ -32,13 +32,13 @@ return 1 try: os.mkdir(newtree, 0777) - except os.error, msg: + except os.error as msg: print newtree + ': cannot mkdir:', msg return 1 linkname = os.path.join(newtree, link) try: os.symlink(os.path.join(os.pardir, oldtree), linkname) - except os.error, msg: + except os.error as msg: if not link_may_fail: print linkname + ': cannot symlink:', msg return 1 @@ -51,7 +51,7 @@ if debug: print 'linknames', (old, new, link) try: names = os.listdir(old) - except os.error, msg: + except os.error as msg: print old + ': warning: cannot listdir:', msg return for name in names: Modified: python/branches/p3yk/Tools/scripts/logmerge.py ============================================================================== --- python/branches/p3yk/Tools/scripts/logmerge.py (original) +++ python/branches/p3yk/Tools/scripts/logmerge.py Wed Jan 10 17:19:56 2007 @@ -180,6 +180,6 @@ if __name__ == '__main__': try: main() - except IOError, e: + except IOError as e: if e.errno != errno.EPIPE: raise Modified: python/branches/p3yk/Tools/scripts/md5sum.py ============================================================================== --- python/branches/p3yk/Tools/scripts/md5sum.py (original) +++ python/branches/p3yk/Tools/scripts/md5sum.py Wed Jan 10 17:19:56 2007 @@ -43,7 +43,7 @@ def printsum(filename, out=sys.stdout): try: fp = open(filename, rmode) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) return 1 if fnfilter: @@ -60,7 +60,7 @@ if not data: break m.update(data) - except IOError, msg: + except IOError as msg: sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) return 1 out.write('%s %s\n' % (m.hexdigest(), filename)) @@ -70,7 +70,7 @@ global fnfilter, rmode, bufsize try: opts, args = getopt.getopt(args, 'blts:') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage)) return 2 for o, a in opts: Modified: python/branches/p3yk/Tools/scripts/methfix.py ============================================================================== --- python/branches/p3yk/Tools/scripts/methfix.py (original) +++ python/branches/p3yk/Tools/scripts/methfix.py Wed Jan 10 17:19:56 2007 @@ -59,7 +59,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -80,7 +80,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 head, tail = os.path.split(filename) @@ -117,7 +117,7 @@ if g is None: try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -141,17 +141,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk/Tools/scripts/ndiff.py ============================================================================== --- python/branches/p3yk/Tools/scripts/ndiff.py (original) +++ python/branches/p3yk/Tools/scripts/ndiff.py Wed Jan 10 17:19:56 2007 @@ -61,7 +61,7 @@ def fopen(fname): try: return open(fname, 'U') - except IOError, detail: + except IOError as detail: return fail("couldn't open " + fname + ": " + str(detail)) # open two files & spray the diff to stdout; return false iff a problem @@ -85,7 +85,7 @@ import getopt try: opts, args = getopt.getopt(args, "qr:") - except getopt.error, detail: + except getopt.error as detail: return fail(str(detail)) noisy = 1 qseen = rseen = 0 Modified: python/branches/p3yk/Tools/scripts/pathfix.py ============================================================================== --- python/branches/p3yk/Tools/scripts/pathfix.py (original) +++ python/branches/p3yk/Tools/scripts/pathfix.py Wed Jan 10 17:19:56 2007 @@ -37,7 +37,7 @@ sys.argv[0]) try: opts, args = getopt.getopt(sys.argv[1:], 'i:') - except getopt.error, msg: + except getopt.error as msg: err(msg + '\n') err(usage) sys.exit(2) @@ -68,7 +68,7 @@ bad = 0 try: names = os.listdir(dirname) - except os.error, msg: + except os.error as msg: err('%s: cannot list directory: %r\n' % (dirname, msg)) return 1 names.sort() @@ -89,7 +89,7 @@ ## dbg('fix(%r)\n' % (filename,)) try: f = open(filename, 'r') - except IOError, msg: + except IOError as msg: err('%s: cannot open: %r\n' % (filename, msg)) return 1 line = f.readline() @@ -102,7 +102,7 @@ tempname = os.path.join(head, '@' + tail) try: g = open(tempname, 'w') - except IOError, msg: + except IOError as msg: f.close() err('%s: cannot create: %r\n' % (tempname, msg)) return 1 @@ -122,17 +122,17 @@ try: statbuf = os.stat(filename) os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: + except os.error as msg: err('%s: warning: chmod failed (%r)\n' % (tempname, msg)) # Then make a backup of the original file as filename~ try: os.rename(filename, filename + '~') - except os.error, msg: + except os.error as msg: err('%s: warning: backup failed (%r)\n' % (filename, msg)) # Now move the temp file to the original file try: os.rename(tempname, filename) - except os.error, msg: + except os.error as msg: err('%s: rename failed (%r)\n' % (filename, msg)) return 1 # Return succes Modified: python/branches/p3yk/Tools/scripts/pindent.py ============================================================================== --- python/branches/p3yk/Tools/scripts/pindent.py (original) +++ python/branches/p3yk/Tools/scripts/pindent.py Wed Jan 10 17:19:56 2007 @@ -491,7 +491,7 @@ import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'cdrs:t:e') - except getopt.error, msg: + except getopt.error as msg: sys.stderr.write('Error: %s\n' % msg) sys.stderr.write(usage) sys.exit(2) Modified: python/branches/p3yk/Tools/scripts/pysource.py ============================================================================== --- python/branches/p3yk/Tools/scripts/pysource.py (original) +++ python/branches/p3yk/Tools/scripts/pysource.py Wed Jan 10 17:19:56 2007 @@ -33,7 +33,7 @@ def _open(fullpath): try: size = os.stat(fullpath).st_size - except OSError, err: # Permission denied - ignore the file + except OSError as err: # Permission denied - ignore the file print_debug("%s: permission denied: %s" % (fullpath, err)) return None @@ -43,7 +43,7 @@ try: return open(fullpath, 'rU') - except IOError, err: # Access denied, or a special file - ignore it + except IOError as err: # Access denied, or a special file - ignore it print_debug("%s: access denied: %s" % (fullpath, err)) return None @@ -81,7 +81,7 @@ try: compile(code, fullpath, "exec") - except Exception, err: + except Exception as err: print_debug("%s: cannot compile: %s" % (fullpath, err)) return False Modified: python/branches/p3yk/Tools/scripts/redemo.py ============================================================================== --- python/branches/p3yk/Tools/scripts/redemo.py (original) +++ python/branches/p3yk/Tools/scripts/redemo.py Wed Jan 10 17:19:56 2007 @@ -104,7 +104,7 @@ self.getflags()) bg = self.promptdisplay['background'] self.statusdisplay.config(text="", background=bg) - except re.error, msg: + except re.error as msg: self.compiled = None self.statusdisplay.config( text="re.error: %s" % str(msg), Modified: python/branches/p3yk/Tools/scripts/reindent.py ============================================================================== --- python/branches/p3yk/Tools/scripts/reindent.py (original) +++ python/branches/p3yk/Tools/scripts/reindent.py Wed Jan 10 17:19:56 2007 @@ -61,7 +61,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], "drvh", ["dryrun", "recurse", "verbose", "help"]) - except getopt.error, msg: + except getopt.error as msg: usage(msg) return for o, a in opts: @@ -99,7 +99,7 @@ print "checking", file, "...", try: f = open(file) - except IOError, msg: + except IOError as msg: errprint("%s: I/O Error: %s" % (file, str(msg))) return Modified: python/branches/p3yk/Tools/scripts/rgrep.py ============================================================================== --- python/branches/p3yk/Tools/scripts/rgrep.py (original) +++ python/branches/p3yk/Tools/scripts/rgrep.py Wed Jan 10 17:19:56 2007 @@ -23,11 +23,11 @@ pattern, filename = args try: prog = re.compile(pattern, reflags) - except re.error, msg: + except re.error as msg: usage("error in regular expression: %s" % str(msg)) try: f = open(filename) - except IOError, msg: + except IOError as msg: usage("can't open %s: %s" % (repr(filename), str(msg)), 1) f.seek(0, 2) pos = f.tell() Modified: python/branches/p3yk/Tools/scripts/texi2html.py ============================================================================== --- python/branches/p3yk/Tools/scripts/texi2html.py (original) +++ python/branches/p3yk/Tools/scripts/texi2html.py Wed Jan 10 17:19:56 2007 @@ -554,7 +554,7 @@ file = os.path.join(self.includedir, file) try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print '*** Can\'t open include file', repr(file) return print '!'*self.debugging, '--> file', repr(file) @@ -1797,7 +1797,7 @@ print>>fp, '' self.dumpfiles(fp) fp.close() - except IOError, msg: + except IOError as msg: print projectfile, ':', msg sys.exit(1) @@ -1822,7 +1822,7 @@ print>>fp, '' print>>fp, '' fp.close() - except IOError, msg: + except IOError as msg: print contentfile, ':', msg sys.exit(1) @@ -1844,7 +1844,7 @@ print>>fp, '' print>>fp, '' fp.close() - except IOError, msg: + except IOError as msg: print indexfile , ':', msg sys.exit(1) @@ -2063,7 +2063,7 @@ try: fp = open(file, 'r') - except IOError, msg: + except IOError as msg: print file, ':', msg sys.exit(1) Modified: python/branches/p3yk/Tools/scripts/treesync.py ============================================================================== --- python/branches/p3yk/Tools/scripts/treesync.py (original) +++ python/branches/p3yk/Tools/scripts/treesync.py Wed Jan 10 17:19:56 2007 @@ -78,7 +78,7 @@ print "creating slave directory", slave try: os.mkdir(slave) - except os.error, msg: + except os.error as msg: print "can't make slave directory", slave, ":", msg return else: Modified: python/branches/p3yk/Tools/scripts/untabify.py ============================================================================== --- python/branches/p3yk/Tools/scripts/untabify.py (original) +++ python/branches/p3yk/Tools/scripts/untabify.py Wed Jan 10 17:19:56 2007 @@ -12,7 +12,7 @@ opts, args = getopt.getopt(sys.argv[1:], "t:") if not args: raise getopt.error, "At least one file argument required" - except getopt.error, msg: + except getopt.error as msg: print msg print "usage:", sys.argv[0], "[-t tabwidth] file ..." return @@ -28,7 +28,7 @@ f = open(filename) text = f.read() f.close() - except IOError, msg: + except IOError as msg: print "%r: I/O error: %s" % (filename, msg) return newtext = text.expandtabs(tabsize) Modified: python/branches/p3yk/Tools/unicode/comparecodecs.py ============================================================================== --- python/branches/p3yk/Tools/unicode/comparecodecs.py (original) +++ python/branches/p3yk/Tools/unicode/comparecodecs.py Wed Jan 10 17:19:56 2007 @@ -18,11 +18,11 @@ u = unichr(i) try: c1 = u.encode(encoding1) - except UnicodeError, reason: + except UnicodeError as reason: c1 = '' try: c2 = u.encode(encoding2) - except UnicodeError, reason: + except UnicodeError as reason: c2 = '' if c1 != c2: print ' * encoding mismatch for 0x%04X: %-14r != %r' % \ Modified: python/branches/p3yk/Tools/unicode/gencodec.py ============================================================================== --- python/branches/p3yk/Tools/unicode/gencodec.py (original) +++ python/branches/p3yk/Tools/unicode/gencodec.py Wed Jan 10 17:19:56 2007 @@ -130,7 +130,7 @@ try: return '(' + ', '.join(['0x%0*X' % (precision, item) for item in t]) + ')' - except TypeError, why: + except TypeError as why: print '* failed to convert %r: %s' % (t, why) raise @@ -393,7 +393,7 @@ else: pymap(mappathname, map, dirprefix + codefile,name,comments) marshalmap(mappathname, map, dirprefix + marshalfile) - except ValueError, why: + except ValueError as why: print '* conversion failed: %s' % why raise @@ -414,7 +414,7 @@ print '* map is empty; skipping' else: pymap(mapname, map, dirprefix + codefile,name,comments) - except ValueError, why: + except ValueError as why: print '* conversion failed: %s' % why if __name__ == '__main__': Modified: python/branches/p3yk/Tools/unicode/listcodecs.py ============================================================================== --- python/branches/p3yk/Tools/unicode/listcodecs.py (original) +++ python/branches/p3yk/Tools/unicode/listcodecs.py Wed Jan 10 17:19:56 2007 @@ -22,7 +22,7 @@ except LookupError: # Codec not found continue - except Exception, reason: + except Exception as reason: # Probably an error from importing the codec; still it's # a valid code name if _debug: Modified: python/branches/p3yk/Tools/versioncheck/pyversioncheck.py ============================================================================== --- python/branches/p3yk/Tools/versioncheck/pyversioncheck.py (original) +++ python/branches/p3yk/Tools/versioncheck/pyversioncheck.py Wed Jan 10 17:19:56 2007 @@ -49,7 +49,7 @@ print ' Checking %s'%url try: fp = urllib.urlopen(url) - except IOError, arg: + except IOError as arg: if verbose >= VERBOSE_EACHFILE: print ' Cannot open:', arg return -1, None, None Modified: python/branches/p3yk/Tools/webchecker/wcgui.py ============================================================================== --- python/branches/p3yk/Tools/webchecker/wcgui.py (original) +++ python/branches/p3yk/Tools/webchecker/wcgui.py Wed Jan 10 17:19:56 2007 @@ -74,7 +74,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print __doc__%vars(webchecker) Modified: python/branches/p3yk/Tools/webchecker/webchecker.py ============================================================================== --- python/branches/p3yk/Tools/webchecker/webchecker.py (original) +++ python/branches/p3yk/Tools/webchecker/webchecker.py Wed Jan 10 17:19:56 2007 @@ -153,7 +153,7 @@ try: opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa') - except getopt.error, msg: + except getopt.error as msg: sys.stdout = sys.stderr print msg print __doc__%globals() @@ -335,7 +335,7 @@ rp.set_url(url) try: rp.read() - except (OSError, IOError), msg: + except (OSError, IOError) as msg: self.note(1, "I/O error parsing %s: %s", url, msg) def run(self): @@ -402,7 +402,7 @@ return try: page = self.getpage(url_pair) - except sgmllib.SGMLParseError, msg: + except sgmllib.SGMLParseError as msg: msg = self.sanitize(msg) self.note(0, "Error parsing %s: %s", self.format_url(url_pair), msg) @@ -541,7 +541,7 @@ url, fragment = url_pair try: return self.urlopener.open(url) - except (OSError, IOError), msg: + except (OSError, IOError) as msg: msg = self.sanitize(msg) self.note(0, "Error %s", msg) if self.verbose > 0: @@ -759,7 +759,7 @@ return self.open_file(url + "index.html") try: names = os.listdir(path) - except os.error, msg: + except os.error as msg: exc_type, exc_value, exc_tb = sys.exc_info() raise IOError, msg, exc_tb names.sort() Modified: python/branches/p3yk/Tools/webchecker/websucker.py ============================================================================== --- python/branches/p3yk/Tools/webchecker/websucker.py (original) +++ python/branches/p3yk/Tools/webchecker/websucker.py Wed Jan 10 17:19:56 2007 @@ -21,7 +21,7 @@ verbose = webchecker.VERBOSE try: opts, args = getopt.getopt(sys.argv[1:], "qv") - except getopt.error, msg: + except getopt.error as msg: print msg print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..." return 2 @@ -83,7 +83,7 @@ f.write(text) f.close() self.message("saved %s", path) - except IOError, msg: + except IOError as msg: self.message("didn't save %s: %s", path, str(msg)) def savefilename(self, url): Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Wed Jan 10 17:19:56 2007 @@ -186,7 +186,7 @@ try: build_ext.build_extension(self, ext) - except (CCompilerError, DistutilsError), why: + except (CCompilerError, DistutilsError) as why: self.announce('WARNING: building of extension "%s" failed: %s' % (ext.name, sys.exc_info()[1])) return @@ -208,7 +208,7 @@ self.get_ext_filename(self.get_ext_fullname(ext.name))) try: imp.load_dynamic(ext.name, ext_filename) - except ImportError, why: + except ImportError as why: self.announce('*** WARNING: renaming "%s" since importing it' ' failed: %s' % (ext.name, why), level=3) assert not self.inplace From python-3000-checkins at python.org Sun Jan 14 00:54:40 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 00:54:40 +0100 (CET) Subject: [Python-3000-checkins] r53417 - python/branches/p3yk/Tools/pybench/CommandLine.py python/branches/p3yk/Tools/pybench/Dict.py python/branches/p3yk/Tools/pybench/Exceptions.py python/branches/p3yk/Tools/pybench/Lookups.py Message-ID: <20070113235440.229771E4004@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 00:54:39 2007 New Revision: 53417 Modified: python/branches/p3yk/Tools/pybench/CommandLine.py python/branches/p3yk/Tools/pybench/Dict.py python/branches/p3yk/Tools/pybench/Exceptions.py python/branches/p3yk/Tools/pybench/Lookups.py Log: Fix pybench so it works -- Larry Hastings. Modified: python/branches/p3yk/Tools/pybench/CommandLine.py ============================================================================== --- python/branches/p3yk/Tools/pybench/CommandLine.py (original) +++ python/branches/p3yk/Tools/pybench/CommandLine.py Sun Jan 14 00:54:39 2007 @@ -165,7 +165,7 @@ def __init__(self,name,help=None): if not name[:1] == '-': - raise TypeError,'option names must start with "-"' + raise TypeError('option names must start with "-"') if name[1:2] == '-': self.prefix = '--' self.name = name[2:] @@ -324,30 +324,32 @@ # Append preset options for option in self.preset_options: - if not self.option_map.has_key(option.name): + if not option.name in self.option_map: self.add_option(option) # Init .files list self.files = [] # Start Application + rc = 0 try: # Process startup rc = self.startup() if rc is not None: - raise SystemExit,rc + raise SystemExit(rc) # Parse command line rc = self.parse() if rc is not None: - raise SystemExit,rc + raise SystemExit(rc) # Start application rc = self.main() if rc is None: rc = 0 - except SystemExit as rc: + except SystemExit as rcException: + rc = rcException pass except KeyboardInterrupt: @@ -367,7 +369,7 @@ print rc = 1 - raise SystemExit,rc + raise SystemExit(rc) def add_option(self, option): @@ -398,7 +400,7 @@ program. It defaults to 0 which usually means: OK. """ - raise SystemExit, rc + raise SystemExit(rc) def parse(self): @@ -459,7 +461,7 @@ except AttributeError: if value == '': # count the number of occurances - if values.has_key(optionname): + if optionname in values: values[optionname] = values[optionname] + 1 else: values[optionname] = 1 @@ -468,7 +470,7 @@ else: rc = handler(value) if rc is not None: - raise SystemExit, rc + raise SystemExit(rc) # Apply final file check (for backward compatibility) rc = self.check_files(self.files) Modified: python/branches/p3yk/Tools/pybench/Dict.py ============================================================================== --- python/branches/p3yk/Tools/pybench/Dict.py (original) +++ python/branches/p3yk/Tools/pybench/Dict.py Sun Jan 14 00:54:39 2007 @@ -351,7 +351,7 @@ def test(self): d = {} - has_key = d.has_key + has_key = lambda key: key in d for i in xrange(self.rounds): @@ -498,7 +498,7 @@ def calibrate(self): d = {} - has_key = d.has_key + has_key = lambda key: key in d for i in xrange(self.rounds): pass Modified: python/branches/p3yk/Tools/pybench/Exceptions.py ============================================================================== --- python/branches/p3yk/Tools/pybench/Exceptions.py (original) +++ python/branches/p3yk/Tools/pybench/Exceptions.py Sun Jan 14 00:54:39 2007 @@ -20,15 +20,15 @@ except: pass try: - raise error,"something" + raise error("something") except: pass try: - raise error,"something" + raise error("something") except: pass try: - raise error,"something" + raise error("something") except: pass try: Modified: python/branches/p3yk/Tools/pybench/Lookups.py ============================================================================== --- python/branches/p3yk/Tools/pybench/Lookups.py (original) +++ python/branches/p3yk/Tools/pybench/Lookups.py Sun Jan 14 00:54:39 2007 @@ -774,11 +774,11 @@ l.sort l.sort - d.has_key - d.has_key - d.has_key - d.has_key - d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key d.items d.items @@ -810,11 +810,11 @@ l.sort l.sort - d.has_key - d.has_key - d.has_key - d.has_key - d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key d.items d.items @@ -846,11 +846,11 @@ l.sort l.sort - d.has_key - d.has_key - d.has_key - d.has_key - d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key d.items d.items @@ -882,11 +882,11 @@ l.sort l.sort - d.has_key - d.has_key - d.has_key - d.has_key - d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key d.items d.items @@ -918,11 +918,11 @@ l.sort l.sort - d.has_key - d.has_key - d.has_key - d.has_key - d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key + # d.has_key d.items d.items From python-3000-checkins at python.org Sun Jan 14 04:32:08 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 04:32:08 +0100 (CET) Subject: [Python-3000-checkins] r53421 - in python/branches/p3yk: BROKEN_TESTS INTBENCH Include/abstract.h Include/boolobject.h Include/intobject.h Include/longobject.h Lib/pickle.py Lib/test/output/test_class Lib/test/test_builtin.py Lib/test/test_descr.py Lib/test/test_marshal.py Lib/test/test_optparse.py Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/callproc.c Modules/_cursesmodule.c Modules/_sre.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/cPickle.c Modules/cjkcodecs/multibytecodec.c Modules/datetimemodule.c Modules/dlmodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/timemodule.c Objects/abstract.c Objects/boolobject.c Objects/complexobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/stringobject.c Objects/unicodeobject.c PC/_msi.c Python/bltinmodule.c Python/ceval.c Python/getargs.c Python/marshal.c Python/pythonrun.c Python/traceback.c Message-ID: <20070114033208.322F51E400C@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 04:31:43 2007 New Revision: 53421 Added: python/branches/p3yk/BROKEN_TESTS (contents, props changed) python/branches/p3yk/INTBENCH (contents, props changed) Modified: python/branches/p3yk/Include/abstract.h python/branches/p3yk/Include/boolobject.h python/branches/p3yk/Include/intobject.h python/branches/p3yk/Include/longobject.h python/branches/p3yk/Lib/pickle.py python/branches/p3yk/Lib/test/output/test_class python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_marshal.py python/branches/p3yk/Lib/test/test_optparse.py python/branches/p3yk/Modules/_csv.c python/branches/p3yk/Modules/_ctypes/_ctypes.c python/branches/p3yk/Modules/_ctypes/callproc.c python/branches/p3yk/Modules/_cursesmodule.c python/branches/p3yk/Modules/_sre.c python/branches/p3yk/Modules/_struct.c python/branches/p3yk/Modules/_testcapimodule.c python/branches/p3yk/Modules/_tkinter.c python/branches/p3yk/Modules/cPickle.c python/branches/p3yk/Modules/cjkcodecs/multibytecodec.c python/branches/p3yk/Modules/datetimemodule.c python/branches/p3yk/Modules/dlmodule.c python/branches/p3yk/Modules/posixmodule.c python/branches/p3yk/Modules/socketmodule.c python/branches/p3yk/Modules/timemodule.c python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/boolobject.c python/branches/p3yk/Objects/complexobject.c python/branches/p3yk/Objects/exceptions.c python/branches/p3yk/Objects/fileobject.c python/branches/p3yk/Objects/floatobject.c python/branches/p3yk/Objects/frameobject.c python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/listobject.c python/branches/p3yk/Objects/longobject.c python/branches/p3yk/Objects/stringobject.c python/branches/p3yk/Objects/unicodeobject.c python/branches/p3yk/PC/_msi.c python/branches/p3yk/Python/bltinmodule.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/getargs.c python/branches/p3yk/Python/marshal.c python/branches/p3yk/Python/pythonrun.c python/branches/p3yk/Python/traceback.c Log: Merged the int/long unification branch, by very crude means (sorry Thomas!). I banged on the code (beyond what's in that branch) to make fewer tests fail; the only tests that fail now are: test_descr -- can't pickle ints?! test_pickletools -- ??? test_socket -- See python.org/sf/1619659 test_sqlite -- ??? I'll deal with those later. Added: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- (empty file) +++ python/branches/p3yk/BROKEN_TESTS Sun Jan 14 04:31:43 2007 @@ -0,0 +1,4 @@ +test_descr -- can't pickle int objects?!?! +test_pickletools -- ??? +test_socket -- OverflowError: can't convert negative value to unsigned int +test_sqlite -- ??? Added: python/branches/p3yk/INTBENCH ============================================================================== --- (empty file) +++ python/branches/p3yk/INTBENCH Sun Jan 14 04:31:43 2007 @@ -0,0 +1,50 @@ +Measurements of _testcapi.profile_int, on an 800MHz G3, OSX 10.4.7 +best of three runs + +r51476 (original p3yk) +Test 1: 1.601978s +Test 2: 1.696623s +Test 3: 1.900683s +Test 4: 5.307155s +Test 5: 2.546707s +Test 6: 1.670252s +Test 7: 1.910734s + +r51506 (int type dropped) +Test 1: 4.134757s +Test 2: 4.398235s +Test 3: 4.611636s +Test 4: 10.665429s + +r51509 (small int cache) +Test 1: 3.457184s +Test 2: 4.514800s +Test 3: 4.999010s +Test 4: 10.818277s + +r51452 (special-casing medium int allocation) +Test 1: 3.258219s +Test 2: 4.255007s +Test 3: 4.547923s +Test 4: 10.615123s +Test 5: 5.255545s +Test 6: 3.775941s +Test 7: 4.001805s + +r51562 (special-case one-digit operations) +Test 1: 3.527860s +Test 2: 3.975953s +Test 3: 4.226751s +Test 4: 10.605721s +Test 5: 5.233576s +Test 6: 2.161525s +Test 7: 3.421624s + +r51573 (speed up PyLong_FromLong) +Test 1: 3.149116s +Test 2: 3.948204s +Test 3: 4.012080s +Test 4: 8.589921s +Test 5: 4.481723s +Test 6: 2.259849s +Test 7: 3.453212s Modified: python/branches/p3yk/Include/abstract.h ============================================================================== --- python/branches/p3yk/Include/abstract.h (original) +++ python/branches/p3yk/Include/abstract.h Sun Jan 14 04:31:43 2007 @@ -716,7 +716,7 @@ is cleared and the value is clipped. */ - PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o); + #define PyNumber_Int PyNumber_Long /* Returns the o converted to an integer object on success, or Modified: python/branches/p3yk/Include/boolobject.h ============================================================================== --- python/branches/p3yk/Include/boolobject.h (original) +++ python/branches/p3yk/Include/boolobject.h Sun Jan 14 04:31:43 2007 @@ -7,8 +7,6 @@ #endif -typedef PyIntObject PyBoolObject; - PyAPI_DATA(PyTypeObject) PyBool_Type; #define PyBool_Check(x) ((x)->ob_type == &PyBool_Type) @@ -17,10 +15,10 @@ Don't forget to apply Py_INCREF() when returning either!!! */ /* Don't use these directly */ -PyAPI_DATA(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct; +PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct; /* Use these macros */ -#define Py_False ((PyObject *) &_Py_ZeroStruct) +#define Py_False ((PyObject *) &_Py_FalseStruct) #define Py_True ((PyObject *) &_Py_TrueStruct) /* Macros for returning Py_True or Py_False, respectively */ Modified: python/branches/p3yk/Include/intobject.h ============================================================================== --- python/branches/p3yk/Include/intobject.h (original) +++ python/branches/p3yk/Include/intobject.h Sun Jan 14 04:31:43 2007 @@ -20,34 +20,31 @@ extern "C" { #endif +/* typedef struct { PyObject_HEAD long ob_ival; } PyIntObject; PyAPI_DATA(PyTypeObject) PyInt_Type; +*/ -#define PyInt_Check(op) PyObject_TypeCheck(op, &PyInt_Type) -#define PyInt_CheckExact(op) ((op)->ob_type == &PyInt_Type) +#define PyInt_Check(op) PyLong_Check(op) +#define PyInt_CheckExact(op) (PyLong_CheckExact(op) && _PyLong_FitsInLong(op)) -PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int); -#ifdef Py_USING_UNICODE -PyAPI_FUNC(PyObject *) PyInt_FromUnicode(Py_UNICODE*, Py_ssize_t, int); -#endif -PyAPI_FUNC(PyObject *) PyInt_FromLong(long); -PyAPI_FUNC(PyObject *) PyInt_FromSize_t(size_t); -PyAPI_FUNC(PyObject *) PyInt_FromSsize_t(Py_ssize_t); -PyAPI_FUNC(long) PyInt_AsLong(PyObject *); -PyAPI_FUNC(Py_ssize_t) PyInt_AsSsize_t(PyObject *); -PyAPI_FUNC(unsigned long) PyInt_AsUnsignedLongMask(PyObject *); -#ifdef HAVE_LONG_LONG -PyAPI_FUNC(unsigned PY_LONG_LONG) PyInt_AsUnsignedLongLongMask(PyObject *); -#endif +#define PyInt_FromString PyLong_FromString +#define PyInt_FromUnicode PyLong_FromUnicode +#define PyInt_FromLong PyLong_FromLong +#define PyInt_FromSize_t PyLong_FromSize_t +#define PyInt_FromSsize_t PyLong_FromSsize_t +#define PyInt_AsLong PyLong_AsLong +#define PyInt_AsSsize_t PyLong_AsSsize_t +#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask +#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask PyAPI_FUNC(long) PyInt_GetMax(void); -/* Macro, trading safety for speed */ -#define PyInt_AS_LONG(op) (((PyIntObject *)(op))->ob_ival) +#define PyInt_AS_LONG(op) PyLong_AsLong(op) /* These aren't really part of the Int object, but they're handy; the protos * are necessary for systems that need the magic of PyAPI_FUNC and that want Modified: python/branches/p3yk/Include/longobject.h ============================================================================== --- python/branches/p3yk/Include/longobject.h (original) +++ python/branches/p3yk/Include/longobject.h Sun Jan 14 04:31:43 2007 @@ -16,15 +16,16 @@ PyAPI_FUNC(PyObject *) PyLong_FromLong(long); PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long); +PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t); +PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t); PyAPI_FUNC(PyObject *) PyLong_FromDouble(double); PyAPI_FUNC(long) PyLong_AsLong(PyObject *); +PyAPI_FUNC(ssize_t) PyLong_AsSsize_t(PyObject *); +PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *); /* For use by intobject.c only */ -PyAPI_FUNC(Py_ssize_t) _PyLong_AsSsize_t(PyObject *); -PyAPI_FUNC(PyObject *) _PyLong_FromSize_t(size_t); -PyAPI_FUNC(PyObject *) _PyLong_FromSsize_t(Py_ssize_t); PyAPI_DATA(int) _PyLong_DigitValue[256]; /* _PyLong_AsScaledDouble returns a double x and an exponent e such that @@ -34,6 +35,7 @@ be multiplied by SHIFT! There may not be enough room in an int to store e*SHIFT directly. */ PyAPI_FUNC(double) _PyLong_AsScaledDouble(PyObject *vv, int *e); + PyAPI_FUNC(int) _PyLong_FitsInLong(PyObject* vv); PyAPI_FUNC(double) PyLong_AsDouble(PyObject *); PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *); Modified: python/branches/p3yk/Lib/pickle.py ============================================================================== --- python/branches/p3yk/Lib/pickle.py (original) +++ python/branches/p3yk/Lib/pickle.py Sun Jan 14 04:31:43 2007 @@ -456,9 +456,29 @@ return # Text pickle, or int too big to fit in signed 4-byte format. self.write(INT + repr(obj) + '\n') - dispatch[IntType] = save_int + # XXX save_int is merged into save_long + # dispatch[IntType] = save_int def save_long(self, obj, pack=struct.pack): + if self.bin: + # If the int is small enough to fit in a signed 4-byte 2's-comp + # format, we can store it more efficiently than the general + # case. + # First one- and two-byte unsigned ints: + if obj >= 0: + if obj <= 0xff: + self.write(BININT1 + chr(obj)) + return + if obj <= 0xffff: + self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8)) + return + # Next check for 4-byte signed ints: + high_bits = obj >> 31 # note that Python shift sign-extends + if high_bits == 0 or high_bits == -1: + # All high bits are copies of bit 2**31, so the value + # fits in a 4-byte signed int. + self.write(BININT + pack("= 2: bytes = encode_long(obj) n = len(bytes) Modified: python/branches/p3yk/Lib/test/output/test_class ============================================================================== --- python/branches/p3yk/Lib/test/output/test_class (original) +++ python/branches/p3yk/Lib/test/output/test_class Sun Jan 14 04:31:43 2007 @@ -44,7 +44,7 @@ __pos__: () __abs__: () __int__: () -__long__: () +__int__: () __float__: () __oct__: () __hex__: () Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Sun Jan 14 04:31:43 2007 @@ -1081,10 +1081,12 @@ self.assertEqual(long(Foo0()), 42L) self.assertEqual(long(Foo1()), 42L) - self.assertEqual(long(Foo2()), 42L) + # XXX invokes __int__ now + # self.assertEqual(long(Foo2()), 42L) self.assertEqual(long(Foo3()), 0) - self.assertEqual(long(Foo4()), 42) - self.assertRaises(TypeError, long, Foo5()) + # XXX likewise + # self.assertEqual(long(Foo4()), 42) + # self.assertRaises(TypeError, long, Foo5()) def test_map(self): self.assertEqual( Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Sun Jan 14 04:31:43 2007 @@ -430,13 +430,6 @@ pass 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(): if verbose: print "Testing long operations..." Modified: python/branches/p3yk/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_marshal.py (original) +++ python/branches/p3yk/Lib/test/test_marshal.py Sun Jan 14 04:31:43 2007 @@ -204,7 +204,7 @@ def test_patch_873224(self): self.assertRaises(Exception, marshal.loads, '0') self.assertRaises(Exception, marshal.loads, 'f') - self.assertRaises(Exception, marshal.loads, marshal.dumps(5L)[:-1]) + self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65L)[:-1]) def test_version_argument(self): # Python 2.4.0 crashes for any call to marshal.dumps(x, y) Modified: python/branches/p3yk/Lib/test/test_optparse.py ============================================================================== --- python/branches/p3yk/Lib/test/test_optparse.py (original) +++ python/branches/p3yk/Lib/test/test_optparse.py Sun Jan 14 04:31:43 2007 @@ -1600,7 +1600,7 @@ self.assertRaises( _parse_num, ("0xOoops", long), {}, ValueError, - re.compile(r"invalid literal for long().*: '?0xOoops'?")) + re.compile(r"invalid literal for int().*: '?0xOoops'?")) def test_parse_num_ok(self): self.assertEqual(_parse_num("0", int), 0) @@ -1618,9 +1618,9 @@ self.assertParseFail(["-n008"], "option -n: invalid integer value: '008'") self.assertParseFail(["-l0b0123"], - "option -l: invalid long integer value: '0b0123'") + "option -l: invalid integer value: '0b0123'") self.assertParseFail(["-l", "0x12x"], - "option -l: invalid long integer value: '0x12x'") + "option -l: invalid integer value: '0x12x'") def _testclasses(): Modified: python/branches/p3yk/Modules/_csv.c ============================================================================== --- python/branches/p3yk/Modules/_csv.c (original) +++ python/branches/p3yk/Modules/_csv.c Sun Jan 14 04:31:43 2007 @@ -219,7 +219,7 @@ if (src == NULL) *target = dflt; else { - if (!PyInt_Check(src)) { + if (!PyInt_CheckExact(src)) { PyErr_Format(PyExc_TypeError, "\"%s\" must be an integer", name); return -1; @@ -1410,7 +1410,7 @@ if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) return NULL; if (new_limit != NULL) { - if (!PyInt_Check(new_limit)) { + if (!PyInt_CheckExact(new_limit)) { PyErr_Format(PyExc_TypeError, "limit must be an integer"); return NULL; Modified: python/branches/p3yk/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/_ctypes.c (original) +++ python/branches/p3yk/Modules/_ctypes/_ctypes.c Sun Jan 14 04:31:43 2007 @@ -991,7 +991,7 @@ return NULL; proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ - if (!proto || !PyInt_Check(proto)) { + if (!proto || !PyInt_CheckExact(proto)) { PyErr_SetString(PyExc_AttributeError, "class must define a '_length_' attribute, " "which must be a positive integer"); Modified: python/branches/p3yk/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/callproc.c (original) +++ python/branches/p3yk/Modules/_ctypes/callproc.c Sun Jan 14 04:31:43 2007 @@ -496,12 +496,6 @@ return 0; } - if (PyInt_Check(obj)) { - pa->ffi_type = &ffi_type_sint; - pa->value.i = PyInt_AS_LONG(obj); - return 0; - } - if (PyLong_Check(obj)) { pa->ffi_type = &ffi_type_sint; pa->value.i = (long)PyLong_AsUnsignedLong(obj); Modified: python/branches/p3yk/Modules/_cursesmodule.c ============================================================================== --- python/branches/p3yk/Modules/_cursesmodule.c (original) +++ python/branches/p3yk/Modules/_cursesmodule.c Sun Jan 14 04:31:43 2007 @@ -193,7 +193,7 @@ static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyInt_Check(obj)) { + if (PyInt_CheckExact(obj)) { *ch = (chtype) PyInt_AsLong(obj); } else if(PyString_Check(obj) && (PyString_Size(obj) == 1)) { @@ -2364,7 +2364,7 @@ if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) + if (PyInt_CheckExact(temp)) ch = (chtype) PyInt_AsLong(temp); else if (PyString_Check(temp)) ch = (chtype) *PyString_AsString(temp); @@ -2386,7 +2386,7 @@ if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) + if (PyInt_CheckExact(temp)) ch = (int) PyInt_AsLong(temp); else if (PyString_Check(temp)) ch = (int) *PyString_AsString(temp); Modified: python/branches/p3yk/Modules/_sre.c ============================================================================== --- python/branches/p3yk/Modules/_sre.c (original) +++ python/branches/p3yk/Modules/_sre.c Sun Jan 14 04:31:43 2007 @@ -2688,8 +2688,7 @@ for (i = 0; i < n; i++) { PyObject *o = PyList_GET_ITEM(code, i); - unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o) - : PyLong_AsUnsignedLong(o); + unsigned long value = PyLong_AsUnsignedLong(o); self->code[i] = (SRE_CODE) value; if ((unsigned long) self->code[i] != value) { PyErr_SetString(PyExc_OverflowError, @@ -2763,6 +2762,10 @@ { Py_ssize_t i; + if (index == NULL) + /* Default value */ + return 0; + if (PyInt_Check(index)) return PyInt_AsSsize_t(index); @@ -2913,7 +2916,7 @@ { Py_ssize_t index; - PyObject* index_ = Py_False; /* zero */ + PyObject* index_ = NULL; if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_)) return NULL; @@ -2936,7 +2939,7 @@ { Py_ssize_t index; - PyObject* index_ = Py_False; /* zero */ + PyObject* index_ = NULL; if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_)) return NULL; @@ -2986,7 +2989,7 @@ { Py_ssize_t index; - PyObject* index_ = Py_False; /* zero */ + PyObject* index_ = NULL; if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_)) return NULL; Modified: python/branches/p3yk/Modules/_struct.c ============================================================================== --- python/branches/p3yk/Modules/_struct.c (original) +++ python/branches/p3yk/Modules/_struct.c Sun Jan 14 04:31:43 2007 @@ -118,8 +118,6 @@ PyNumberMethods *m; assert(v != NULL); - if (PyInt_Check(v)) - return PyLong_FromLong(PyInt_AS_LONG(v)); if (PyLong_Check(v)) { Py_INCREF(v); return v; Modified: python/branches/p3yk/Modules/_testcapimodule.c ============================================================================== --- python/branches/p3yk/Modules/_testcapimodule.c (original) +++ python/branches/p3yk/Modules/_testcapimodule.c Sun Jan 14 04:31:43 2007 @@ -718,6 +718,119 @@ Py_RETURN_NONE; } +#ifdef HAVE_GETTIMEOFDAY +/* Profiling of integer performance */ +void print_delta(int test, struct timeval *s, struct timeval *e) +{ + e->tv_sec -= s->tv_sec; + e->tv_usec -= s->tv_usec; + if (e->tv_usec < 0) { + e->tv_sec -=1; + e->tv_usec += 1000000; + } + printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, e->tv_usec); +} + +static PyObject * +profile_int(PyObject *self, PyObject* args) +{ + int i, k; + struct timeval start, stop; + PyObject *single, **multiple, *op1, *result; + + /* Test 1: Allocate and immediately deallocate + many small integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyInt_FromLong(i); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(1, &start, &stop); + + /* Test 2: Allocate and immediately deallocate + many large integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyInt_FromLong(i+1000000); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(2, &start, &stop); + + /* Test 3: Allocate a few integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000); + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) { + for(i=0; i < 1000; i++) { + multiple[i] = PyInt_FromLong(i+1000000); + } + for(i=0; i < 1000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(3, &start, &stop); + + /* Test 4: Allocate many integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 20; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyInt_FromLong(i+1000000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(4, &start, &stop); + + /* Test 5: Allocate many integers < 32000 */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 10; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyInt_FromLong(i+1000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(5, &start, &stop); + + /* Test 6: Perform small int addition */ + op1 = PyInt_FromLong(1); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(6, &start, &stop); + + /* Test 7: Perform medium int addition */ + op1 = PyInt_FromLong(1000); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(7, &start, &stop); + + Py_INCREF(Py_None); + return Py_None; +} +#endif + static PyMethodDef TestMethods[] = { {"raise_exception", raise_exception, METH_VARARGS}, {"test_config", (PyCFunction)test_config, METH_NOARGS}, @@ -756,6 +869,9 @@ #ifdef WITH_THREAD {"_test_thread_state", test_thread_state, METH_VARARGS}, #endif +#ifdef HAVE_GETTIMEOFDAY + {"profile_int", profile_int, METH_NOARGS}, +#endif {NULL, NULL} /* sentinel */ }; Modified: python/branches/p3yk/Modules/_tkinter.c ============================================================================== --- python/branches/p3yk/Modules/_tkinter.c (original) +++ python/branches/p3yk/Modules/_tkinter.c Sun Jan 14 04:31:43 2007 @@ -913,7 +913,7 @@ PyString_GET_SIZE(value)); else if (PyBool_Check(value)) return Tcl_NewBooleanObj(PyObject_IsTrue(value)); - else if (PyInt_Check(value)) + else if (PyInt_CheckExact(value)) return Tcl_NewLongObj(PyInt_AS_LONG(value)); else if (PyFloat_Check(value)) return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value)); Modified: python/branches/p3yk/Modules/cPickle.c ============================================================================== --- python/branches/p3yk/Modules/cPickle.c (original) +++ python/branches/p3yk/Modules/cPickle.c Sun Jan 14 04:31:43 2007 @@ -711,7 +711,9 @@ PyErr_SetString(PicklingError, "no int where int expected in memo"); return -1; } - c_value = PyInt_AS_LONG((PyIntObject*)value); + c_value = PyInt_AsLong(value); + if (c_value == -1 && PyErr_Occurred()) + return -1; if (!self->bin) { s[0] = GET; @@ -958,7 +960,7 @@ { static const char *buf[2] = {FALSE, TRUE}; static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1}; - long l = PyInt_AS_LONG((PyIntObject *)args); + long l = args == Py_True; if (self->proto >= 2) { char opcode = l ? NEWTRUE : NEWFALSE; @@ -971,10 +973,9 @@ } static int -save_int(Picklerobject *self, PyObject *args) +save_int(Picklerobject *self, long l) { char c_str[32]; - long l = PyInt_AS_LONG((PyIntObject *)args); int len = 0; if (!self->bin @@ -1027,9 +1028,16 @@ Py_ssize_t size; int res = -1; PyObject *repr = NULL; - + int val = PyInt_AsLong(args); static char l = LONG; + if (val == -1 && PyErr_Occurred()) { + /* out of range for int pickling */ + PyErr_Clear(); + } + else + return save_int(self, val); + if (self->proto >= 2) { /* Linear-time pickling. */ size_t nbits; @@ -2183,13 +2191,6 @@ goto finally; } break; - case 'i': - if (type == &PyInt_Type) { - res = save_int(self, args); - goto finally; - } - break; - case 'l': if (type == &PyLong_Type) { res = save_long(self, args); @@ -2486,7 +2487,9 @@ rsize += PyString_GET_SIZE(k); else if (PyInt_Check(k)) { /* put */ - ik = PyInt_AS_LONG((PyIntObject*)k); + ik = PyInt_AsLong(k); + if (ik == -1 && PyErr_Occurred()) + goto err; if (ik >= lm || ik == 0) { PyErr_SetString(PicklingError, "Invalid get data"); @@ -2506,7 +2509,9 @@ } else { /* put */ - ik = PyInt_AS_LONG((PyIntObject *)k); + ik = PyInt_AsLong(k); + if (ik == -1 && PyErr_Occurred()) + goto err; if (ik >= lm || ik == 0) { PyErr_SetString(PicklingError, "Invalid get data"); @@ -2535,8 +2540,9 @@ } else if (PyTuple_Check(k)) { /* get */ - ik = PyInt_AS_LONG((PyIntObject *) - PyTuple_GET_ITEM(k, 0)); + ik = PyLong_AsLong(PyTuple_GET_ITEM(k, 0)); + if (ik == -1 && PyErr_Occurred()) + goto err; if (ik < 256) { *s++ = BINGET; *s++ = (int)(ik & 0xff); @@ -2551,7 +2557,9 @@ } else { /* put */ - ik = PyInt_AS_LONG((PyIntObject*)k); + ik = PyLong_AsLong(k); + if (ik == -1 && PyErr_Occurred()) + goto err; if (have_get[ik]) { /* with matching get */ if (ik < 256) { Modified: python/branches/p3yk/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/p3yk/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/p3yk/Modules/cjkcodecs/multibytecodec.c Sun Jan 14 04:31:43 2007 @@ -1314,6 +1314,9 @@ return NULL; } + if (size == -1 && PyErr_Occurred()) + return NULL; + return mbstreamreader_iread(self, "read", size); } @@ -1335,6 +1338,9 @@ return NULL; } + if (size == -1 && PyErr_Occurred()) + return NULL; + return mbstreamreader_iread(self, "readline", size); } @@ -1356,6 +1362,9 @@ return NULL; } + if (sizehint == -1 && PyErr_Occurred()) + return NULL; + r = mbstreamreader_iread(self, "read", sizehint); if (r == NULL) return NULL; Modified: python/branches/p3yk/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk/Modules/datetimemodule.c (original) +++ python/branches/p3yk/Modules/datetimemodule.c Sun Jan 14 04:31:43 2007 @@ -1844,10 +1844,7 @@ * lose a little info. */ assert(PyInt_Check(factor) || PyLong_Check(factor)); - if (PyInt_Check(factor)) - dnum = (double)PyInt_AsLong(factor); - else - dnum = PyLong_AsDouble(factor); + dnum = PyLong_AsDouble(factor); dnum *= fracpart; fracpart = modf(dnum, &intpart); @@ -3800,7 +3797,7 @@ Py_DECREF(obj); return NULL; } - if (PyInt_Check(p)) + if (PyInt_CheckExact(p)) ia[i] = PyInt_AsLong(p); else good_timetuple = 0; Modified: python/branches/p3yk/Modules/dlmodule.c ============================================================================== --- python/branches/p3yk/Modules/dlmodule.c (original) +++ python/branches/p3yk/Modules/dlmodule.c Sun Jan 14 04:31:43 2007 @@ -107,9 +107,11 @@ } for (i = 1; i < n; i++) { PyObject *v = PyTuple_GetItem(args, i); - if (PyInt_Check(v)) + if (PyInt_Check(v)) { alist[i-1] = PyInt_AsLong(v); - else if (PyString_Check(v)) + if (alist[i-1] == -1 && PyErr_Occurred()) + return NULL; + } else if (PyString_Check(v)) alist[i-1] = (long)PyString_AsString(v); else if (v == Py_None) alist[i-1] = (long) ((char *)NULL); Modified: python/branches/p3yk/Modules/posixmodule.c ============================================================================== --- python/branches/p3yk/Modules/posixmodule.c (original) +++ python/branches/p3yk/Modules/posixmodule.c Sun Jan 14 04:31:43 2007 @@ -5437,32 +5437,21 @@ elem = PySequence_GetItem(groups, i); if (!elem) return NULL; - if (!PyInt_Check(elem)) { - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); Py_DECREF(elem); return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back the value to see if it fitted in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } } - } else { - long x = PyInt_AsLong(elem); grouplist[i] = x; + /* read back the value to see if it fitted in gid_t */ if (grouplist[i] != x) { PyErr_SetString(PyExc_TypeError, "group id too big"); Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Sun Jan 14 04:31:43 2007 @@ -3483,12 +3483,7 @@ { unsigned long x; - if (PyInt_Check(arg)) { - x = PyInt_AS_LONG(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; - } - else if (PyLong_Check(arg)) { + if (PyLong_Check(arg)) { x = PyLong_AsUnsignedLong(arg); if (x == (unsigned long) -1 && PyErr_Occurred()) return NULL; @@ -3542,12 +3537,7 @@ { unsigned long x; - if (PyInt_Check(arg)) { - x = PyInt_AS_LONG(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; - } - else if (PyLong_Check(arg)) { + if (PyLong_Check(arg)) { x = PyLong_AsUnsignedLong(arg); if (x == (unsigned long) -1 && PyErr_Occurred()) return NULL; @@ -3827,7 +3817,7 @@ "getaddrinfo() argument 1 must be string or None"); return NULL; } - if (PyInt_Check(pobj)) { + if (PyInt_CheckExact(pobj)) { PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj)); pptr = pbuf; } else if (PyString_Check(pobj)) { Modified: python/branches/p3yk/Modules/timemodule.c ============================================================================== --- python/branches/p3yk/Modules/timemodule.c (original) +++ python/branches/p3yk/Modules/timemodule.c Sun Jan 14 04:31:43 2007 @@ -357,7 +357,7 @@ if (y < 1900) { PyObject *accept = PyDict_GetItemString(moddict, "accept2dyear"); - if (accept == NULL || !PyInt_Check(accept) || + if (accept == NULL || !PyInt_CheckExact(accept) || PyInt_AsLong(accept) == 0) { PyErr_SetString(PyExc_ValueError, "year >= 1900 required"); Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Sun Jan 14 04:31:43 2007 @@ -790,25 +790,6 @@ return type_error("bad operand type for abs(): '%.200s'", o); } -/* Add a check for embedded NULL-bytes in the argument. */ -static PyObject * -int_from_string(const char *s, Py_ssize_t len) -{ - char *end; - PyObject *x; - - x = PyInt_FromString((char*)s, &end, 10); - if (x == NULL) - return NULL; - if (end != s + len) { - PyErr_SetString(PyExc_ValueError, - "null byte in argument for int()"); - Py_DECREF(x); - return NULL; - } - return x; -} - /* Return a Python Int or Long from the object item Raise TypeError if the result is not an int-or-long or if the object cannot be interpreted as an index. @@ -828,7 +809,7 @@ if (result && !PyInt_Check(result) && !PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, - "__index__ returned non-(int,long) " \ + "__index__ returned non-int " \ "(type %.200s)", result->ob_type->tp_name); Py_DECREF(result); @@ -890,51 +871,6 @@ } -PyObject * -PyNumber_Int(PyObject *o) -{ - PyNumberMethods *m; - const char *buffer; - Py_ssize_t buffer_len; - - if (o == NULL) - return null_error(); - if (PyInt_CheckExact(o)) { - Py_INCREF(o); - return o; - } - m = o->ob_type->tp_as_number; - if (m && m->nb_int) { /* This should include subclasses of int */ - PyObject *res = m->nb_int(o); - if (res && (!PyInt_Check(res) && !PyLong_Check(res))) { - PyErr_Format(PyExc_TypeError, - "__int__ returned non-int (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyInt_Check(o)) { /* A int subclass without nb_int */ - PyIntObject *io = (PyIntObject*)o; - return PyInt_FromLong(io->ob_ival); - } - if (PyString_Check(o)) - return int_from_string(PyString_AS_STRING(o), - PyString_GET_SIZE(o)); -#ifdef Py_USING_UNICODE - if (PyUnicode_Check(o)) - return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o), - PyUnicode_GET_SIZE(o), - 10); -#endif - if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) - return int_from_string((char*)buffer, buffer_len); - - return type_error("int() argument must be a string or a " - "number, not '%.200s'", o); -} - /* Add a check for embedded NULL-bytes in the argument. */ static PyObject * long_from_string(const char *s, Py_ssize_t len) @@ -947,7 +883,7 @@ return NULL; if (end != s + len) { PyErr_SetString(PyExc_ValueError, - "null byte in argument for long()"); + "null byte in argument for int()"); Py_DECREF(x); return NULL; } @@ -963,7 +899,22 @@ if (o == NULL) return null_error(); + if (PyLong_CheckExact(o)) { + Py_INCREF(o); + return o; + } m = o->ob_type->tp_as_number; + if (m && m->nb_int) { /* This should include subclasses of int */ + PyObject *res = m->nb_int(o); + if (res && !PyLong_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } if (m && m->nb_long) { /* This should include subclasses of long */ PyObject *res = m->nb_long(o); if (res && (!PyInt_Check(res) && !PyLong_Check(res))) { @@ -994,7 +945,7 @@ if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) return long_from_string(buffer, buffer_len); - return type_error("long() argument must be a string or a " + return type_error("int() argument must be a string or a " "number, not '%.200s'", o); } Modified: python/branches/p3yk/Objects/boolobject.c ============================================================================== --- python/branches/p3yk/Objects/boolobject.c (original) +++ python/branches/p3yk/Objects/boolobject.c Sun Jan 14 04:31:43 2007 @@ -1,13 +1,14 @@ /* Boolean type, a subtype of int */ #include "Python.h" +#include "longintrepr.h" /* We need to define bool_print to override int_print */ static int -bool_print(PyBoolObject *self, FILE *fp, int flags) +bool_print(PyObject *self, FILE *fp, int flags) { - fputs(self->ob_ival == 0 ? "False" : "True", fp); + fputs(self == Py_False ? "False" : "True", fp); return 0; } @@ -17,11 +18,11 @@ static PyObject *true_str = NULL; static PyObject * -bool_repr(PyBoolObject *self) +bool_repr(PyObject *self) { PyObject *s; - if (self->ob_ival) + if (self == Py_True) s = true_str ? true_str : (true_str = PyString_InternFromString("True")); else @@ -68,27 +69,24 @@ bool_and(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyInt_Type.tp_as_number->nb_and(a, b); - return PyBool_FromLong( - ((PyBoolObject *)a)->ob_ival & ((PyBoolObject *)b)->ob_ival); + return PyLong_Type.tp_as_number->nb_and(a, b); + return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyInt_Type.tp_as_number->nb_or(a, b); - return PyBool_FromLong( - ((PyBoolObject *)a)->ob_ival | ((PyBoolObject *)b)->ob_ival); + return PyLong_Type.tp_as_number->nb_or(a, b); + return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyInt_Type.tp_as_number->nb_xor(a, b); - return PyBool_FromLong( - ((PyBoolObject *)a)->ob_ival ^ ((PyBoolObject *)b)->ob_ival); + return PyLong_Type.tp_as_number->nb_xor(a, b); + return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ @@ -139,6 +137,7 @@ 0, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ + 0, /* nb_index */ }; /* The type object for bool. Note that this cannot be subclassed! */ @@ -147,20 +146,20 @@ PyObject_HEAD_INIT(&PyType_Type) 0, "bool", - sizeof(PyIntObject), + sizeof(struct _longobject), 0, 0, /* tp_dealloc */ - (printfunc)bool_print, /* tp_print */ + bool_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ - (reprfunc)bool_repr, /* tp_repr */ + bool_repr, /* tp_repr */ &bool_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ - (reprfunc)bool_repr, /* tp_str */ + bool_repr, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ @@ -175,7 +174,7 @@ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - &PyInt_Type, /* tp_base */ + &PyLong_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ @@ -188,12 +187,12 @@ /* The objects representing bool values False and True */ /* Named Zero for link-level compatibility */ -PyIntObject _Py_ZeroStruct = { +struct _longobject _Py_FalseStruct = { PyObject_HEAD_INIT(&PyBool_Type) - 0 + 0, { 0 } }; -PyIntObject _Py_TrueStruct = { +struct _longobject _Py_TrueStruct = { PyObject_HEAD_INIT(&PyBool_Type) - 1 + 1, { 1 } }; Modified: python/branches/p3yk/Objects/complexobject.c ============================================================================== --- python/branches/p3yk/Objects/complexobject.c (original) +++ python/branches/p3yk/Objects/complexobject.c Sun Jan 14 04:31:43 2007 @@ -349,10 +349,6 @@ PyObject *obj = *pobj; pc->real = pc->imag = 0.0; - if (PyInt_Check(obj)) { - pc->real = PyInt_AS_LONG(obj); - return 0; - } if (PyLong_Check(obj)) { pc->real = PyLong_AsDouble(obj); if (pc->real == -1.0 && PyErr_Occurred()) { Modified: python/branches/p3yk/Objects/exceptions.c ============================================================================== --- python/branches/p3yk/Objects/exceptions.c (original) +++ python/branches/p3yk/Objects/exceptions.c Sun Jan 14 04:31:43 2007 @@ -1089,7 +1089,7 @@ have_filename = (self->filename != NULL) && PyString_Check(self->filename); - have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno); + have_lineno = (self->lineno != NULL) && PyInt_CheckExact(self->lineno); if (!have_filename && !have_lineno) return str; @@ -1225,10 +1225,8 @@ return -1; } - if (PyInt_Check(attr)) { - *value = PyInt_AS_LONG(attr); - } else if (PyLong_Check(attr)) { - *value = _PyLong_AsSsize_t(attr); + if (PyLong_Check(attr)) { + *value = PyLong_AsSsize_t(attr); if (*value == -1 && PyErr_Occurred()) return -1; } else { @@ -1515,8 +1513,8 @@ if (!PyArg_ParseTuple(args, "O!O!O!O!O!", &PyString_Type, &self->encoding, objecttype, &self->object, - &PyInt_Type, &self->start, - &PyInt_Type, &self->end, + &PyLong_Type, &self->start, + &PyLong_Type, &self->end, &PyString_Type, &self->reason)) { self->encoding = self->object = self->start = self->end = self->reason = NULL; @@ -1748,8 +1746,8 @@ if (!PyArg_ParseTuple(args, "O!O!O!O!", &PyUnicode_Type, &self->object, - &PyInt_Type, &self->start, - &PyInt_Type, &self->end, + &PyLong_Type, &self->start, + &PyLong_Type, &self->end, &PyString_Type, &self->reason)) { self->object = self->start = self->end = self->reason = NULL; return -1; Modified: python/branches/p3yk/Objects/fileobject.c ============================================================================== --- python/branches/p3yk/Objects/fileobject.c (original) +++ python/branches/p3yk/Objects/fileobject.c Sun Jan 14 04:31:43 2007 @@ -2136,7 +2136,7 @@ if (v == NULL) PyErr_Clear(); else { - if (PyInt_Check(v)) + if (PyInt_CheckExact(v)) oldflag = PyInt_AsLong(v); assert(oldflag < INT_MAX); Py_DECREF(v); @@ -2301,6 +2301,8 @@ return -1; } + if (fd == -1 && PyErr_Occurred()) + return -1; if (fd < 0) { PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", Modified: python/branches/p3yk/Objects/floatobject.c ============================================================================== --- python/branches/p3yk/Objects/floatobject.c (original) +++ python/branches/p3yk/Objects/floatobject.c Sun Jan 14 04:31:43 2007 @@ -273,10 +273,7 @@ { register PyObject *obj = *v; - if (PyInt_Check(obj)) { - *dbl = (double)PyInt_AS_LONG(obj); - } - else if (PyLong_Check(obj)) { + if (PyLong_Check(obj)) { *dbl = PyLong_AsDouble(obj); if (*dbl == -1.0 && PyErr_Occurred()) { *v = NULL; @@ -376,32 +373,6 @@ goto Unimplemented; } - else if (PyInt_Check(w)) { - long jj = PyInt_AS_LONG(w); - /* In the worst realistic case I can imagine, C double is a - * Cray single with 48 bits of precision, and long has 64 - * bits. - */ -#if SIZEOF_LONG > 6 - unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj); - if (abs >> 48) { - /* Needs more than 48 bits. Make it take the - * PyLong path. - */ - PyObject *result; - PyObject *ww = PyLong_FromLong(jj); - - if (ww == NULL) - return NULL; - result = float_richcompare(v, ww, op); - Py_DECREF(ww); - return result; - } -#endif - j = (double)jj; - assert((long)j == jj); - } - else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign = _PyLong_Sign(w); Modified: python/branches/p3yk/Objects/frameobject.c ============================================================================== --- python/branches/p3yk/Objects/frameobject.c (original) +++ python/branches/p3yk/Objects/frameobject.c Sun Jan 14 04:31:43 2007 @@ -88,7 +88,7 @@ int setup_op = 0; /* (ditto) */ /* f_lineno must be an integer. */ - if (!PyInt_Check(p_new_lineno)) { + if (!PyInt_CheckExact(p_new_lineno)) { PyErr_SetString(PyExc_ValueError, "lineno must be an integer"); return -1; Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Sun Jan 14 04:31:43 2007 @@ -10,6 +10,7 @@ return LONG_MAX; /* To initialize sys.maxint */ } +#if 0 /* Integers are quite normal objects, to make object handling uniform. (Using odd pointers to represent integers would save much space but require extra checks for this special case throughout the code.) @@ -1254,3 +1255,4 @@ } } } +#endif /* if 0 */ Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Sun Jan 14 04:31:43 2007 @@ -945,7 +945,7 @@ Py_DECREF(args); if (res == NULL) return -1; - if (!PyInt_Check(res)) { + if (!PyInt_CheckExact(res)) { PyErr_Format(PyExc_TypeError, "comparison function must return int, not %.200s", res->ob_type->tp_name); Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Sun Jan 14 04:31:43 2007 @@ -7,6 +7,53 @@ #include +#ifndef NSMALLPOSINTS +#define NSMALLPOSINTS 257 +#endif +#ifndef NSMALLNEGINTS +#define NSMALLNEGINTS 5 +#endif +#if NSMALLNEGINTS + NSMALLPOSINTS > 0 +/* Small integers are preallocated in this array so that they + can be shared. + The integers that are preallocated are those in the range + -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). +*/ +static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; +#ifdef COUNT_ALLOCS +int quick_int_allocs, quick_neg_int_allocs; +#endif + +static inline PyObject * +get_small_int(int ival) +{ + PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); + Py_INCREF(v); +#ifdef COUNT_ALLOCS + if (ival >= 0) + quick_int_allocs++; + else + quick_neg_int_allocs++; +#endif + return v; +} +#define CHECK_SMALL_INT(ival) \ + do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ + return get_small_int(ival); \ + } while(0) + +#else +#define CHECK_SMALL_INT(ival) +#endif + +#define MEDIUM_VALUE(x) ((x)->ob_size < 0 ? -(x)->ob_digit[0] : ((x)->ob_size == 0 ? 0 : (x)->ob_digit[0])) +/* If a freshly-allocated long is already shared, it must + be a small integer, so negating it must go to PyLong_FromLong */ +#define NEGATE(x) \ + do if ((x)->ob_refcnt == 1) (x)->ob_size = -(x)->ob_size; \ + else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x)); \ + Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ + while(0) /* For long multiplication, use the O(N**2) school algorithm unless * both operands contain more than KARATSUBA_CUTOFF digits (this * being an internal Python long digit, in base BASE). @@ -64,11 +111,21 @@ PyLongObject * _PyLong_New(Py_ssize_t size) { - if (size > PY_SSIZE_T_MAX) { + PyLongObject *result; + /* Can't use sizeof(PyLongObject) here, since the + compiler takes padding at the end into account. + As the consequence, this would waste 2 bytes on + a 32-bit system, and 6 bytes on a 64-bit system. + This computation would be incorrect on systems + which have padding before the digits; with 16-bit + digits this should not happen. */ + result = PyObject_MALLOC(sizeof(PyVarObject) + + size*sizeof(digit)); + if (!result) { PyErr_NoMemory(); return NULL; } - return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size); + return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); } PyObject * @@ -81,6 +138,12 @@ i = src->ob_size; if (i < 0) i = -(i); + if (i < 2) { + int ival = src->ob_digit[0]; + if (src->ob_size < 0) + ival = -ival; + CHECK_SMALL_INT(ival); + } result = _PyLong_New(i); if (result != NULL) { result->ob_size = src->ob_size; @@ -98,17 +161,37 @@ PyLongObject *v; unsigned long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; - int negative = 0; + int sign = 1; + + CHECK_SMALL_INT(ival); if (ival < 0) { ival = -ival; - negative = 1; + sign = -1; } - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ + /* Fast path for single-digits ints */ + if (!(ival>>SHIFT)) { + v = _PyLong_New(1); + if (v) { + v->ob_size = sign; + v->ob_digit[0] = ival; + } + return (PyObject*)v; + } + + /* 2 digits */ + if (!(ival >> 2*SHIFT)) { + v = _PyLong_New(2); + if (v) { + v->ob_size = 2*sign; + v->ob_digit[0] = (digit)ival & MASK; + v->ob_digit[1] = ival >> SHIFT; + } + return (PyObject*)v; + } + + /* Larger numbers: loop to determine number of digits */ t = (unsigned long)ival; while (t) { ++ndigits; @@ -117,7 +200,7 @@ v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; - v->ob_size = negative ? -ndigits : ndigits; + v->ob_size = ndigits*sign; t = (unsigned long)ival; while (t) { *p++ = (digit)(t & MASK); @@ -136,6 +219,8 @@ unsigned long t; int ndigits = 0; + if (ival < BASE) + return PyLong_FromLong(ival); /* Count the number of Python digits. */ t = (unsigned long)ival; while (t) { @@ -165,9 +250,10 @@ neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to long"); + "cannot convert float infinity to int"); return NULL; } + CHECK_SMALL_INT((int)dval); if (dval < 0.0) { neg = 1; dval = -dval; @@ -214,15 +300,39 @@ unsigned long x, prev; Py_ssize_t i; int sign; + int do_decref = 0; /* if nb_int was called */ - if (vv == NULL || !PyLong_Check(vv)) { - if (vv != NULL && PyInt_Check(vv)) - return PyInt_AsLong(vv); + if (vv == NULL) { PyErr_BadInternalCall(); return -1; } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + if ((nb = vv->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + v = (PyLongObject *)vv; i = v->ob_size; + switch (i) { + case -1: return -v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } sign = 1; x = 0; if (i < 0) { @@ -235,6 +345,9 @@ if ((x >> SHIFT) != prev) goto overflow; } + if (do_decref) { + Py_DECREF(vv); + } /* Haven't lost any bits, but casting to long requires extra care * (see comment above). */ @@ -247,16 +360,32 @@ /* else overflow */ overflow: + if (do_decref) { + Py_DECREF(vv); + } PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to int"); + "int too large to convert to int"); return -1; } +int +_PyLong_FitsInLong(PyObject *vv) +{ + int size; + if (!PyLong_CheckExact(vv)) { + PyErr_BadInternalCall(); + return 0; + } + /* conservative estimate */ + size = ((PyLongObject*)vv)->ob_size; + return -2 <= size && size <= 2; +} + /* Get a Py_ssize_t from a long int object. Returns -1 and sets an error condition if overflow occurs. */ Py_ssize_t -_PyLong_AsSsize_t(PyObject *vv) { +PyLong_AsSsize_t(PyObject *vv) { register PyLongObject *v; size_t x, prev; Py_ssize_t i; @@ -268,6 +397,11 @@ } v = (PyLongObject *)vv; i = v->ob_size; + switch (i) { + case -1: return -v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } sign = 1; x = 0; if (i < 0) { @@ -293,7 +427,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to int"); + "int too large to convert to "); return -1; } @@ -308,15 +442,6 @@ Py_ssize_t i; if (vv == NULL || !PyLong_Check(vv)) { - if (vv != NULL && PyInt_Check(vv)) { - long val = PyInt_AsLong(vv); - if (val < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); - return (unsigned long) -1; - } - return val; - } PyErr_BadInternalCall(); return (unsigned long) -1; } @@ -325,15 +450,57 @@ x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); + "can't convert negative value to unsigned int"); return (unsigned long) -1; } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } while (--i >= 0) { prev = x; x = (x << SHIFT) + v->ob_digit[i]; if ((x >> SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "long int too large to convert"); + "int too large to convert"); + return (unsigned long) -1; + } + } + return x; +} + +/* Get a C unsigned long int from a long int object. + Returns -1 and sets an error condition if overflow occurs. */ + +size_t +PyLong_AsSize_t(PyObject *vv) +{ + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + i = v->ob_size; + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << SHIFT) + v->ob_digit[i]; + if ((x >> SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "int too large to convert"); return (unsigned long) -1; } } @@ -343,8 +510,8 @@ /* Get a C unsigned long int from a long int object, ignoring the high bits. Returns -1 and sets an error condition if an error occurs. */ -unsigned long -PyLong_AsUnsignedLongMask(PyObject *vv) +static unsigned long +_PyLong_AsUnsignedLongMask(PyObject *vv) { register PyLongObject *v; unsigned long x; @@ -352,13 +519,15 @@ int sign; if (vv == NULL || !PyLong_Check(vv)) { - if (vv != NULL && PyInt_Check(vv)) - return PyInt_AsUnsignedLongMask(vv); PyErr_BadInternalCall(); return (unsigned long) -1; } v = (PyLongObject *)vv; i = v->ob_size; + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } sign = 1; x = 0; if (i < 0) { @@ -371,6 +540,41 @@ return x * sign; } +unsigned long +PyLong_AsUnsignedLongMask(register PyObject *op) +{ + PyNumberMethods *nb; + PyLongObject *lo; + unsigned long val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned long)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned long)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned long)-1; + } +} + int _PyLong_Sign(PyObject *vv) { @@ -409,7 +613,7 @@ return result; Overflow: - PyErr_SetString(PyExc_OverflowError, "long has too many bits " + PyErr_SetString(PyExc_OverflowError, "int has too many bits " "to express in a platform size_t"); return (size_t)-1; } @@ -542,7 +746,7 @@ ndigits = -(v->ob_size); if (!is_signed) { PyErr_SetString(PyExc_TypeError, - "can't convert negative long to unsigned"); + "can't convert negative int to unsigned"); return -1; } do_twos_comp = 1; @@ -653,7 +857,7 @@ return 0; Overflow: - PyErr_SetString(PyExc_OverflowError, "long too big to convert"); + PyErr_SetString(PyExc_OverflowError, "int too big to convert"); return -1; } @@ -739,7 +943,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to float"); + "int too large to convert to float"); return -1.0; } @@ -748,24 +952,17 @@ PyObject * PyLong_FromVoidPtr(void *p) { -#if SIZEOF_VOID_P <= SIZEOF_LONG - if ((long)p < 0) - return PyLong_FromUnsignedLong((unsigned long)p); - return PyInt_FromLong((long)p); -#else - #ifndef HAVE_LONG_LONG # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long" #endif #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - /* optimize null pointers */ - if (p == NULL) + /* special-case null pointer */ + if (!p) return PyInt_FromLong(0); - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p); + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); -#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ } /* Get a C pointer from a long object (or an int object in some cases) */ @@ -780,9 +977,7 @@ #if SIZEOF_VOID_P <= SIZEOF_LONG long x; - if (PyInt_Check(vv)) - x = PyInt_AS_LONG(vv); - else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) x = PyLong_AsLong(vv); else x = PyLong_AsUnsignedLong(vv); @@ -796,9 +991,7 @@ #endif PY_LONG_LONG x; - if (PyInt_Check(vv)) - x = PyInt_AS_LONG(vv); - else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) x = PyLong_AsLongLong(vv); else x = PyLong_AsUnsignedLongLong(vv); @@ -828,6 +1021,7 @@ int ndigits = 0; int negative = 0; + CHECK_SMALL_INT(ival); if (ival < 0) { ival = -ival; negative = 1; @@ -864,6 +1058,8 @@ unsigned PY_LONG_LONG t; int ndigits = 0; + if (ival < BASE) + return PyLong_FromLong(ival); /* Count the number of Python digits. */ t = (unsigned PY_LONG_LONG)ival; while (t) { @@ -885,22 +1081,26 @@ /* Create a new long int object from a C Py_ssize_t. */ PyObject * -_PyLong_FromSsize_t(Py_ssize_t ival) +PyLong_FromSsize_t(Py_ssize_t ival) { Py_ssize_t bytes = ival; int one = 1; + if (ival < BASE) + return PyLong_FromLong(ival); return _PyLong_FromByteArray( (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); + SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); } /* Create a new long int object from a C size_t. */ PyObject * -_PyLong_FromSize_t(size_t ival) +PyLong_FromSize_t(size_t ival) { size_t bytes = ival; int one = 1; + if (ival < BASE) + return PyLong_FromLong(ival); return _PyLong_FromByteArray( (unsigned char *)&bytes, SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); @@ -912,6 +1112,7 @@ PY_LONG_LONG PyLong_AsLongLong(PyObject *vv) { + PyLongObject *v; PY_LONG_LONG bytes; int one = 1; int res; @@ -923,8 +1124,6 @@ if (!PyLong_Check(vv)) { PyNumberMethods *nb; PyObject *io; - if (PyInt_Check(vv)) - return (PY_LONG_LONG)PyInt_AsLong(vv); if ((nb = vv->ob_type->tp_as_number) == NULL || nb->nb_int == NULL) { PyErr_SetString(PyExc_TypeError, "an integer is required"); @@ -933,11 +1132,6 @@ io = (*nb->nb_int) (vv); if (io == NULL) return -1; - if (PyInt_Check(io)) { - bytes = PyInt_AsLong(io); - Py_DECREF(io); - return bytes; - } if (PyLong_Check(io)) { bytes = PyLong_AsLongLong(io); Py_DECREF(io); @@ -948,6 +1142,12 @@ return -1; } + v = (PyLongObject*)vv; + switch(v->ob_size) { + case -1: return -v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } res = _PyLong_AsByteArray( (PyLongObject *)vv, (unsigned char *)&bytes, SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); @@ -965,6 +1165,7 @@ unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *vv) { + PyLongObject *v; unsigned PY_LONG_LONG bytes; int one = 1; int res; @@ -974,6 +1175,12 @@ return (unsigned PY_LONG_LONG)-1; } + v = (PyLongObject*)vv; + switch(v->ob_size) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + res = _PyLong_AsByteArray( (PyLongObject *)vv, (unsigned char *)&bytes, SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); @@ -988,8 +1195,8 @@ /* Get a C unsigned long int from a long int object, ignoring the high bits. Returns -1 and sets an error condition if an error occurs. */ -unsigned PY_LONG_LONG -PyLong_AsUnsignedLongLongMask(PyObject *vv) +static unsigned PY_LONG_LONG +_PyLong_AsUnsignedLongLongMask(PyObject *vv) { register PyLongObject *v; unsigned PY_LONG_LONG x; @@ -1001,6 +1208,10 @@ return (unsigned long) -1; } v = (PyLongObject *)vv; + switch(v->ob_size) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } i = v->ob_size; sign = 1; x = 0; @@ -1013,6 +1224,41 @@ } return x * sign; } + +unsigned PY_LONG_LONG +PyLong_AsUnsignedLongLongMask(register PyObject *op) +{ + PyNumberMethods *nb; + PyLongObject *lo; + unsigned PY_LONG_LONG val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned PY_LONG_LONG)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned PY_LONG_LONG)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned PY_LONG_LONG)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned PY_LONG_LONG)-1; + } +} #undef IS_LITTLE_ENDIAN #endif /* HAVE_LONG_LONG */ @@ -1024,9 +1270,6 @@ *a = (PyLongObject *) v; Py_INCREF(v); } - else if (PyInt_Check(v)) { - *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v)); - } else { return 0; } @@ -1034,9 +1277,6 @@ *b = (PyLongObject *) w; Py_INCREF(w); } - else if (PyInt_Check(w)) { - *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w)); - } else { Py_DECREF(*a); return 0; @@ -1206,7 +1446,7 @@ sz = i + j / bits; if (j / SHIFT < size_a || sz < i) { PyErr_SetString(PyExc_OverflowError, - "long is too large to format"); + "int is too large to format"); return NULL; } str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz); @@ -1386,7 +1626,7 @@ n = (p - start) * bits_per_char + SHIFT - 1; if (n / bits_per_char < p - start) { PyErr_SetString(PyExc_ValueError, - "long string too large to convert"); + "int string too large to convert"); return NULL; } n = n / SHIFT; @@ -1433,7 +1673,7 @@ if ((base != 0 && base < 2) || base > 36) { PyErr_SetString(PyExc_ValueError, - "long() arg 2 must be >= 2 and <= 36"); + "int() arg 2 must be >= 2 and <= 36"); return NULL; } while (*str != '\0' && isspace(Py_CHARMASK(*str))) @@ -1683,7 +1923,7 @@ if (strrepr == NULL) return NULL; PyErr_Format(PyExc_ValueError, - "invalid literal for long() with base %d: %s", + "invalid literal for int() with base %d: %s", base, PyString_AS_STRING(strrepr)); Py_DECREF(strrepr); return NULL; @@ -1727,14 +1967,14 @@ if (size_b == 0) { PyErr_SetString(PyExc_ZeroDivisionError, - "long division or modulo by zero"); + "integer division or modulo by zero"); return -1; } if (size_a < size_b || (size_a == size_b && a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { /* |a| < |b|. */ - *pdiv = _PyLong_New(0); + *pdiv = (PyLongObject*)PyLong_FromLong(0); Py_INCREF(a); *prem = (PyLongObject *) a; return 0; @@ -1756,9 +1996,9 @@ the remainder r has the sign of a, so a = b*z + r. */ if ((a->ob_size < 0) != (b->ob_size < 0)) - z->ob_size = -(z->ob_size); + NEGATE(z); if (a->ob_size < 0 && (*prem)->ob_size != 0) - (*prem)->ob_size = -((*prem)->ob_size); + NEGATE(*prem); *pdiv = z; return 0; } @@ -1922,6 +2162,11 @@ same value hash to the same value, otherwise comparisons of mapping keys will turn out weird */ i = v->ob_size; + switch(i) { + case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } sign = 1; x = 0; if (i < 0) { @@ -2027,7 +2272,7 @@ } assert(borrow == 0); if (sign < 0) - z->ob_size = -(z->ob_size); + NEGATE(z); return long_normalize(z); } @@ -2038,6 +2283,9 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) + return PyInt_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); if (a->ob_size < 0) { if (b->ob_size < 0) { z = x_add(a, b); @@ -2065,6 +2313,8 @@ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) + return PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); if (a->ob_size < 0) { if (b->ob_size < 0) z = x_sub(a, b); @@ -2494,10 +2744,13 @@ return Py_NotImplemented; } + if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) + return PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w)); + z = k_mul(a, b); /* Negate if exactly one of the inputs is negative. */ if (((a->ob_size ^ b->ob_size) < 0) && z) - z->ob_size = -(z->ob_size); + NEGATE(z); Py_DECREF(a); Py_DECREF(b); return (PyObject *)z; @@ -2603,7 +2856,7 @@ if (bd == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, - "long division or modulo by zero"); + "int division or modulo by zero"); return NULL; } @@ -2622,7 +2875,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "long/long too large for a float"); + "int/int too large for a float"); return NULL; } @@ -2691,11 +2944,6 @@ c = (PyLongObject *)x; Py_INCREF(x); } - else if (PyInt_Check(x)) { - c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x)); - if (c == NULL) - goto Error; - } else if (x == Py_None) c = NULL; else { @@ -2741,7 +2989,7 @@ Py_DECREF(c); c = temp; temp = NULL; - c->ob_size = - c->ob_size; + NEGATE(c); } /* if modulus == 1: @@ -2862,6 +3110,8 @@ /* Implement ~x as -(x+1) */ PyLongObject *x; PyLongObject *w; + if (ABS(v->ob_size) <=1) + return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); w = (PyLongObject *)PyLong_FromLong(1L); if (w == NULL) return NULL; @@ -2888,11 +3138,8 @@ long_neg(PyLongObject *v) { PyLongObject *z; - if (v->ob_size == 0 && PyLong_CheckExact(v)) { - /* -0 == 0 */ - Py_INCREF(v); - return (PyObject *) v; - } + if (ABS(v->ob_size) <= 1) + return PyLong_FromLong(-MEDIUM_VALUE(v)); z = (PyLongObject *)_PyLong_Copy(v); if (z != NULL) z->ob_size = -(v->ob_size); @@ -3016,7 +3263,7 @@ if (z == NULL) goto lshift_error; if (a->ob_size < 0) - z->ob_size = -(z->ob_size); + NEGATE(z); for (i = 0; i < wordshift; i++) z->ob_digit[i] = 0; accum = 0; @@ -3194,22 +3441,7 @@ static PyObject * long_int(PyObject *v) { - long x; - x = PyLong_AsLong(v); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - PyErr_Clear(); - if (PyLong_CheckExact(v)) { - Py_INCREF(v); - return v; - } - else - return _PyLong_Copy((PyLongObject *)v); - } - else - return NULL; - } - return PyInt_FromLong(x); + return long_long(v); } static PyObject * @@ -3246,15 +3478,25 @@ if (type != &PyLong_Type) return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, &x, &base)) return NULL; if (x == NULL) return PyLong_FromLong(0L); if (base == -909) return PyNumber_Long(x); - else if (PyString_Check(x)) - return PyLong_FromString(PyString_AS_STRING(x), NULL, base); + else if (PyString_Check(x)) { + char *s = PyString_AS_STRING(x); + char *end; + PyObject *r = PyLong_FromString(s, &end, base); + if (r != NULL && end != s + PyString_GET_SIZE(x)) { + PyErr_SetString(PyExc_ValueError, + "null byte in argument for int()"); + Py_DECREF(r); + r = NULL; + } + return r; + } #ifdef Py_USING_UNICODE else if (PyUnicode_Check(x)) return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), @@ -3263,7 +3505,7 @@ #endif else { PyErr_SetString(PyExc_TypeError, - "long() can't convert non-string with explicit base"); + "int() can't convert non-string with explicit base"); return NULL; } } @@ -3312,9 +3554,9 @@ }; PyDoc_STRVAR(long_doc, -"long(x[, base]) -> integer\n\ +"int(x[, base]) -> integer\n\ \n\ -Convert a string or number to a long integer, if possible. A floating\n\ +Convert a string or number to an integer, if possible. A floating\n\ point argument will be truncated towards zero (this does not include a\n\ string representation of a floating point number!) When converting a\n\ string, use the optional base. It is an error to supply a base when\n\ @@ -3363,8 +3605,10 @@ PyTypeObject PyLong_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ - "long", /* tp_name */ - sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */ + "int", /* tp_name */ + /* See _PyLong_New for why this isn't + sizeof(PyLongObject) - sizeof(digit) */ + sizeof(PyVarObject), /* tp_basicsize */ sizeof(digit), /* tp_itemsize */ long_dealloc, /* tp_dealloc */ 0, /* tp_print */ @@ -3377,7 +3621,7 @@ 0, /* tp_as_mapping */ (hashfunc)long_hash, /* tp_hash */ 0, /* tp_call */ - 0, /* tp_str */ + long_repr, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ @@ -3402,3 +3646,43 @@ long_new, /* tp_new */ PyObject_Del, /* tp_free */ }; + +int +_PyLong_Init(void) +{ +#if NSMALLNEGINTS + NSMALLPOSINTS > 0 + int ival; + PyLongObject *v = small_ints; + for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) { + PyObject_INIT(v, &PyLong_Type); + v->ob_size = -1; + v->ob_digit[0] = -ival; + } + for (; ival < NSMALLPOSINTS; ival++, v++) { + PyObject_INIT(v, &PyLong_Type); + v->ob_size = ival ? 1 : 0; + v->ob_digit[0] = ival; + } +#endif + return 1; +} + +void +PyLong_Fini(void) +{ +#if 0 + int i; + /* This is currently not needed; the small integers + are statically allocated */ +#if NSMALLNEGINTS + NSMALLPOSINTS > 0 + PyIntObject **q; + + i = NSMALLNEGINTS + NSMALLPOSINTS; + q = small_ints; + while (--i >= 0) { + Py_XDECREF(*q); + *q++ = NULL; + } +#endif +#endif +} Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Sun Jan 14 04:31:43 2007 @@ -4221,6 +4221,14 @@ int numdigits; /* len == numnondigits + numdigits */ int numnondigits = 0; + /* Avoid exceeding SSIZE_T_MAX */ + if (prec > PY_SSIZE_T_MAX-3) { + PyErr_SetString(PyExc_OverflowError, + "precision too large"); + return NULL; + } + + switch (type) { case 'd': case 'u': @@ -4565,6 +4573,8 @@ goto error; } width = PyInt_AsLong(v); + if (width == -1 && PyErr_Occurred()) + goto error; if (width < 0) { flags |= F_LJUST; width = -width; @@ -4602,6 +4612,8 @@ goto error; } prec = PyInt_AsLong(v); + if (prec == -1 && PyErr_Occurred()) + goto error; if (prec < 0) prec = 0; if (--fmtcnt >= 0) Modified: python/branches/p3yk/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk/Objects/unicodeobject.c (original) +++ python/branches/p3yk/Objects/unicodeobject.c Sun Jan 14 04:31:43 2007 @@ -7585,6 +7585,8 @@ goto onError; } width = PyInt_AsLong(v); + if (width == -1 && PyErr_Occurred()) + goto onError; if (width < 0) { flags |= F_LJUST; width = -width; @@ -7620,6 +7622,8 @@ goto onError; } prec = PyInt_AsLong(v); + if (prec == -1 && PyErr_Occurred()) + goto onError; if (prec < 0) prec = 0; if (--fmtcnt >= 0) Modified: python/branches/p3yk/PC/_msi.c ============================================================================== --- python/branches/p3yk/PC/_msi.c (original) +++ python/branches/p3yk/PC/_msi.c Sun Jan 14 04:31:43 2007 @@ -543,7 +543,7 @@ if (PyString_Check(data)) { status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR, 0, NULL, PyString_AsString(data)); - } else if (PyInt_Check(data)) { + } else if (PyInt_CheckExact(data)) { status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, PyInt_AsLong(data), NULL, NULL); } else { Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Sun Jan 14 04:31:43 2007 @@ -2124,7 +2124,7 @@ SETBUILTIN("float", &PyFloat_Type); SETBUILTIN("frozenset", &PyFrozenSet_Type); SETBUILTIN("property", &PyProperty_Type); - SETBUILTIN("int", &PyInt_Type); + SETBUILTIN("int", &PyLong_Type); SETBUILTIN("list", &PyList_Type); SETBUILTIN("long", &PyLong_Type); SETBUILTIN("object", &PyBaseObject_Type); Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Sun Jan 14 04:31:43 2007 @@ -3900,7 +3900,7 @@ { if (v != NULL) { Py_ssize_t x; - if (PyInt_Check(v)) { + if (PyInt_CheckExact(v)) { /* XXX(nnorwitz): I think PyInt_AS_LONG is correct, however, it looks like it should be AsSsize_t. There should be a comment here explaining why. Modified: python/branches/p3yk/Python/getargs.c ============================================================================== --- python/branches/p3yk/Python/getargs.c (original) +++ python/branches/p3yk/Python/getargs.c Sun Jan 14 04:31:43 2007 @@ -720,9 +720,7 @@ case 'K': { /* long long sized bitfield */ unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); unsigned PY_LONG_LONG ival; - if (PyInt_Check(arg)) - ival = PyInt_AsUnsignedLongMask(arg); - else if (PyLong_Check(arg)) + if (PyLong_Check(arg)) ival = PyLong_AsUnsignedLongLongMask(arg); else return converterr("integer", arg, msgbuf, bufsize); Modified: python/branches/p3yk/Python/marshal.c ============================================================================== --- python/branches/p3yk/Python/marshal.c (original) +++ python/branches/p3yk/Python/marshal.c Sun Jan 14 04:31:43 2007 @@ -144,31 +144,34 @@ else if (v == Py_True) { w_byte(TYPE_TRUE, p); } - else if (PyInt_Check(v)) { - long x = PyInt_AS_LONG((PyIntObject *)v); + else if (PyLong_Check(v)) { + long x = PyLong_AsLong(v); + if ((x == -1) && PyErr_Occurred()) { + PyLongObject *ob = (PyLongObject *)v; + PyErr_Clear(); + w_byte(TYPE_LONG, p); + n = ob->ob_size; + w_long((long)n, p); + if (n < 0) + n = -n; + for (i = 0; i < n; i++) + w_short(ob->ob_digit[i], p); + } + else { #if SIZEOF_LONG > 4 - long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); - if (y && y != -1) { - w_byte(TYPE_INT64, p); - w_long64(x, p); - } - else + long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); + if (y && y != -1) { + w_byte(TYPE_INT64, p); + w_long64(x, p); + } + else #endif { - w_byte(TYPE_INT, p); - w_long(x, p); + w_byte(TYPE_INT, p); + w_long(x, p); + } } } - else if (PyLong_Check(v)) { - PyLongObject *ob = (PyLongObject *)v; - w_byte(TYPE_LONG, p); - n = ob->ob_size; - w_long((long)n, p); - if (n < 0) - n = -n; - for (i = 0; i < n; i++) - w_short(ob->ob_digit[i], p); - } else if (PyFloat_Check(v)) { if (p->version > 1) { unsigned char buf[8]; Modified: python/branches/p3yk/Python/pythonrun.c ============================================================================== --- python/branches/p3yk/Python/pythonrun.c (original) +++ python/branches/p3yk/Python/pythonrun.c Sun Jan 14 04:31:43 2007 @@ -60,6 +60,8 @@ static void call_ll_exitfuncs(void); extern void _PyUnicode_Init(void); extern void _PyUnicode_Fini(void); +extern int _PyLong_Init(void); +extern void PyLong_Fini(void); #ifdef WITH_THREAD extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *); @@ -181,8 +183,8 @@ if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); - if (!_PyInt_Init()) - Py_FatalError("Py_Initialize: can't init ints"); + if (!_PyLong_Init()) + Py_FatalError("Py_Initialize: can't init longs"); _PyFloat_Init(); @@ -453,7 +455,7 @@ PyList_Fini(); PySet_Fini(); PyString_Fini(); - PyInt_Fini(); + PyLong_Fini(); PyFloat_Fini(); #ifdef Py_USING_UNICODE Modified: python/branches/p3yk/Python/traceback.c ============================================================================== --- python/branches/p3yk/Python/traceback.c (original) +++ python/branches/p3yk/Python/traceback.c Sun Jan 14 04:31:43 2007 @@ -250,7 +250,7 @@ return -1; } limitv = PySys_GetObject("tracebacklimit"); - if (limitv && PyInt_Check(limitv)) { + if (limitv && PyInt_CheckExact(limitv)) { limit = PyInt_AsLong(limitv); if (limit <= 0) return 0; From python-3000-checkins at python.org Sun Jan 14 04:42:31 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 04:42:31 +0100 (CET) Subject: [Python-3000-checkins] r53422 - python/branches/p3yk/Misc/NEWS Message-ID: <20070114034231.5296D1E400C@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 04:42:30 2007 New Revision: 53422 Modified: python/branches/p3yk/Misc/NEWS Log: News about int/long unification and except syntax change. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Sun Jan 14 04:42:30 2007 @@ -36,6 +36,13 @@ Core and Builtins ----------------- +- Int/Long unification is halfway complete. There are a few broken tests, + the 'long' built-in hasn't been removed yet, and literals with trailing + 'L' or 'l' are still recognized. Performance may be sub-optimal. + +- 'except E, V' must now be spelled as 'except E as V' and deletes V + at the end of the except clause; V must be a simple name. + - Added function annotations per PEP 3107. - Moved intern() to sys.intern(). From python-3000-checkins at python.org Sun Jan 14 05:02:17 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 05:02:17 +0100 (CET) Subject: [Python-3000-checkins] r53424 - in python/branches/p3yk: BROKEN_TESTS Modules/cPickle.c Message-ID: <20070114040217.D1E5A1E400C@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 05:02:16 2007 New Revision: 53424 Modified: python/branches/p3yk/BROKEN_TESTS python/branches/p3yk/Modules/cPickle.c Log: Fix cPickle breakage due to last-minute change to the name of the 'long' type (it's not called 'int' :-). Modified: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- python/branches/p3yk/BROKEN_TESTS (original) +++ python/branches/p3yk/BROKEN_TESTS Sun Jan 14 05:02:16 2007 @@ -1,4 +1,3 @@ -test_descr -- can't pickle int objects?!?! -test_pickletools -- ??? +test_pickletools -- Test probably needs to be fixed test_socket -- OverflowError: can't convert negative value to unsigned int test_sqlite -- ??? Modified: python/branches/p3yk/Modules/cPickle.c ============================================================================== --- python/branches/p3yk/Modules/cPickle.c (original) +++ python/branches/p3yk/Modules/cPickle.c Sun Jan 14 05:02:16 2007 @@ -2191,7 +2191,7 @@ goto finally; } break; - case 'l': + case 'i': if (type == &PyLong_Type) { res = save_long(self, args); goto finally; From python-3000-checkins at python.org Sun Jan 14 17:55:37 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 17:55:37 +0100 (CET) Subject: [Python-3000-checkins] r53433 - python/branches/p3yk/BROKEN_TESTS Message-ID: <20070114165537.11D5C1E401E@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 17:55:36 2007 New Revision: 53433 Modified: python/branches/p3yk/BROKEN_TESTS Log: Honesty before all. Modified: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- python/branches/p3yk/BROKEN_TESTS (original) +++ python/branches/p3yk/BROKEN_TESTS Sun Jan 14 17:55:36 2007 @@ -1,3 +1,5 @@ +test_format -- '%o' % 0 works? ... no # Unexpected : 'expected string or Unicode object, int found' test_pickletools -- Test probably needs to be fixed +test_repr -- test_numbers() fails test_socket -- OverflowError: can't convert negative value to unsigned int -test_sqlite -- ??? +test_sqlite -- CheckLargeInt (sqlite3.test.types.SqliteTypeTests, sqlite3.test.types.DeclTypesTests) From python-3000-checkins at python.org Sun Jan 14 19:43:49 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 19:43:49 +0100 (CET) Subject: [Python-3000-checkins] r53438 - python/branches/p3yk/Lib/ftplib.py Message-ID: <20070114184349.A65F71E4005@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 19:43:49 2007 New Revision: 53438 Modified: python/branches/p3yk/Lib/ftplib.py Log: Fix new bug in ftplib.py introduced by exception scope limitation. Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Sun Jan 14 19:43:49 2007 @@ -119,7 +119,8 @@ try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) - except socket.error as msg: + except socket.error as err: + msg = err if self.sock: self.sock.close() self.sock = None From python-3000-checkins at python.org Sun Jan 14 19:52:07 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 14 Jan 2007 19:52:07 +0100 (CET) Subject: [Python-3000-checkins] r53439 - in python/branches/p3yk: BROKEN_TESTS Lib/test/test_format.py Message-ID: <20070114185207.79C141E4005@bag.python.org> Author: guido.van.rossum Date: Sun Jan 14 19:52:06 2007 New Revision: 53439 Modified: python/branches/p3yk/BROKEN_TESTS python/branches/p3yk/Lib/test/test_format.py Log: One more test breakage hits the dust. The test was clearly in the wrong. Modified: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- python/branches/p3yk/BROKEN_TESTS (original) +++ python/branches/p3yk/BROKEN_TESTS Sun Jan 14 19:52:06 2007 @@ -1,5 +1,4 @@ -test_format -- '%o' % 0 works? ... no # Unexpected : 'expected string or Unicode object, int found' test_pickletools -- Test probably needs to be fixed test_repr -- test_numbers() fails -test_socket -- OverflowError: can't convert negative value to unsigned int +test_socket -- ntol problems, see SF patch 1635058 test_sqlite -- CheckLargeInt (sqlite3.test.types.SqliteTypeTests, sqlite3.test.types.DeclTypesTests) Modified: python/branches/p3yk/Lib/test/test_format.py ============================================================================== --- python/branches/p3yk/Lib/test/test_format.py (original) +++ python/branches/p3yk/Lib/test/test_format.py Sun Jan 14 19:52:06 2007 @@ -236,7 +236,7 @@ return self + 1 test_exc('%o', Foobar(), TypeError, - "expected string or Unicode object, long found") + "expected string or Unicode object, int found") if sys.maxint == 2**31-1: # crashes 2.2.1 and earlier: From python-3000-checkins at python.org Mon Jan 15 01:07:33 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 01:07:33 +0100 (CET) Subject: [Python-3000-checkins] r53443 - in python/branches/p3yk: Lib/test/test_socket.py Misc/ACKS Modules/socketmodule.c Message-ID: <20070115000733.C415C1E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 01:07:32 2007 New Revision: 53443 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Misc/ACKS python/branches/p3yk/Modules/socketmodule.c Log: Merged revisions 53434 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53434 | guido.van.rossum | 2007-01-14 09:03:32 -0800 (Sun, 14 Jan 2007) | 3 lines Patch #1635058 by Mark Roberts: ensure that htonl and friends never accept or return negative numbers, per the underlying C implementation. ........ Modified: python/branches/p3yk/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket.py (original) +++ python/branches/p3yk/Lib/test/test_socket.py Mon Jan 15 01:07:32 2007 @@ -310,6 +310,20 @@ self.assertEqual(swapped & mask, mask) self.assertRaises(OverflowError, func, 1L<<34) + def testNtoHErrors(self): + good_values = [ 1, 2, 3, 1L, 2L, 3L ] + bad_values = [ -1, -2, -3, -1L, -2L, -3L ] + for k in good_values: + socket.ntohl(k) + socket.ntohs(k) + socket.htonl(k) + socket.htons(k) + for k in bad_values: + self.assertRaises(OverflowError, socket.ntohl, k) + self.assertRaises(OverflowError, socket.ntohs, k) + self.assertRaises(OverflowError, socket.htonl, k) + self.assertRaises(OverflowError, socket.htons, k) + def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. Modified: python/branches/p3yk/Misc/ACKS ============================================================================== --- python/branches/p3yk/Misc/ACKS (original) +++ python/branches/p3yk/Misc/ACKS Mon Jan 15 01:07:32 2007 @@ -521,6 +521,7 @@ Nicholas Riley Jean-Claude Rimbault Anthony Roach +Mark Roberts Andy Robinson Jim Robinson Kevin Rodgers Modified: python/branches/p3yk/Modules/socketmodule.c ============================================================================== --- python/branches/p3yk/Modules/socketmodule.c (original) +++ python/branches/p3yk/Modules/socketmodule.c Mon Jan 15 01:07:32 2007 @@ -3468,7 +3468,12 @@ if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { return NULL; } - x2 = (int)ntohs((short)x1); + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)ntohs((unsigned short)x1); return PyInt_FromLong(x2); } @@ -3505,7 +3510,7 @@ arg->ob_type->tp_name); if (x == (unsigned long) -1 && PyErr_Occurred()) return NULL; - return PyInt_FromLong(ntohl(x)); + return PyLong_FromUnsignedLong(ntohl(x)); } PyDoc_STRVAR(ntohl_doc, @@ -3522,7 +3527,12 @@ if (!PyArg_ParseTuple(args, "i:htons", &x1)) { return NULL; } - x2 = (int)htons((short)x1); + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)htons((unsigned short)x1); return PyInt_FromLong(x2); } @@ -3557,7 +3567,7 @@ return PyErr_Format(PyExc_TypeError, "expected int/long, %s found", arg->ob_type->tp_name); - return PyInt_FromLong(htonl(x)); + return PyLong_FromUnsignedLong(htonl((unsigned long)x)); } PyDoc_STRVAR(htonl_doc, From python-3000-checkins at python.org Mon Jan 15 01:14:39 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 01:14:39 +0100 (CET) Subject: [Python-3000-checkins] r53444 - in python/branches/p3yk: BROKEN_TESTS Lib/repr.py Message-ID: <20070115001439.AF3E01E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 01:14:39 2007 New Revision: 53444 Modified: python/branches/p3yk/BROKEN_TESTS python/branches/p3yk/Lib/repr.py Log: Fix repr.py -- it was triggering on the type name 'long', should be 'int'. Modified: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- python/branches/p3yk/BROKEN_TESTS (original) +++ python/branches/p3yk/BROKEN_TESTS Mon Jan 15 01:14:39 2007 @@ -1,4 +1,2 @@ test_pickletools -- Test probably needs to be fixed -test_repr -- test_numbers() fails -test_socket -- ntol problems, see SF patch 1635058 test_sqlite -- CheckLargeInt (sqlite3.test.types.SqliteTypeTests, sqlite3.test.types.DeclTypesTests) Modified: python/branches/p3yk/Lib/repr.py ============================================================================== --- python/branches/p3yk/Lib/repr.py (original) +++ python/branches/p3yk/Lib/repr.py Mon Jan 15 01:14:39 2007 @@ -92,7 +92,7 @@ s = s[:i] + '...' + s[len(s)-j:] return s - def repr_long(self, x, level): + def repr_int(self, x, level): s = __builtin__.repr(x) # XXX Hope this isn't too slow... if len(s) > self.maxlong: i = max(0, (self.maxlong-3)//2) From python-3000-checkins at python.org Mon Jan 15 01:21:47 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 01:21:47 +0100 (CET) Subject: [Python-3000-checkins] r53445 - in python/branches/p3yk: BROKEN_TESTS Lib/pickletools.py Message-ID: <20070115002147.03BAF1E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 01:21:46 2007 New Revision: 53445 Modified: python/branches/p3yk/BROKEN_TESTS python/branches/p3yk/Lib/pickletools.py Log: Fix pickletools doctests -- all we get nowadays is longs. (Hmm... Shouldn't longs of certain sizes be pickled using 'I' opcodes? Later.) Modified: python/branches/p3yk/BROKEN_TESTS ============================================================================== --- python/branches/p3yk/BROKEN_TESTS (original) +++ python/branches/p3yk/BROKEN_TESTS Mon Jan 15 01:21:46 2007 @@ -1,2 +1 @@ -test_pickletools -- Test probably needs to be fixed test_sqlite -- CheckLargeInt (sqlite3.test.types.SqliteTypeTests, sqlite3.test.types.DeclTypesTests) Modified: python/branches/p3yk/Lib/pickletools.py ============================================================================== --- python/branches/p3yk/Lib/pickletools.py (original) +++ python/branches/p3yk/Lib/pickletools.py Mon Jan 15 01:21:46 2007 @@ -2000,13 +2000,13 @@ 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 - 5: I INT 1 + 5: L LONG 1 8: a APPEND - 9: I INT 2 + 9: L LONG 2 12: a APPEND 13: ( MARK - 14: I INT 3 - 17: I INT 4 + 14: L LONG 3 + 17: L LONG 4 20: t TUPLE (MARK at 13) 21: p PUT 1 24: a APPEND @@ -2079,7 +2079,7 @@ 93: p PUT 6 96: S STRING 'value' 105: p PUT 7 - 108: I INT 42 + 108: L LONG 42 112: s SETITEM 113: b BUILD 114: a APPEND From python-3000-checkins at python.org Mon Jan 15 01:31:50 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 01:31:50 +0100 (CET) Subject: [Python-3000-checkins] r53446 - in python/branches/p3yk: Misc/NEWS Modules/_sqlite/statement.c Objects/longobject.c Message-ID: <20070115003150.F16CA1E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 01:31:49 2007 New Revision: 53446 Modified: python/branches/p3yk/Misc/NEWS python/branches/p3yk/Modules/_sqlite/statement.c python/branches/p3yk/Objects/longobject.c Log: Fix the sqlite failure -- it was the usual, PyInt_Check -> PyInt_CheckExact. Clarify some OverflowError messages from the various PyLong_AsXXX methods. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Jan 15 01:31:49 2007 @@ -36,9 +36,9 @@ Core and Builtins ----------------- -- Int/Long unification is halfway complete. There are a few broken tests, - the 'long' built-in hasn't been removed yet, and literals with trailing - 'L' or 'l' are still recognized. Performance may be sub-optimal. +- Int/Long unification is halfway complete. The 'long' built-in type + hasn't been removed yet, and literals with trailing 'L' or 'l' are + still recognized. Performance may be sub-optimal. - 'except E, V' must now be spelled as 'except E as V' and deletes V at the end of the except clause; V must be a simple name. Modified: python/branches/p3yk/Modules/_sqlite/statement.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/statement.c (original) +++ python/branches/p3yk/Modules/_sqlite/statement.c Mon Jan 15 01:31:49 2007 @@ -100,7 +100,7 @@ if (parameter == Py_None) { rc = sqlite3_bind_null(self->st, pos); - } else if (PyInt_Check(parameter)) { + } else if (PyInt_CheckExact(parameter)) { longval = PyInt_AsLong(parameter); rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval); #ifdef HAVE_LONG_LONG Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Mon Jan 15 01:31:49 2007 @@ -364,7 +364,7 @@ Py_DECREF(vv); } PyErr_SetString(PyExc_OverflowError, - "int too large to convert to int"); + "Python int too large to convert to C long"); return -1; } @@ -427,7 +427,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "int too large to convert to "); + "Python int too large to convert to C ssize_t"); return -1; } @@ -462,7 +462,7 @@ x = (x << SHIFT) + v->ob_digit[i]; if ((x >> SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "int too large to convert"); + "python int too large to convert to C unsigned long"); return (unsigned long) -1; } } @@ -500,7 +500,7 @@ x = (x << SHIFT) + v->ob_digit[i]; if ((x >> SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "int too large to convert"); + "Python int too large to convert to C size_t"); return (unsigned long) -1; } } @@ -943,7 +943,7 @@ overflow: PyErr_SetString(PyExc_OverflowError, - "int too large to convert to float"); + "Python int too large to convert to C double"); return -1.0; } From python-3000-checkins at python.org Mon Jan 15 01:38:26 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 01:38:26 +0100 (CET) Subject: [Python-3000-checkins] r53448 - python/branches/p3yk/BROKEN_TESTS Message-ID: <20070115003826.0C5991E4020@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 01:38:25 2007 New Revision: 53448 Removed: python/branches/p3yk/BROKEN_TESTS Log: No more tests are broken AFAIK. Deleted: /python/branches/p3yk/BROKEN_TESTS ============================================================================== --- /python/branches/p3yk/BROKEN_TESTS Mon Jan 15 01:38:25 2007 +++ (empty file) @@ -1 +0,0 @@ -test_sqlite -- CheckLargeInt (sqlite3.test.types.SqliteTypeTests, sqlite3.test.types.DeclTypesTests) From python-3000-checkins at python.org Mon Jan 15 16:49:37 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 15 Jan 2007 16:49:37 +0100 (CET) Subject: [Python-3000-checkins] r53451 - in python/branches/p3yk: Doc/lib/liblogging.tex Doc/lib/libsmtplib.tex Doc/lib/libsocket.tex Doc/lib/libtest.tex Lib/BaseHTTPServer.py Lib/ctypes/__init__.py Lib/ctypes/test/test_win32.py Lib/ctypes/util.py Lib/ctypes/wintypes.py Lib/idlelib/EditorWindow.py Lib/logging/__init__.py Lib/logging/handlers.py Lib/platform.py Lib/pydoc.py Lib/sqlite3/dbapi2.py Lib/sqlite3/test/factory.py Lib/sqlite3/test/regression.py Lib/sqlite3/test/types.py Lib/subprocess.py Lib/test/test___all__.py Lib/test/test_optparse.py Lib/test/test_set.py Lib/test/test_subprocess.py Makefile.pre.in Modules/_ctypes/_ctypes.c Modules/_ctypes/libffi_msvc/ffi.c Modules/_sqlite/cache.c Modules/_sqlite/cache.h Modules/_sqlite/connection.c Modules/_sqlite/connection.h Modules/_sqlite/cursor.c Modules/_sqlite/cursor.h Modules/_sqlite/microprotocols.c Modules/_sqlite/microprotocols.h Modules/_sqlite/module.c Modules/_sqlite/module.h Modules/_sqlite/prepare_protocol.c Modules/_sqlite/prepare_protocol.h Modules/_sqlite/row.c Modules/_sqlite/row.h Modules/_sqlite/statement.c Modules/_sqlite/statement.h Modules/_sqlite/util.c Modules/_sqlite/util.h Objects/intobject.c Objects/setobject.c Python/Python-ast.c Tools/pybench/pybench.py Message-ID: <20070115154937.780661E4008@bag.python.org> Author: thomas.wouters Date: Mon Jan 15 16:49:28 2007 New Revision: 53451 Modified: python/branches/p3yk/ (props changed) python/branches/p3yk/Doc/lib/liblogging.tex python/branches/p3yk/Doc/lib/libsmtplib.tex python/branches/p3yk/Doc/lib/libsocket.tex python/branches/p3yk/Doc/lib/libtest.tex python/branches/p3yk/Lib/BaseHTTPServer.py python/branches/p3yk/Lib/ctypes/__init__.py python/branches/p3yk/Lib/ctypes/test/test_win32.py python/branches/p3yk/Lib/ctypes/util.py python/branches/p3yk/Lib/ctypes/wintypes.py python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/logging/handlers.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/sqlite3/dbapi2.py python/branches/p3yk/Lib/sqlite3/test/factory.py python/branches/p3yk/Lib/sqlite3/test/regression.py python/branches/p3yk/Lib/sqlite3/test/types.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/test/test___all__.py python/branches/p3yk/Lib/test/test_optparse.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_subprocess.py python/branches/p3yk/Makefile.pre.in python/branches/p3yk/Modules/_ctypes/_ctypes.c python/branches/p3yk/Modules/_ctypes/libffi_msvc/ffi.c python/branches/p3yk/Modules/_sqlite/cache.c python/branches/p3yk/Modules/_sqlite/cache.h python/branches/p3yk/Modules/_sqlite/connection.c python/branches/p3yk/Modules/_sqlite/connection.h python/branches/p3yk/Modules/_sqlite/cursor.c python/branches/p3yk/Modules/_sqlite/cursor.h python/branches/p3yk/Modules/_sqlite/microprotocols.c python/branches/p3yk/Modules/_sqlite/microprotocols.h python/branches/p3yk/Modules/_sqlite/module.c python/branches/p3yk/Modules/_sqlite/module.h python/branches/p3yk/Modules/_sqlite/prepare_protocol.c python/branches/p3yk/Modules/_sqlite/prepare_protocol.h python/branches/p3yk/Modules/_sqlite/row.c python/branches/p3yk/Modules/_sqlite/row.h python/branches/p3yk/Modules/_sqlite/statement.c python/branches/p3yk/Modules/_sqlite/statement.h python/branches/p3yk/Modules/_sqlite/util.c python/branches/p3yk/Modules/_sqlite/util.h python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Tools/pybench/pybench.py Log: Merged revisions 53304-53433,53435-53450 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r53304 | vinay.sajip | 2007-01-09 15:50:28 +0100 (Tue, 09 Jan 2007) | 1 line Bug #1627575: Added _open() method to FileHandler which can be used to reopen files. The FileHandler instance now saves the encoding (which can be None) in an attribute called "encoding". ........ r53305 | vinay.sajip | 2007-01-09 15:51:36 +0100 (Tue, 09 Jan 2007) | 1 line Added entry about addition of _open() method to logging.FileHandler. ........ r53306 | vinay.sajip | 2007-01-09 15:54:56 +0100 (Tue, 09 Jan 2007) | 1 line Added a docstring ........ r53316 | thomas.heller | 2007-01-09 20:19:33 +0100 (Tue, 09 Jan 2007) | 4 lines Verify the sizes of the basic ctypes data types against the struct module. Will backport to release25-maint. ........ r53340 | gustavo.niemeyer | 2007-01-10 17:13:40 +0100 (Wed, 10 Jan 2007) | 3 lines Mention in the int() docstring that a base zero has meaning, as stated in http://docs.python.org/lib/built-in-funcs.html as well. ........ r53341 | gustavo.niemeyer | 2007-01-10 17:15:48 +0100 (Wed, 10 Jan 2007) | 2 lines Minor change in int() docstring for proper spacing. ........ r53358 | thomas.heller | 2007-01-10 21:12:13 +0100 (Wed, 10 Jan 2007) | 1 line Change the ctypes version number to "1.1.0". ........ r53361 | thomas.heller | 2007-01-10 21:51:19 +0100 (Wed, 10 Jan 2007) | 1 line Must change the version number in the _ctypes extension as well. ........ r53362 | guido.van.rossum | 2007-01-11 00:12:56 +0100 (Thu, 11 Jan 2007) | 3 lines Fix the signature of log_error(). (A subclass that did the right thing was getting complaints from pychecker.) ........ r53370 | matthias.klose | 2007-01-11 11:26:31 +0100 (Thu, 11 Jan 2007) | 2 lines - Make the documentation match the code and the docstring ........ r53375 | matthias.klose | 2007-01-11 12:44:04 +0100 (Thu, 11 Jan 2007) | 2 lines - idle: Honor the "Cancel" action in the save dialog (Debian bug #299092). ........ r53381 | raymond.hettinger | 2007-01-11 19:22:55 +0100 (Thu, 11 Jan 2007) | 1 line SF #1486663 -- Allow keyword args in subclasses of set() and frozenset(). ........ r53388 | thomas.heller | 2007-01-11 22:18:56 +0100 (Thu, 11 Jan 2007) | 4 lines Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions of HANDLE, WPARAM, LPARAM data types. Make parameterless foreign function calls work. ........ r53390 | thomas.heller | 2007-01-11 22:23:12 +0100 (Thu, 11 Jan 2007) | 2 lines Correct the comments: the code is right. ........ r53393 | brett.cannon | 2007-01-12 08:27:52 +0100 (Fri, 12 Jan 2007) | 3 lines Fix error where the end of a funcdesc environment was accidentally moved too far down. ........ r53397 | anthony.baxter | 2007-01-12 10:35:56 +0100 (Fri, 12 Jan 2007) | 3 lines add parsetok.h as a dependency - previously, changing this file doesn't cause the right files to be rebuilt. ........ r53401 | thomas.heller | 2007-01-12 21:08:19 +0100 (Fri, 12 Jan 2007) | 3 lines Avoid warnings in the test suite because ctypes.wintypes cannot be imported on non-windows systems. ........ r53402 | thomas.heller | 2007-01-12 21:17:34 +0100 (Fri, 12 Jan 2007) | 6 lines patch #1610795: BSD version of ctypes.util.find_library, by Martin Kammerhofer. release25-maint backport candidate, but the release manager has to decide. ........ r53403 | thomas.heller | 2007-01-12 21:21:53 +0100 (Fri, 12 Jan 2007) | 3 lines patch #1610795: BSD version of ctypes.util.find_library, by Martin Kammerhofer. ........ r53406 | brett.cannon | 2007-01-13 01:29:49 +0100 (Sat, 13 Jan 2007) | 2 lines Deprecate the sets module. ........ r53407 | georg.brandl | 2007-01-13 13:31:51 +0100 (Sat, 13 Jan 2007) | 3 lines Fix typo. ........ r53409 | marc-andre.lemburg | 2007-01-13 22:00:08 +0100 (Sat, 13 Jan 2007) | 16 lines Bump version number and change copyright year. Add new API linux_distribution() which supports reading the full distribution name and also knows how to parse LSB-style release files. Redirect the old dist() API to the new API (using the short distribution name taken from the release file filename). Add branch and revision to _sys_version(). Add work-around for Cygwin to libc_ver(). Add support for IronPython (thanks for Anthony Baxter) and make Jython support more robust. ........ r53410 | neal.norwitz | 2007-01-13 22:22:37 +0100 (Sat, 13 Jan 2007) | 1 line Fix grammar in docstrings ........ r53411 | marc-andre.lemburg | 2007-01-13 23:32:21 +0100 (Sat, 13 Jan 2007) | 9 lines Add parameter sys_version to _sys_version(). Change the cache for _sys_version() to take the parameter into account. Add support for parsing the IronPython 1.0.1 sys.version value - even though it still returns '1.0.0'; the version string no longer includes the patch level. ........ r53412 | peter.astrand | 2007-01-13 23:35:35 +0100 (Sat, 13 Jan 2007) | 1 line Fix for bug #1634343: allow specifying empty arguments on Windows ........ r53414 | marc-andre.lemburg | 2007-01-13 23:59:36 +0100 (Sat, 13 Jan 2007) | 14 lines Add Python implementation to the machine details. Pretty-print the Python version used for running PyBench. Let the user know when calibration has finished. [ 1563844 ] pybench support for IronPython: Simplify Unicode version detection. Make garbage collection and check interval settings optional if the Python implementation doesn't support thess (e.g. IronPython). ........ r53415 | marc-andre.lemburg | 2007-01-14 00:13:54 +0100 (Sun, 14 Jan 2007) | 5 lines Use defaults if sys.executable isn't set (e.g. on Jython). This change allows running PyBench under Jython. ........ r53416 | marc-andre.lemburg | 2007-01-14 00:15:33 +0100 (Sun, 14 Jan 2007) | 3 lines Jython doesn't have sys.setcheckinterval() - ignore it in that case. ........ r53420 | gerhard.haering | 2007-01-14 02:43:50 +0100 (Sun, 14 Jan 2007) | 29 lines Merged changes from standalone version 2.3.3. This should probably all be merged into the 2.5 maintenance branch: - self->statement was not checked while fetching data, which could lead to crashes if you used the pysqlite API in unusual ways. Closing the cursor and continuing to fetch data was enough. - Converters are stored in a converters dictionary. The converter name is uppercased first. The old upper-casing algorithm was wrong and was replaced by a simple call to the Python string's upper() method instead. -Applied patch by Glyph Lefkowitz that fixes the problem with subsequent SQLITE_SCHEMA errors. - Improvement to the row type: rows can now be iterated over and have a keys() method. This improves compatibility with both tuple and dict a lot. - A bugfix for the subsecond resolution in timestamps. - Corrected the way the flags PARSE_DECLTYPES and PARSE_COLNAMES are checked for. Now they work as documented. - gcc on Linux sucks. It exports all symbols by default in shared libraries, so if symbols are not unique it can lead to problems with symbol lookup. pysqlite used to crash under Apache when mod_cache was enabled because both modules had the symbol cache_init. I fixed this by applying the prefix pysqlite_ almost everywhere. Sigh. ........ r53423 | guido.van.rossum | 2007-01-14 04:46:33 +0100 (Sun, 14 Jan 2007) | 2 lines Remove a dependency of this test on $COLUMNS. ........ r53425 | ka-ping.yee | 2007-01-14 05:25:15 +0100 (Sun, 14 Jan 2007) | 3 lines Handle old-style instances more gracefully (display documentation on the relevant class instead of documentation on ). ........ r53440 | vinay.sajip | 2007-01-14 22:49:59 +0100 (Sun, 14 Jan 2007) | 1 line Added WatchedFileHandler (based on SF patch #1598415) ........ r53441 | vinay.sajip | 2007-01-14 22:50:50 +0100 (Sun, 14 Jan 2007) | 1 line Added documentation for WatchedFileHandler (based on SF patch #1598415) ........ r53442 | guido.van.rossum | 2007-01-15 01:02:35 +0100 (Mon, 15 Jan 2007) | 2 lines Doc patch matching r53434 (htonl etc. now always take/return positive ints). ........ Modified: python/branches/p3yk/Doc/lib/liblogging.tex ============================================================================== --- python/branches/p3yk/Doc/lib/liblogging.tex (original) +++ python/branches/p3yk/Doc/lib/liblogging.tex Mon Jan 15 16:49:28 2007 @@ -989,10 +989,11 @@ package, sends logging output to a disk file. It inherits the output functionality from \class{StreamHandler}. -\begin{classdesc}{FileHandler}{filename\optional{, mode}} +\begin{classdesc}{FileHandler}{filename\optional{, mode\optional{, encoding}}} Returns a new instance of the \class{FileHandler} class. The specified file is opened and used as the stream for logging. If \var{mode} is -not specified, \constant{'a'} is used. By default, the file grows +not specified, \constant{'a'} is used. If \var{encoding} is not \var{None}, +it is used to open the file with that encoding. By default, the file grows indefinitely. \end{classdesc} @@ -1004,6 +1005,41 @@ Outputs the record to the file. \end{methoddesc} +\subsubsection{WatchedFileHandler} + +\versionadded{2.6} +The \class{WatchedFileHandler} class, located in the \module{logging.handlers} +module, is a \class{FileHandler} which watches the file it is logging to. +If the file changes, it is closed and reopened using the file name. + +A file change can happen because of usage of programs such as \var{newsyslog} +and \var{logrotate} which perform log file rotation. This handler, intended +for use under Unix/Linux, watches the file to see if it has changed since the +last emit. (A file is deemed to have changed if its device or inode have +changed.) If the file has changed, the old file stream is closed, and the file +opened to get a new stream. + +This handler is not appropriate for use under Windows, because under Windows +open log files cannot be moved or renamed - logging opens the files with +exclusive locks - and so there is no need for such a handler. Furthermore, +\var{ST_INO} is not supported under Windows; \function{stat()} always returns +zero for this value. + +\begin{classdesc}{WatchedFileHandler}{filename\optional{,mode\optional{, + encoding}}} +Returns a new instance of the \class{WatchedFileHandler} class. The specified +file is opened and used as the stream for logging. If \var{mode} is +not specified, \constant{'a'} is used. If \var{encoding} is not \var{None}, +it is used to open the file with that encoding. By default, the file grows +indefinitely. +\end{classdesc} + +\begin{methoddesc}{emit}{record} +Outputs the record to the file, but first checks to see if the file has +changed. If it has, the existing stream is flushed and closed and the file +opened again, before outputting the record to the file. +\end{methoddesc} + \subsubsection{RotatingFileHandler} The \class{RotatingFileHandler} class, located in the \module{logging.handlers} Modified: python/branches/p3yk/Doc/lib/libsmtplib.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsmtplib.tex (original) +++ python/branches/p3yk/Doc/lib/libsmtplib.tex Mon Jan 15 16:49:28 2007 @@ -185,7 +185,7 @@ The server didn't reply properly to the \samp{HELO} greeting. \item[\exception{SMTPAuthenticationError}] The server didn't accept the username/password combination. - \item[\exception{SMTPError}] + \item[\exception{SMTPException}] No suitable authentication method was found. \end{description} \end{methoddesc} Modified: python/branches/p3yk/Doc/lib/libsocket.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libsocket.tex (original) +++ python/branches/p3yk/Doc/lib/libsocket.tex Mon Jan 15 16:49:28 2007 @@ -331,25 +331,25 @@ \end{funcdesc} \begin{funcdesc}{ntohl}{x} -Convert 32-bit integers from network to host byte order. On machines +Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. \end{funcdesc} \begin{funcdesc}{ntohs}{x} -Convert 16-bit integers from network to host byte order. On machines +Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. \end{funcdesc} \begin{funcdesc}{htonl}{x} -Convert 32-bit integers from host to network byte order. On machines +Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. \end{funcdesc} \begin{funcdesc}{htons}{x} -Convert 16-bit integers from host to network byte order. On machines +Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libtest.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libtest.tex (original) +++ python/branches/p3yk/Doc/lib/libtest.tex Mon Jan 15 16:49:28 2007 @@ -281,6 +281,7 @@ The optional argument \var{testclass} accepts one of the test classes in the suite so as to print out more detailed information on where the testing suite originated from. +\end{funcdesc} The \module{test.test_support} module defines the following classes: @@ -299,4 +300,3 @@ Temporarily unset the environment variable \code{envvar}. \end{methoddesc} -\end{funcdesc} Modified: python/branches/p3yk/Lib/BaseHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/BaseHTTPServer.py (original) +++ python/branches/p3yk/Lib/BaseHTTPServer.py Mon Jan 15 16:49:28 2007 @@ -396,7 +396,7 @@ self.log_message('"%s" %s %s', self.requestline, str(code), str(size)) - def log_error(self, *args): + def log_error(self, format, *args): """Log an error. This is called when a request cannot be fulfilled. By @@ -408,7 +408,7 @@ """ - self.log_message(*args) + self.log_message(format, *args) def log_message(self, format, *args): """Log an arbitrary message. Modified: python/branches/p3yk/Lib/ctypes/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/__init__.py Mon Jan 15 16:49:28 2007 @@ -5,7 +5,7 @@ import os as _os, sys as _sys -__version__ = "1.0.1" +__version__ = "1.1.0" from _ctypes import Union, Structure, Array from _ctypes import _Pointer @@ -133,6 +133,18 @@ from _ctypes import sizeof, byref, addressof, alignment, resize from _ctypes import _SimpleCData +def _check_size(typ, typecode=None): + # Check if sizeof(ctypes_type) against struct.calcsize. This + # should protect somewhat against a misconfigured libffi. + from struct import calcsize + if typecode is None: + # Most _type_ codes are the same as used in struct + typecode = typ._type_ + actual, required = sizeof(typ), calcsize(typecode) + if actual != required: + raise SystemError("sizeof(%s) wrong: %d instead of %d" % \ + (typ, actual, required)) + class py_object(_SimpleCData): _type_ = "O" def __repr__(self): @@ -140,18 +152,23 @@ return super(py_object, self).__repr__() except ValueError: return "%s()" % type(self).__name__ +_check_size(py_object, "P") class c_short(_SimpleCData): _type_ = "h" +_check_size(c_short) class c_ushort(_SimpleCData): _type_ = "H" +_check_size(c_ushort) class c_long(_SimpleCData): _type_ = "l" +_check_size(c_long) class c_ulong(_SimpleCData): _type_ = "L" +_check_size(c_ulong) if _calcsize("i") == _calcsize("l"): # if int and long have the same size, make c_int an alias for c_long @@ -160,15 +177,19 @@ else: class c_int(_SimpleCData): _type_ = "i" + _check_size(c_int) class c_uint(_SimpleCData): _type_ = "I" + _check_size(c_uint) class c_float(_SimpleCData): _type_ = "f" +_check_size(c_float) class c_double(_SimpleCData): _type_ = "d" +_check_size(c_double) if _calcsize("l") == _calcsize("q"): # if long and long long have the same size, make c_longlong an alias for c_long @@ -177,33 +198,40 @@ else: class c_longlong(_SimpleCData): _type_ = "q" + _check_size(c_longlong) class c_ulonglong(_SimpleCData): _type_ = "Q" ## def from_param(cls, val): ## return ('d', float(val), val) ## from_param = classmethod(from_param) + _check_size(c_ulonglong) class c_ubyte(_SimpleCData): _type_ = "B" c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte # backward compatibility: ##c_uchar = c_ubyte +_check_size(c_ubyte) class c_byte(_SimpleCData): _type_ = "b" c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte +_check_size(c_byte) class c_char(_SimpleCData): _type_ = "c" c_char.__ctype_le__ = c_char.__ctype_be__ = c_char +_check_size(c_char) class c_char_p(_SimpleCData): _type_ = "z" +_check_size(c_char_p, "P") class c_void_p(_SimpleCData): _type_ = "P" c_voidp = c_void_p # backwards compatibility (to a bug) +_check_size(c_void_p) # This cache maps types to pointers to them. _pointer_type_cache = {} Modified: python/branches/p3yk/Lib/ctypes/test/test_win32.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_win32.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_win32.py Mon Jan 15 16:49:28 2007 @@ -32,12 +32,32 @@ # or wrong calling convention self.assertRaises(ValueError, IsWindow, None) +if sys.platform == "win32": + class FunctionCallTestCase(unittest.TestCase): + if is_resource_enabled("SEH"): def test_SEH(self): - # Call functions with invalid arguments, and make sure that access violations - # are trapped and raise an exception. + # Call functions with invalid arguments, and make sure + # that access violations are trapped and raise an + # exception. self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32) + def test_noargs(self): + # This is a special case on win32 x64 + windll.user32.GetDesktopWindow() + + class TestWintypes(unittest.TestCase): + def test_HWND(self): + from ctypes import wintypes + self.failUnlessEqual(sizeof(wintypes.HWND), sizeof(c_void_p)) + + def test_PARAM(self): + from ctypes import wintypes + self.failUnlessEqual(sizeof(wintypes.WPARAM), + sizeof(c_void_p)) + self.failUnlessEqual(sizeof(wintypes.LPARAM), + sizeof(c_void_p)) + class Structures(unittest.TestCase): def test_struct_by_value(self): Modified: python/branches/p3yk/Lib/ctypes/util.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/util.py (original) +++ python/branches/p3yk/Lib/ctypes/util.py Mon Jan 15 16:49:28 2007 @@ -46,24 +46,17 @@ import re, tempfile, errno def _findLib_gcc(name): - expr = '[^\(\)\s]*lib%s\.[^\(\)\s]*' % name + expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) fdout, ccout = tempfile.mkstemp() os.close(fdout) - cmd = 'if type gcc &>/dev/null; then CC=gcc; else CC=cc; fi;' \ + cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \ '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name try: - fdout, outfile = tempfile.mkstemp() - os.close(fdout) - fd = os.popen(cmd) - trace = fd.read() - err = fd.close() + f = os.popen(cmd) + trace = f.read() + f.close() finally: try: - os.unlink(outfile) - except OSError as e: - if e.errno != errno.ENOENT: - raise - try: os.unlink(ccout) except OSError as e: if e.errno != errno.ENOENT: @@ -73,29 +66,58 @@ return None return res.group(0) - def _findLib_ld(name): - expr = '/[^\(\)\s]*lib%s\.[^\(\)\s]*' % name - res = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read()) - if not res: - # Hm, this works only for libs needed by the python executable. - cmd = 'ldd %s 2>/dev/null' % sys.executable - res = re.search(expr, os.popen(cmd).read()) - if not res: - return None - return res.group(0) - def _get_soname(f): + # assuming GNU binutils / ELF + if not f: + return None cmd = "objdump -p -j .dynamic 2>/dev/null " + f res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) if not res: return None return res.group(1) - def find_library(name): - lib = _findLib_ld(name) or _findLib_gcc(name) - if not lib: - return None - return _get_soname(lib) + if (sys.platform.startswith("freebsd") + or sys.platform.startswith("openbsd") + or sys.platform.startswith("dragonfly")): + + def _num_version(libname): + # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ] + parts = libname.split(".") + nums = [] + try: + while parts: + nums.insert(0, int(parts.pop())) + except ValueError: + pass + return nums or [ sys.maxint ] + + def find_library(name): + ename = re.escape(name) + expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename) + res = re.findall(expr, + os.popen('/sbin/ldconfig -r 2>/dev/null').read()) + if not res: + return _get_soname(_findLib_gcc(name)) + res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y))) + return res[-1] + + else: + + def _findLib_ldconfig(name): + # XXX assuming GLIBC's ldconfig (with option -p) + expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) + res = re.search(expr, + os.popen('/sbin/ldconfig -p 2>/dev/null').read()) + if not res: + # Hm, this works only for libs needed by the python executable. + cmd = 'ldd %s 2>/dev/null' % sys.executable + res = re.search(expr, os.popen(cmd).read()) + if not res: + return None + return res.group(0) + + def find_library(name): + return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name)) ################################################################ # test code Modified: python/branches/p3yk/Lib/ctypes/wintypes.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/wintypes.py (original) +++ python/branches/p3yk/Lib/ctypes/wintypes.py Mon Jan 15 16:49:28 2007 @@ -34,8 +34,14 @@ LPCWSTR = LPWSTR = c_wchar_p LPCSTR = LPSTR = c_char_p -WPARAM = c_uint -LPARAM = c_long +# WPARAM is defined as UINT_PTR (unsigned type) +# LPARAM is defined as LONG_PTR (signed type) +if sizeof(c_long) == sizeof(c_void_p): + WPARAM = c_ulong + LPARAM = c_long +elif sizeof(c_longlong) == sizeof(c_void_p): + WPARAM = c_ulonglong + LPARAM = c_longlong ATOM = WORD LANGID = WORD @@ -48,7 +54,7 @@ ################################################################ # HANDLE types -HANDLE = c_ulong # in the header files: void * +HANDLE = c_void_p # in the header files: void * HACCEL = HANDLE HBITMAP = HANDLE Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/EditorWindow.py Mon Jan 15 16:49:28 2007 @@ -819,7 +819,7 @@ def close(self): reply = self.maybesave() - if reply != "cancel": + if str(reply) != "cancel": self._close() return reply Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Mon Jan 15 16:49:28 2007 @@ -41,8 +41,8 @@ __author__ = "Vinay Sajip " __status__ = "production" -__version__ = "0.5.0.0" -__date__ = "08 January 2007" +__version__ = "0.5.0.1" +__date__ = "09 January 2007" #--------------------------------------------------------------------------- # Miscellaneous module data @@ -764,17 +764,15 @@ """ Open the specified file and use it as the stream for logging. """ - if codecs is None: - encoding = None - if encoding is None: - stream = open(filename, mode) - else: - stream = codecs.open(filename, mode, encoding) - StreamHandler.__init__(self, stream) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes + if codecs is None: + encoding = None self.baseFilename = os.path.abspath(filename) self.mode = mode + self.encoding = encoding + stream = self._open() + StreamHandler.__init__(self, stream) def close(self): """ @@ -784,6 +782,17 @@ self.stream.close() StreamHandler.close(self) + def _open(self): + """ + Open the current base file with the (original) mode and encoding. + Return the resulting stream. + """ + if self.encoding is None: + stream = open(self.baseFilename, self.mode) + else: + stream = codecs.open(self.baseFilename, self.mode, self.encoding) + return stream + #--------------------------------------------------------------------------- # Manager classes and functions #--------------------------------------------------------------------------- Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Mon Jan 15 16:49:28 2007 @@ -32,6 +32,7 @@ import cPickle as pickle except ImportError: import pickle +from stat import ST_DEV, ST_INO try: import codecs @@ -286,6 +287,54 @@ self.stream = open(self.baseFilename, 'w') self.rolloverAt = self.rolloverAt + self.interval +class WatchedFileHandler(logging.FileHandler): + """ + A handler for logging to a file, which watches the file + to see if it has changed while in use. This can happen because of + usage of programs such as newsyslog and logrotate which perform + log file rotation. This handler, intended for use under Unix, + watches the file to see if it has changed since the last emit. + (A file has changed if its device or inode have changed.) + If it has changed, the old file stream is closed, and the file + opened to get a new stream. + + This handler is not appropriate for use under Windows, because + under Windows open files cannot be moved or renamed - logging + opens the files with exclusive locks - and so there is no need + for such a handler. Furthermore, ST_INO is not supported under + Windows; stat always returns zero for this value. + + This handler is based on a suggestion and patch by Chad J. + Schroeder. + """ + def __init__(self, filename, mode='a', encoding=None): + logging.FileHandler.__init__(self, filename, mode, encoding) + stat = os.stat(self.baseFilename) + self.dev, self.ino = stat[ST_DEV], stat[ST_INO] + + def emit(self, record): + """ + Emit a record. + + First check if the underlying file has changed, and if it + has, close the old stream and reopen the file to get the + current stream. + """ + if not os.path.exists(self.baseFilename): + stat = None + changed = 1 + else: + stat = os.stat(self.baseFilename) + changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino) + if changed: + self.stream.flush() + self.stream.close() + self.stream = self._open() + if stat is None: + stat = os.stat(self.baseFilename) + self.dev, self.ino = stat[ST_DEV], stat[ST_INO] + logging.FileHandler.emit(self, record) + class SocketHandler(logging.Handler): """ A handler class which writes logging records, in pickle format, to Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Mon Jan 15 16:49:28 2007 @@ -28,12 +28,15 @@ # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support), -# Colin Kong, Trent Mick, Guido van Rossum +# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter # # History: # # # +# 1.0.6 - added linux_distribution() +# 1.0.5 - fixed Java support to allow running the module on Jython +# 1.0.4 - added IronPython support # 1.0.3 - added normalization of Windows system name # 1.0.2 - added more Windows support # 1.0.1 - reformatted to make doc.py happy @@ -88,7 +91,7 @@ __copyright__ = """ Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal at lemburg.com - Copyright (c) 2000-2003, eGenix.com Software GmbH; mailto:info at egenix.com + Copyright (c) 2000-2007, eGenix.com Software GmbH; mailto:info at egenix.com Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee or royalty is hereby granted, @@ -107,7 +110,7 @@ """ -__version__ = '1.0.4' +__version__ = '1.0.6' import sys,string,os,re @@ -136,6 +139,11 @@ The file is read and scanned in chunks of chunksize bytes. """ + if hasattr(os.path, 'realpath'): + # Python 2.2 introduced os.path.realpath(); it is used + # here to work around problems with Cygwin not being + # able to open symlinks for reading + executable = os.path.realpath(executable) f = open(executable,'rb') binary = f.read(chunksize) pos = 0 @@ -218,14 +226,69 @@ return distname,version,id _release_filename = re.compile(r'(\w+)[-_](release|version)') -_release_version = re.compile(r'([\d.]+)[^(]*(?:\((.+)\))?') +_lsb_release_version = re.compile(r'(.+)' + ' release ' + '([\d.]+)' + '[^(]*(?:\((.+)\))?') +_release_version = re.compile(r'([^0-9]+)' + '(?: release )?' + '([\d.]+)' + '[^(]*(?:\((.+)\))?') + +# See also http://www.novell.com/coolsolutions/feature/11251.html +# and http://linuxmafia.com/faq/Admin/release-files.html +# and http://data.linux-ntfs.org/rpm/whichrpm +# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html + +_supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos', + 'mandrake', 'rocks', 'slackware', 'yellowdog', + 'gentoo', 'UnitedLinux') + +def _parse_release_file(firstline): + + # Parse the first line + m = _lsb_release_version.match(firstline) + if m is not None: + # LSB format: "distro release x.x (codename)" + return tuple(m.groups()) + + # Pre-LSB format: "distro x.x (codename)" + m = _release_version.match(firstline) + if m is not None: + return tuple(m.groups()) + + # Unkown format... take the first two words + l = string.split(string.strip(firstline)) + if l: + version = l[0] + if len(l) > 1: + id = l[1] + else: + id = '' + return '', version, id -# Note:In supported_dists below we need 'fedora' before 'redhat' as in -# Fedora redhat-release is a link to fedora-release. +def _test_parse_release_file(): + + for input, output in ( + # Examples of release file contents: + ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64')) + ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64')) + ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586')) + ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux')) + ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche')) + ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike')) + ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant')) + ('CentOS release 4', ('CentOS', '4', None)) + ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia')) + ): + parsed = _parse_release_file(input) + if parsed != output: + print (input, parsed) -def dist(distname='',version='',id='', +def linux_distribution(distname='', version='', id='', - supported_dists=('SuSE', 'debian', 'fedora', 'redhat', 'mandrake')): + supported_dists=_supported_dists, + full_distribution_name=1): """ Tries to determine the name of the Linux OS distribution name. @@ -233,6 +296,15 @@ /etc and then reverts to _dist_try_harder() in case no suitable files are found. + supported_dists may be given to define the set of Linux + distributions to look for. It defaults to a list of currently + supported Linux distributions identified by their release file + name. + + If full_distribution_name is true (default), the full + distribution read from the OS is returned. Otherwise the short + name taken from supported_dists is used. + Returns a tuple (distname,version,id) which default to the args given as parameters. @@ -242,33 +314,50 @@ except os.error: # Probably not a Unix system return distname,version,id + etc.sort() for file in etc: m = _release_filename.match(file) - if m: + if m is not None: _distname,dummy = m.groups() if _distname in supported_dists: distname = _distname break else: return _dist_try_harder(distname,version,id) - f = open('/etc/'+file,'r') + + # Read the first line + f = open('/etc/'+file, 'r') firstline = f.readline() f.close() - m = _release_version.search(firstline) - if m: - _version,_id = m.groups() - if _version: - version = _version - if _id: - id = _id - else: - # Unkown format... take the first two words - l = string.split(string.strip(firstline)) - if l: - version = l[0] - if len(l) > 1: - id = l[1] - return distname,version,id + _distname, _version, _id = _parse_release_file(firstline) + + if _distname and full_distribution_name: + distname = _distname + if _version: + version = _version + if _id: + id = _id + return distname, version, id + +# To maintain backwards compatibility: + +def dist(distname='',version='',id='', + + supported_dists=_supported_dists): + + """ Tries to determine the name of the Linux OS distribution name. + + The function first looks for a distribution release file in + /etc and then reverts to _dist_try_harder() in case no + suitable files are found. + + Returns a tuple (distname,version,id) which default to the + args given as parameters. + + """ + return linux_distribution(distname, version, id, + supported_dists=supported_dists, + full_distribution_name=0) class _popen: @@ -357,7 +446,7 @@ else: return popen(cmd,mode,bufsize) -def _norm_version(version,build=''): +def _norm_version(version, build=''): """ Normalize the version and build strings and return a single version string using the format major.minor.build (or patchlevel). @@ -378,7 +467,7 @@ '.*' 'Version ([\d.]+))') -def _syscmd_ver(system='',release='',version='', +def _syscmd_ver(system='', release='', version='', supported_platforms=('win32','win16','dos','os2')): @@ -418,7 +507,7 @@ # Parse the output info = string.strip(info) m = _ver_output.match(info) - if m: + if m is not None: system,release,version = m.groups() # Strip trailing dots from version and release if release[-1] == '.': @@ -615,8 +704,11 @@ from java.lang import System try: - return System.getProperty(name) - except: + value = System.getProperty(name) + if value is None: + return default + return value + except AttributeError: return default def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')): @@ -637,20 +729,20 @@ except ImportError: return release,vendor,vminfo,osinfo - vendor = _java_getprop('java.vendor',vendor) - release = _java_getprop('java.version',release) - vm_name,vm_release,vm_vendor = vminfo - vm_name = _java_getprop('java.vm.name',vm_name) - vm_vendor = _java_getprop('java.vm.vendor',vm_vendor) - vm_release = _java_getprop('java.vm.version',vm_release) - vminfo = vm_name,vm_release,vm_vendor - os_name,os_version,os_arch = osinfo - os_arch = _java_getprop('java.os.arch',os_arch) - os_name = _java_getprop('java.os.name',os_name) - os_version = _java_getprop('java.os.version',os_version) - osinfo = os_name,os_version,os_arch + vendor = _java_getprop('java.vendor', vendor) + release = _java_getprop('java.version', release) + vm_name, vm_release, vm_vendor = vminfo + vm_name = _java_getprop('java.vm.name', vm_name) + vm_vendor = _java_getprop('java.vm.vendor', vm_vendor) + vm_release = _java_getprop('java.vm.version', vm_release) + vminfo = vm_name, vm_release, vm_vendor + os_name, os_version, os_arch = osinfo + os_arch = _java_getprop('java.os.arch', os_arch) + os_name = _java_getprop('java.os.name', os_name) + os_version = _java_getprop('java.os.version', os_version) + osinfo = os_name, os_version, os_arch - return release,vendor,vminfo,osinfo + return release, vendor, vminfo, osinfo ### System name aliasing @@ -716,7 +808,7 @@ # Format the platform string platform = string.join( map(string.strip, - filter(len,args)), + filter(len, args)), '-') # Cleanup some possible filename obstacles... @@ -871,7 +963,10 @@ bits = str(size*8) + 'bit' # Get data from the 'file' system command - output = _syscmd_file(executable,'') + if executable: + output = _syscmd_file(executable, '') + else: + output = '' if not output and \ executable == sys.executable: @@ -960,6 +1055,10 @@ release,version,csd,ptype = win32_ver() if release and version: use_syscmd_ver = 0 + # XXX Should try to parse the PROCESSOR_* environment variables + # available on Win XP and later; see + # http://support.microsoft.com/kb/888731 and + # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM # Try the 'ver' system command available on some # platforms @@ -1092,36 +1191,136 @@ ### Various APIs for extracting information from sys.version -_sys_version_parser = re.compile(r'([\w.+]+)\s*' - '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*' - '\[([^\]]+)\]?') -_sys_version_cache = None +_sys_version_parser = re.compile( + r'([\w.+]+)\s*' + '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*' + '\[([^\]]+)\]?') + +_jython_sys_version_parser = re.compile( + r'([\d\.]+)') + +_ironpython_sys_version_parser = re.compile( + r'IronPython\s*' + '([\d\.]+)' + '(?: \(([\d\.]+)\))?' + ' on (.NET [\d\.]+)') -def _sys_version(): +_sys_version_cache = {} + +def _sys_version(sys_version=None): """ Returns a parsed version of Python's sys.version as tuple - (version, buildno, builddate, compiler) referring to the Python - version, build number, build date/time as string and the compiler - identification string. + (name, version, branch, revision, buildno, builddate, compiler) + referring to the Python implementation name, version, branch, + revision, build number, build date/time as string and the compiler + identification string. Note that unlike the Python sys.version, the returned value for the Python version will always include the patchlevel (it defaults to '.0'). + The function returns empty strings for tuple entries that + cannot be determined. + + sys_version may be given to parse an alternative version + string, e.g. if the version was read from a different Python + interpreter. + """ - global _sys_version_cache + # Get the Python version + if sys_version is None: + sys_version = sys.version - if _sys_version_cache is not None: - return _sys_version_cache - version, buildno, builddate, buildtime, compiler = \ - _sys_version_parser.match(sys.version).groups() - builddate = builddate + ' ' + buildtime + # Try the cache first + result = _sys_version_cache.get(sys_version, None) + if result is not None: + return result + + # Parse it + if sys_version[:10] == 'IronPython': + # IronPython + name = 'IronPython' + match = _ironpython_sys_version_parser.match(sys_version) + if match is None: + raise ValueError( + 'failed to parse IronPython sys.version: %s' % + repr(sys_version)) + version, alt_version, compiler = match.groups() + branch = '' + revision = '' + buildno = '' + builddate = '' + + elif sys.platform[:4] == 'java': + # Jython + name = 'Jython' + match = _jython_sys_version_parser.match(sys_version) + if match is None: + raise ValueError( + 'failed to parse Jython sys.version: %s' % + repr(sys_version)) + version, = match.groups() + branch = '' + revision = '' + compiler = sys.platform + buildno = '' + builddate = '' + + else: + # CPython + match = _sys_version_parser.match(sys_version) + if match is None: + raise ValueError( + 'failed to parse CPython sys.version: %s' % + repr(sys_version)) + version, buildno, builddate, buildtime, compiler = \ + match.groups() + if hasattr(sys, 'subversion'): + # sys.subversion was added in Python 2.5 + name, branch, revision = sys.subversion + else: + name = 'CPython' + branch = '' + revision = '' + builddate = builddate + ' ' + buildtime + + # Add the patchlevel version if missing l = string.split(version, '.') if len(l) == 2: l.append('0') version = string.join(l, '.') - _sys_version_cache = (version, buildno, builddate, compiler) - return _sys_version_cache + + # Build and cache the result + result = (name, version, branch, revision, buildno, builddate, compiler) + _sys_version_cache[sys_version] = result + return result + +def _test_sys_version(): + + _sys_version_cache.clear() + for input, output in ( + ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]', + ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')), + ('IronPython 1.0.60816 on .NET 2.0.50727.42', + ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')), + ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42', + ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')), + ): + parsed = _sys_version(input) + if parsed != output: + print (input, parsed) + +def python_implementation(): + + """ Returns a string identifying the Python implementation. + + Currently, the following implementations are identified: + 'CPython' (C implementation of Python), + 'IronPython' (.NET implementation of Python), + 'Jython' (Java implementation of Python). + + """ + return _sys_version()[0] def python_version(): @@ -1131,7 +1330,9 @@ will always include the patchlevel (it defaults to 0). """ - return _sys_version()[0] + if hasattr(sys, 'version_info'): + return '%i.%i.%i' % sys.version_info[:3] + return _sys_version()[1] def python_version_tuple(): @@ -1142,7 +1343,36 @@ will always include the patchlevel (it defaults to 0). """ - return string.split(_sys_version()[0], '.') + if hasattr(sys, 'version_info'): + return sys.version_info[:3] + return tuple(string.split(_sys_version()[1], '.')) + +def python_branch(): + + """ Returns a string identifying the Python implementation + branch. + + For CPython this is the Subversion branch from which the + Python binary was built. + + If not available, an empty string is returned. + + """ + + return _sys_version()[2] + +def python_revision(): + + """ Returns a string identifying the Python implementation + revision. + + For CPython this is the Subversion revision from which the + Python binary was built. + + If not available, an empty string is returned. + + """ + return _sys_version()[3] def python_build(): @@ -1150,7 +1380,7 @@ build number and date as strings. """ - return _sys_version()[1:3] + return _sys_version()[4:6] def python_compiler(): @@ -1158,7 +1388,7 @@ Python. """ - return _sys_version()[3] + return _sys_version()[6] ### The Opus Magnum of platform strings :-) @@ -1219,7 +1449,7 @@ elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() - if terse: + if terse or not os_name: platform = _platform(system,release,version) else: platform = _platform(system,release,version, Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Mon Jan 15 16:49:28 2007 @@ -1448,6 +1448,9 @@ text = TextDoc() html = HTMLDoc() +class _OldStyleClass: pass +_OLD_INSTANCE_TYPE = type(_OldStyleClass()) + def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): @@ -1468,12 +1471,16 @@ desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ - if not (inspect.ismodule(object) or - inspect.isclass(object) or - inspect.isroutine(object) or - inspect.isgetsetdescriptor(object) or - inspect.ismemberdescriptor(object) or - isinstance(object, property)): + if type(object) is _OLD_INSTANCE_TYPE: + # If the passed object is an instance of an old-style class, + # document its available methods instead of its value. + object = object.__class__ + elif not (inspect.ismodule(object) or + inspect.isclass(object) or + inspect.isroutine(object) or + inspect.isgetsetdescriptor(object) or + inspect.ismemberdescriptor(object) or + isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) Modified: python/branches/p3yk/Lib/sqlite3/dbapi2.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/dbapi2.py (original) +++ python/branches/p3yk/Lib/sqlite3/dbapi2.py Mon Jan 15 16:49:28 2007 @@ -68,7 +68,7 @@ timepart_full = timepart.split(".") hours, minutes, seconds = map(int, timepart_full[0].split(":")) if len(timepart_full) == 2: - microseconds = int(float("0." + timepart_full[1]) * 1000000) + microseconds = int(timepart_full[1]) else: microseconds = 0 Modified: python/branches/p3yk/Lib/sqlite3/test/factory.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/factory.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/factory.py Mon Jan 15 16:49:28 2007 @@ -91,7 +91,7 @@ list), "row is not instance of list") - def CheckSqliteRow(self): + def CheckSqliteRowIndex(self): self.con.row_factory = sqlite.Row row = self.con.execute("select 1 as a, 2 as b").fetchone() self.failUnless(isinstance(row, @@ -110,6 +110,27 @@ self.failUnless(col1 == 1, "by index: wrong result for column 0") self.failUnless(col2 == 2, "by index: wrong result for column 1") + def CheckSqliteRowIter(self): + """Checks if the row object is iterable""" + self.con.row_factory = sqlite.Row + row = self.con.execute("select 1 as a, 2 as b").fetchone() + for col in row: + pass + + def CheckSqliteRowAsTuple(self): + """Checks if the row object can be converted to a tuple""" + self.con.row_factory = sqlite.Row + row = self.con.execute("select 1 as a, 2 as b").fetchone() + t = tuple(row) + + def CheckSqliteRowAsDict(self): + """Checks if the row object can be correctly converted to a dictionary""" + self.con.row_factory = sqlite.Row + row = self.con.execute("select 1 as a, 2 as b").fetchone() + d = dict(row) + self.failUnlessEqual(d["a"], row["a"]) + self.failUnlessEqual(d["b"], row["b"]) + def tearDown(self): self.con.close() Modified: python/branches/p3yk/Lib/sqlite3/test/regression.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/regression.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/regression.py Mon Jan 15 16:49:28 2007 @@ -69,6 +69,16 @@ cur.execute('select 1 as "foo baz"') self.failUnlessEqual(cur.description[0][0], "foo baz") + def CheckStatementAvailable(self): + # pysqlite up to 2.3.2 crashed on this, because the active statement handle was not checked + # before trying to fetch data from it. close() destroys the active statement ... + con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES) + cur = con.cursor() + cur.execute("select 4 union select 5") + cur.close() + cur.fetchone() + cur.fetchone() + def suite(): regression_suite = unittest.makeSuite(RegressionTests, "Check") return unittest.TestSuite((regression_suite,)) Modified: python/branches/p3yk/Lib/sqlite3/test/types.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/types.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/types.py Mon Jan 15 16:49:28 2007 @@ -112,6 +112,7 @@ # and implement two custom ones sqlite.converters["BOOL"] = lambda x: bool(int(x)) sqlite.converters["FOO"] = DeclTypesTests.Foo + sqlite.converters["WRONG"] = lambda x: "WRONG" def tearDown(self): del sqlite.converters["FLOAT"] @@ -123,7 +124,7 @@ def CheckString(self): # default self.cur.execute("insert into test(s) values (?)", ("foo",)) - self.cur.execute("select s from test") + self.cur.execute('select s as "s [WRONG]" from test') row = self.cur.fetchone() self.failUnlessEqual(row[0], "foo") @@ -210,26 +211,32 @@ class ColNamesTests(unittest.TestCase): def setUp(self): - self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES|sqlite.PARSE_DECLTYPES) + self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES) self.cur = self.con.cursor() self.cur.execute("create table test(x foo)") sqlite.converters["FOO"] = lambda x: "[%s]" % x sqlite.converters["BAR"] = lambda x: "<%s>" % x sqlite.converters["EXC"] = lambda x: 5/0 + sqlite.converters["B1B1"] = lambda x: "MARKER" def tearDown(self): del sqlite.converters["FOO"] del sqlite.converters["BAR"] del sqlite.converters["EXC"] + del sqlite.converters["B1B1"] self.cur.close() self.con.close() - def CheckDeclType(self): + def CheckDeclTypeNotUsed(self): + """ + Assures that the declared type is not used when PARSE_DECLTYPES + is not set. + """ self.cur.execute("insert into test(x) values (?)", ("xxx",)) self.cur.execute("select x from test") val = self.cur.fetchone()[0] - self.failUnlessEqual(val, "[xxx]") + self.failUnlessEqual(val, "xxx") def CheckNone(self): self.cur.execute("insert into test(x) values (?)", (None,)) @@ -247,6 +254,11 @@ # whitespace should be stripped. self.failUnlessEqual(self.cur.description[0][0], "x") + def CheckCaseInConverterName(self): + self.cur.execute("""select 'other' as "x [b1b1]\"""") + val = self.cur.fetchone()[0] + self.failUnlessEqual(val, "MARKER") + def CheckCursorDescriptionNoRow(self): """ cursor.description should at least provide the column name(s), even if @@ -340,6 +352,13 @@ ts2 = self.cur.fetchone()[0] self.failUnlessEqual(ts, ts2) + def CheckDateTimeSubSecondsFloatingPoint(self): + ts = sqlite.Timestamp(2004, 2, 14, 7, 15, 0, 510241) + self.cur.execute("insert into test(ts) values (?)", (ts,)) + self.cur.execute("select ts from test") + ts2 = self.cur.fetchone()[0] + self.failUnlessEqual(ts, ts2) + def suite(): sqlite_type_suite = unittest.makeSuite(SqliteTypeTests, "Check") decltypes_type_suite = unittest.makeSuite(DeclTypesTests, "Check") Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Mon Jan 15 16:49:28 2007 @@ -500,7 +500,7 @@ if result: result.append(' ') - needquote = (" " in arg) or ("\t" in arg) + needquote = (" " in arg) or ("\t" in arg) or arg == "" if needquote: result.append('"') Modified: python/branches/p3yk/Lib/test/test___all__.py ============================================================================== --- python/branches/p3yk/Lib/test/test___all__.py (original) +++ python/branches/p3yk/Lib/test/test___all__.py Mon Jan 15 16:49:28 2007 @@ -132,7 +132,6 @@ self.check_all("rlcompleter") self.check_all("robotparser") self.check_all("sched") - self.check_all("sets") self.check_all("sgmllib") self.check_all("shelve") self.check_all("shlex") Modified: python/branches/p3yk/Lib/test/test_optparse.py ============================================================================== --- python/branches/p3yk/Lib/test/test_optparse.py (original) +++ python/branches/p3yk/Lib/test/test_optparse.py Mon Jan 15 16:49:28 2007 @@ -1500,8 +1500,16 @@ self.assertHelpEquals(_expected_help_long_opts_first) def test_help_title_formatter(self): - self.parser.formatter = TitledHelpFormatter() - self.assertHelpEquals(_expected_help_title_formatter) + save = os.environ.get("COLUMNS") + try: + os.environ["COLUMNS"] = "80" + self.parser.formatter = TitledHelpFormatter() + self.assertHelpEquals(_expected_help_title_formatter) + finally: + if save is not None: + os.environ["COLUMNS"] = save + else: + del os.environ["COLUMNS"] def test_wrap_columns(self): # Ensure that wrapping respects $COLUMNS environment variable. Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Mon Jan 15 16:49:28 2007 @@ -476,6 +476,16 @@ class TestSetSubclass(TestSet): thetype = SetSubclass +class SetSubclassWithKeywordArgs(set): + def __init__(self, iterable=[], newarg=None): + set.__init__(self, iterable) + +class TestSetSubclassWithKeywordArgs(TestSet): + + def test_keywords_in_subclass(self): + 'SF bug #1486663 -- this used to erroneously raise a TypeError' + SetSubclassWithKeywordArgs(newarg=1) + class TestFrozenSet(TestJointOps): thetype = frozenset @@ -1454,6 +1464,7 @@ test_classes = ( TestSet, TestSetSubclass, + TestSetSubclassWithKeywordArgs, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, Modified: python/branches/p3yk/Lib/test/test_subprocess.py ============================================================================== --- python/branches/p3yk/Lib/test/test_subprocess.py (original) +++ python/branches/p3yk/Lib/test/test_subprocess.py Mon Jan 15 16:49:28 2007 @@ -430,6 +430,8 @@ '"a\\\\b c" d e') self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']), '"a\\\\b\\ c" d e') + self.assertEqual(subprocess.list2cmdline(['ab', '']), + 'ab ""') def test_poll(self): Modified: python/branches/p3yk/Makefile.pre.in ============================================================================== --- python/branches/p3yk/Makefile.pre.in (original) +++ python/branches/p3yk/Makefile.pre.in Mon Jan 15 16:49:28 2007 @@ -484,6 +484,8 @@ Parser/tokenizer_pgen.o: $(srcdir)/Parser/tokenizer.c +Parser/pgenmain.o: $(srcdir)/Include/parsetok.h + $(AST_H): $(AST_ASDL) $(ASDLGEN_FILES) $(ASDLGEN) -h $(AST_H_DIR) $(AST_ASDL) @@ -537,6 +539,7 @@ Include/moduleobject.h \ Include/object.h \ Include/objimpl.h \ + Include/parsetok.h \ Include/patchlevel.h \ Include/pyarena.h \ Include/pydebug.h \ Modified: python/branches/p3yk/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/_ctypes.c (original) +++ python/branches/p3yk/Modules/_ctypes/_ctypes.c Mon Jan 15 16:49:28 2007 @@ -4749,7 +4749,7 @@ #endif PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL)); PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI)); - PyModule_AddStringConstant(m, "__version__", "1.0.1"); + PyModule_AddStringConstant(m, "__version__", "1.1.0"); PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); Modified: python/branches/p3yk/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/branches/p3yk/Modules/_ctypes/libffi_msvc/ffi.c (original) +++ python/branches/p3yk/Modules/_ctypes/libffi_msvc/ffi.c Mon Jan 15 16:49:28 2007 @@ -224,7 +224,8 @@ #else case FFI_SYSV: /*@-usedef@*/ - return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes, + /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ + return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, cif->flags, ecif.rvalue, fn); /*@=usedef@*/ break; Modified: python/branches/p3yk/Modules/_sqlite/cache.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/cache.c (original) +++ python/branches/p3yk/Modules/_sqlite/cache.c Mon Jan 15 16:49:28 2007 @@ -25,11 +25,11 @@ #include /* only used internally */ -Node* new_node(PyObject* key, PyObject* data) +pysqlite_Node* pysqlite_new_node(PyObject* key, PyObject* data) { - Node* node; + pysqlite_Node* node; - node = (Node*) (NodeType.tp_alloc(&NodeType, 0)); + node = (pysqlite_Node*) (pysqlite_NodeType.tp_alloc(&pysqlite_NodeType, 0)); if (!node) { return NULL; } @@ -46,7 +46,7 @@ return node; } -void node_dealloc(Node* self) +void pysqlite_node_dealloc(pysqlite_Node* self) { Py_DECREF(self->key); Py_DECREF(self->data); @@ -54,7 +54,7 @@ self->ob_type->tp_free((PyObject*)self); } -int cache_init(Cache* self, PyObject* args, PyObject* kwargs) +int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs) { PyObject* factory; int size = 10; @@ -86,10 +86,10 @@ return 0; } -void cache_dealloc(Cache* self) +void pysqlite_cache_dealloc(pysqlite_Cache* self) { - Node* node; - Node* delete_node; + pysqlite_Node* node; + pysqlite_Node* delete_node; if (!self->factory) { /* constructor failed, just get out of here */ @@ -112,14 +112,14 @@ self->ob_type->tp_free((PyObject*)self); } -PyObject* cache_get(Cache* self, PyObject* args) +PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args) { PyObject* key = args; - Node* node; - Node* ptr; + pysqlite_Node* node; + pysqlite_Node* ptr; PyObject* data; - node = (Node*)PyDict_GetItem(self->mapping, key); + node = (pysqlite_Node*)PyDict_GetItem(self->mapping, key); if (node) { /* an entry for this key already exists in the cache */ @@ -186,7 +186,7 @@ return NULL; } - node = new_node(key, data); + node = pysqlite_new_node(key, data); if (!node) { return NULL; } @@ -211,9 +211,9 @@ return node->data; } -PyObject* cache_display(Cache* self, PyObject* args) +PyObject* pysqlite_cache_display(pysqlite_Cache* self, PyObject* args) { - Node* ptr; + pysqlite_Node* ptr; PyObject* prevkey; PyObject* nextkey; PyObject* fmt_args; @@ -265,20 +265,20 @@ } static PyMethodDef cache_methods[] = { - {"get", (PyCFunction)cache_get, METH_O, + {"get", (PyCFunction)pysqlite_cache_get, METH_O, PyDoc_STR("Gets an entry from the cache or calls the factory function to produce one.")}, - {"display", (PyCFunction)cache_display, METH_NOARGS, + {"display", (PyCFunction)pysqlite_cache_display, METH_NOARGS, PyDoc_STR("For debugging only.")}, {NULL, NULL} }; -PyTypeObject NodeType = { +PyTypeObject pysqlite_NodeType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME "Node", /* tp_name */ - sizeof(Node), /* tp_basicsize */ + sizeof(pysqlite_Node), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)node_dealloc, /* tp_dealloc */ + (destructor)pysqlite_node_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -315,13 +315,13 @@ 0 /* tp_free */ }; -PyTypeObject CacheType = { +PyTypeObject pysqlite_CacheType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".Cache", /* tp_name */ - sizeof(Cache), /* tp_basicsize */ + sizeof(pysqlite_Cache), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)cache_dealloc, /* tp_dealloc */ + (destructor)pysqlite_cache_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -352,24 +352,24 @@ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)cache_init, /* tp_init */ + (initproc)pysqlite_cache_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0 /* tp_free */ }; -extern int cache_setup_types(void) +extern int pysqlite_cache_setup_types(void) { int rc; - NodeType.tp_new = PyType_GenericNew; - CacheType.tp_new = PyType_GenericNew; + pysqlite_NodeType.tp_new = PyType_GenericNew; + pysqlite_CacheType.tp_new = PyType_GenericNew; - rc = PyType_Ready(&NodeType); + rc = PyType_Ready(&pysqlite_NodeType); if (rc < 0) { return rc; } - rc = PyType_Ready(&CacheType); + rc = PyType_Ready(&pysqlite_CacheType); return rc; } Modified: python/branches/p3yk/Modules/_sqlite/cache.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/cache.h (original) +++ python/branches/p3yk/Modules/_sqlite/cache.h Mon Jan 15 16:49:28 2007 @@ -29,15 +29,15 @@ * dictionary. The list items are of type 'Node' and the dictionary has the * nodes as values. */ -typedef struct _Node +typedef struct _pysqlite_Node { PyObject_HEAD PyObject* key; PyObject* data; long count; - struct _Node* prev; - struct _Node* next; -} Node; + struct _pysqlite_Node* prev; + struct _pysqlite_Node* next; +} pysqlite_Node; typedef struct { @@ -50,24 +50,24 @@ /* the factory callable */ PyObject* factory; - Node* first; - Node* last; + pysqlite_Node* first; + pysqlite_Node* last; /* if set, decrement the factory function when the Cache is deallocated. * this is almost always desirable, but not in the pysqlite context */ int decref_factory; -} Cache; +} pysqlite_Cache; -extern PyTypeObject NodeType; -extern PyTypeObject CacheType; +extern PyTypeObject pysqlite_NodeType; +extern PyTypeObject pysqlite_CacheType; -int node_init(Node* self, PyObject* args, PyObject* kwargs); -void node_dealloc(Node* self); +int pysqlite_node_init(pysqlite_Node* self, PyObject* args, PyObject* kwargs); +void pysqlite_node_dealloc(pysqlite_Node* self); -int cache_init(Cache* self, PyObject* args, PyObject* kwargs); -void cache_dealloc(Cache* self); -PyObject* cache_get(Cache* self, PyObject* args); +int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs); +void pysqlite_cache_dealloc(pysqlite_Cache* self); +PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args); -int cache_setup_types(void); +int pysqlite_cache_setup_types(void); #endif Modified: python/branches/p3yk/Modules/_sqlite/connection.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/connection.c (original) +++ python/branches/p3yk/Modules/_sqlite/connection.c Mon Jan 15 16:49:28 2007 @@ -32,7 +32,7 @@ #include "pythread.h" -static int connection_set_isolation_level(Connection* self, PyObject* isolation_level); +static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level); void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len) @@ -43,11 +43,11 @@ #if SQLITE_VERSION_NUMBER >= 3003003 sqlite3_result_error(ctx, errmsg, len); #else - PyErr_SetString(OperationalError, errmsg); + PyErr_SetString(pysqlite_OperationalError, errmsg); #endif } -int connection_init(Connection* self, PyObject* args, PyObject* kwargs) +int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL}; @@ -82,7 +82,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _seterror(self->db); + _pysqlite_seterror(self->db); return -1; } @@ -95,10 +95,10 @@ Py_INCREF(isolation_level); } self->isolation_level = NULL; - connection_set_isolation_level(self, isolation_level); + pysqlite_connection_set_isolation_level(self, isolation_level); Py_DECREF(isolation_level); - self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "Oi", self, cached_statements); + self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements); if (PyErr_Occurred()) { return -1; } @@ -135,41 +135,41 @@ return -1; } - self->Warning = Warning; - self->Error = Error; - self->InterfaceError = InterfaceError; - self->DatabaseError = DatabaseError; - self->DataError = DataError; - self->OperationalError = OperationalError; - self->IntegrityError = IntegrityError; - self->InternalError = InternalError; - self->ProgrammingError = ProgrammingError; - self->NotSupportedError = NotSupportedError; + self->Warning = pysqlite_Warning; + self->Error = pysqlite_Error; + self->InterfaceError = pysqlite_InterfaceError; + self->DatabaseError = pysqlite_DatabaseError; + self->DataError = pysqlite_DataError; + self->OperationalError = pysqlite_OperationalError; + self->IntegrityError = pysqlite_IntegrityError; + self->InternalError = pysqlite_InternalError; + self->ProgrammingError = pysqlite_ProgrammingError; + self->NotSupportedError = pysqlite_NotSupportedError; return 0; } /* Empty the entire statement cache of this connection */ -void flush_statement_cache(Connection* self) +void pysqlite_flush_statement_cache(pysqlite_Connection* self) { - Node* node; - Statement* statement; + pysqlite_Node* node; + pysqlite_Statement* statement; node = self->statement_cache->first; while (node) { - statement = (Statement*)(node->data); - (void)statement_finalize(statement); + statement = (pysqlite_Statement*)(node->data); + (void)pysqlite_statement_finalize(statement); node = node->next; } Py_DECREF(self->statement_cache); - self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "O", self); + self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self); Py_DECREF(self); self->statement_cache->decref_factory = 0; } -void reset_all_statements(Connection* self) +void pysqlite_reset_all_statements(pysqlite_Connection* self) { int i; PyObject* weakref; @@ -179,12 +179,12 @@ weakref = PyList_GetItem(self->statements, i); statement = PyWeakref_GetObject(weakref); if (statement != Py_None) { - (void)statement_reset((Statement*)statement); + (void)pysqlite_statement_reset((pysqlite_Statement*)statement); } } } -void connection_dealloc(Connection* self) +void pysqlite_connection_dealloc(pysqlite_Connection* self) { Py_XDECREF(self->statement_cache); @@ -208,7 +208,7 @@ self->ob_type->tp_free((PyObject*)self); } -PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { static char *kwlist[] = {"factory", NULL, NULL}; PyObject* factory = NULL; @@ -220,34 +220,34 @@ return NULL; } - if (!check_thread(self) || !check_connection(self)) { + if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) { return NULL; } if (factory == NULL) { - factory = (PyObject*)&CursorType; + factory = (PyObject*)&pysqlite_CursorType; } cursor = PyObject_CallFunction(factory, "O", self); if (cursor && self->row_factory != Py_None) { - Py_XDECREF(((Cursor*)cursor)->row_factory); + Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory); Py_INCREF(self->row_factory); - ((Cursor*)cursor)->row_factory = self->row_factory; + ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory; } return cursor; } -PyObject* connection_close(Connection* self, PyObject* args) +PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args) { int rc; - if (!check_thread(self)) { + if (!pysqlite_check_thread(self)) { return NULL; } - flush_statement_cache(self); + pysqlite_flush_statement_cache(self); if (self->db) { Py_BEGIN_ALLOW_THREADS @@ -255,7 +255,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _seterror(self->db); + _pysqlite_seterror(self->db); return NULL; } else { self->db = NULL; @@ -271,17 +271,17 @@ * * 0 => error; 1 => ok */ -int check_connection(Connection* con) +int pysqlite_check_connection(pysqlite_Connection* con) { if (!con->db) { - PyErr_SetString(ProgrammingError, "Cannot operate on a closed database."); + PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database."); return 0; } else { return 1; } } -PyObject* _connection_begin(Connection* self) +PyObject* _pysqlite_connection_begin(pysqlite_Connection* self) { int rc; const char* tail; @@ -292,7 +292,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _seterror(self->db); + _pysqlite_seterror(self->db); goto error; } @@ -300,7 +300,7 @@ if (rc == SQLITE_DONE) { self->inTransaction = 1; } else { - _seterror(self->db); + _pysqlite_seterror(self->db); } Py_BEGIN_ALLOW_THREADS @@ -308,7 +308,7 @@ Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _seterror(self->db); + _pysqlite_seterror(self->db); } error: @@ -320,13 +320,13 @@ } } -PyObject* connection_commit(Connection* self, PyObject* args) +PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args) { int rc; const char* tail; sqlite3_stmt* statement; - if (!check_thread(self) || !check_connection(self)) { + if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) { return NULL; } @@ -335,7 +335,7 @@ rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail); Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _seterror(self->db); + _pysqlite_seterror(self->db); goto error; } @@ -343,14 +343,14 @@ if (rc == SQLITE_DONE) { self->inTransaction = 0; } else { - _seterror(self->db); + _pysqlite_seterror(self->db); } Py_BEGIN_ALLOW_THREADS rc = sqlite3_finalize(statement); Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _seterror(self->db); + _pysqlite_seterror(self->db); } } @@ -364,24 +364,24 @@ } } -PyObject* connection_rollback(Connection* self, PyObject* args) +PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args) { int rc; const char* tail; sqlite3_stmt* statement; - if (!check_thread(self) || !check_connection(self)) { + if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) { return NULL; } if (self->inTransaction) { - reset_all_statements(self); + pysqlite_reset_all_statements(self); Py_BEGIN_ALLOW_THREADS rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail); Py_END_ALLOW_THREADS if (rc != SQLITE_OK) { - _seterror(self->db); + _pysqlite_seterror(self->db); goto error; } @@ -389,14 +389,14 @@ if (rc == SQLITE_DONE) { self->inTransaction = 0; } else { - _seterror(self->db); + _pysqlite_seterror(self->db); } Py_BEGIN_ALLOW_THREADS rc = sqlite3_finalize(statement); Py_END_ALLOW_THREADS if (rc != SQLITE_OK && !PyErr_Occurred()) { - _seterror(self->db); + _pysqlite_seterror(self->db); } } @@ -410,7 +410,7 @@ } } -void _set_result(sqlite3_context* context, PyObject* py_val) +void _pysqlite_set_result(sqlite3_context* context, PyObject* py_val) { long longval; const char* buffer; @@ -445,7 +445,7 @@ } } -PyObject* _build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv) +PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv) { PyObject* args; int i; @@ -512,7 +512,7 @@ return args; } -void _func_callback(sqlite3_context* context, int argc, sqlite3_value** argv) +void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv) { PyObject* args; PyObject* py_func; @@ -524,14 +524,14 @@ py_func = (PyObject*)sqlite3_user_data(context); - args = _build_py_params(context, argc, argv); + args = _pysqlite_build_py_params(context, argc, argv); if (args) { py_retval = PyObject_CallObject(py_func, args); Py_DECREF(args); } if (py_retval) { - _set_result(context, py_retval); + _pysqlite_set_result(context, py_retval); Py_DECREF(py_retval); } else { if (_enable_callback_tracebacks) { @@ -545,7 +545,7 @@ PyGILState_Release(threadstate); } -static void _step_callback(sqlite3_context *context, int argc, sqlite3_value** params) +static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params) { PyObject* args; PyObject* function_result = NULL; @@ -581,7 +581,7 @@ goto error; } - args = _build_py_params(context, argc, params); + args = _pysqlite_build_py_params(context, argc, params); if (!args) { goto error; } @@ -605,7 +605,7 @@ PyGILState_Release(threadstate); } -void _final_callback(sqlite3_context* context) +void _pysqlite_final_callback(sqlite3_context* context) { PyObject* function_result = NULL; PyObject** aggregate_instance; @@ -634,7 +634,7 @@ } _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1); } else { - _set_result(context, function_result); + _pysqlite_set_result(context, function_result); } error: @@ -644,7 +644,7 @@ PyGILState_Release(threadstate); } -void _drop_unused_statement_references(Connection* self) +void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self) { PyObject* new_list; PyObject* weakref; @@ -676,7 +676,7 @@ self->statements = new_list; } -PyObject* connection_create_function(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { static char *kwlist[] = {"name", "narg", "func", NULL, NULL}; @@ -691,11 +691,11 @@ return NULL; } - rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _func_callback, NULL, NULL); + rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL); if (rc != SQLITE_OK) { /* Workaround for SQLite bug: no error code or string is available here */ - PyErr_SetString(OperationalError, "Error creating function"); + PyErr_SetString(pysqlite_OperationalError, "Error creating function"); return NULL; } else { PyDict_SetItem(self->function_pinboard, func, Py_None); @@ -705,7 +705,7 @@ } } -PyObject* connection_create_aggregate(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* aggregate_class; @@ -719,10 +719,10 @@ return NULL; } - rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_step_callback, &_final_callback); + rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback); if (rc != SQLITE_OK) { /* Workaround for SQLite bug: no error code or string is available here */ - PyErr_SetString(OperationalError, "Error creating aggregate"); + PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate"); return NULL; } else { PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None); @@ -732,7 +732,7 @@ } } -int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source) +static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source) { PyObject *ret; int rc; @@ -762,7 +762,7 @@ return rc; } -PyObject* connection_set_authorizer(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* authorizer_cb; @@ -777,7 +777,7 @@ rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb); if (rc != SQLITE_OK) { - PyErr_SetString(OperationalError, "Error setting authorizer callback"); + PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback"); return NULL; } else { PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None); @@ -787,11 +787,11 @@ } } -int check_thread(Connection* self) +int pysqlite_check_thread(pysqlite_Connection* self) { if (self->check_same_thread) { if (PyThread_get_thread_ident() != self->thread_ident) { - PyErr_Format(ProgrammingError, + PyErr_Format(pysqlite_ProgrammingError, "SQLite objects created in a thread can only be used in that same thread." "The object was created in thread id %ld and this is thread id %ld", self->thread_ident, PyThread_get_thread_ident()); @@ -803,22 +803,22 @@ return 1; } -static PyObject* connection_get_isolation_level(Connection* self, void* unused) +static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused) { Py_INCREF(self->isolation_level); return self->isolation_level; } -static PyObject* connection_get_total_changes(Connection* self, void* unused) +static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused) { - if (!check_connection(self)) { + if (!pysqlite_check_connection(self)) { return NULL; } else { return Py_BuildValue("i", sqlite3_total_changes(self->db)); } } -static int connection_set_isolation_level(Connection* self, PyObject* isolation_level) +static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level) { PyObject* res; PyObject* begin_statement; @@ -834,7 +834,7 @@ Py_INCREF(Py_None); self->isolation_level = Py_None; - res = connection_commit(self, NULL); + res = pysqlite_connection_commit(self, NULL); if (!res) { return -1; } @@ -866,10 +866,10 @@ return 0; } -PyObject* connection_call(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* sql; - Statement* statement; + pysqlite_Statement* statement; PyObject* weakref; int rc; @@ -877,22 +877,22 @@ return NULL; } - _drop_unused_statement_references(self); + _pysqlite_drop_unused_statement_references(self); - statement = PyObject_New(Statement, &StatementType); + statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType); if (!statement) { return NULL; } - rc = statement_create(statement, self, sql); + rc = pysqlite_statement_create(statement, self, sql); if (rc != SQLITE_OK) { if (rc == PYSQLITE_TOO_MUCH_SQL) { - PyErr_SetString(Warning, "You can only execute one statement at a time."); + PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time."); } else if (rc == PYSQLITE_SQL_WRONG_TYPE) { - PyErr_SetString(Warning, "SQL is of wrong type. Must be string or unicode."); + PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode."); } else { - _seterror(self->db); + _pysqlite_seterror(self->db); } Py_DECREF(statement); @@ -918,7 +918,7 @@ return (PyObject*)statement; } -PyObject* connection_execute(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* cursor = 0; PyObject* result = 0; @@ -949,7 +949,7 @@ return cursor; } -PyObject* connection_executemany(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* cursor = 0; PyObject* result = 0; @@ -980,7 +980,7 @@ return cursor; } -PyObject* connection_executescript(Connection* self, PyObject* args, PyObject* kwargs) +PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { PyObject* cursor = 0; PyObject* result = 0; @@ -1014,7 +1014,7 @@ /* ------------------------- COLLATION CODE ------------------------ */ static int -collation_callback( +pysqlite_collation_callback( void* context, int text1_length, const void* text1_data, int text2_length, const void* text2_data) @@ -1063,11 +1063,11 @@ } static PyObject * -connection_interrupt(Connection* self, PyObject* args) +pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args) { PyObject* retval = NULL; - if (!check_connection(self)) { + if (!pysqlite_check_connection(self)) { goto finally; } @@ -1081,7 +1081,7 @@ } static PyObject * -connection_create_collation(Connection* self, PyObject* args) +pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args) { PyObject* callable; PyObject* uppercase_name = 0; @@ -1090,7 +1090,7 @@ char* chk; int rc; - if (!check_thread(self) || !check_connection(self)) { + if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) { goto finally; } @@ -1111,7 +1111,7 @@ { chk++; } else { - PyErr_SetString(ProgrammingError, "invalid character in collation name"); + PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name"); goto finally; } } @@ -1131,10 +1131,10 @@ PyString_AsString(uppercase_name), SQLITE_UTF8, (callable != Py_None) ? callable : NULL, - (callable != Py_None) ? collation_callback : NULL); + (callable != Py_None) ? pysqlite_collation_callback : NULL); if (rc != SQLITE_OK) { PyDict_DelItem(self->collations, uppercase_name); - _seterror(self->db); + _pysqlite_seterror(self->db); goto finally; } @@ -1155,63 +1155,63 @@ PyDoc_STR("SQLite database connection object."); static PyGetSetDef connection_getset[] = { - {"isolation_level", (getter)connection_get_isolation_level, (setter)connection_set_isolation_level}, - {"total_changes", (getter)connection_get_total_changes, (setter)0}, + {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level}, + {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0}, {NULL} }; static PyMethodDef connection_methods[] = { - {"cursor", (PyCFunction)connection_cursor, METH_VARARGS|METH_KEYWORDS, + {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Return a cursor for the connection.")}, - {"close", (PyCFunction)connection_close, METH_NOARGS, + {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS, PyDoc_STR("Closes the connection.")}, - {"commit", (PyCFunction)connection_commit, METH_NOARGS, + {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS, PyDoc_STR("Commit the current transaction.")}, - {"rollback", (PyCFunction)connection_rollback, METH_NOARGS, + {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS, PyDoc_STR("Roll back the current transaction.")}, - {"create_function", (PyCFunction)connection_create_function, METH_VARARGS|METH_KEYWORDS, + {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Creates a new function. Non-standard.")}, - {"create_aggregate", (PyCFunction)connection_create_aggregate, METH_VARARGS|METH_KEYWORDS, + {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Creates a new aggregate. Non-standard.")}, - {"set_authorizer", (PyCFunction)connection_set_authorizer, METH_VARARGS|METH_KEYWORDS, + {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Sets authorizer callback. Non-standard.")}, - {"execute", (PyCFunction)connection_execute, METH_VARARGS, + {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS, PyDoc_STR("Executes a SQL statement. Non-standard.")}, - {"executemany", (PyCFunction)connection_executemany, METH_VARARGS, + {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS, PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")}, - {"executescript", (PyCFunction)connection_executescript, METH_VARARGS, + {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS, PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")}, - {"create_collation", (PyCFunction)connection_create_collation, METH_VARARGS, + {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS, PyDoc_STR("Creates a collation function. Non-standard.")}, - {"interrupt", (PyCFunction)connection_interrupt, METH_NOARGS, + {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS, PyDoc_STR("Abort any pending database operation. Non-standard.")}, {NULL, NULL} }; static struct PyMemberDef connection_members[] = { - {"Warning", T_OBJECT, offsetof(Connection, Warning), RO}, - {"Error", T_OBJECT, offsetof(Connection, Error), RO}, - {"InterfaceError", T_OBJECT, offsetof(Connection, InterfaceError), RO}, - {"DatabaseError", T_OBJECT, offsetof(Connection, DatabaseError), RO}, - {"DataError", T_OBJECT, offsetof(Connection, DataError), RO}, - {"OperationalError", T_OBJECT, offsetof(Connection, OperationalError), RO}, - {"IntegrityError", T_OBJECT, offsetof(Connection, IntegrityError), RO}, - {"InternalError", T_OBJECT, offsetof(Connection, InternalError), RO}, - {"ProgrammingError", T_OBJECT, offsetof(Connection, ProgrammingError), RO}, - {"NotSupportedError", T_OBJECT, offsetof(Connection, NotSupportedError), RO}, - {"row_factory", T_OBJECT, offsetof(Connection, row_factory)}, - {"text_factory", T_OBJECT, offsetof(Connection, text_factory)}, + {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), RO}, + {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), RO}, + {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), RO}, + {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), RO}, + {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), RO}, + {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), RO}, + {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), RO}, + {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), RO}, + {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), RO}, + {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), RO}, + {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)}, + {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)}, {NULL} }; -PyTypeObject ConnectionType = { +PyTypeObject pysqlite_ConnectionType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".Connection", /* tp_name */ - sizeof(Connection), /* tp_basicsize */ + sizeof(pysqlite_Connection), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)connection_dealloc, /* tp_dealloc */ + (destructor)pysqlite_connection_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1221,7 +1221,7 @@ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ - (ternaryfunc)connection_call, /* tp_call */ + (ternaryfunc)pysqlite_connection_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ @@ -1242,14 +1242,14 @@ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)connection_init, /* tp_init */ + (initproc)pysqlite_connection_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0 /* tp_free */ }; -extern int connection_setup_types(void) +extern int pysqlite_connection_setup_types(void) { - ConnectionType.tp_new = PyType_GenericNew; - return PyType_Ready(&ConnectionType); + pysqlite_ConnectionType.tp_new = PyType_GenericNew; + return PyType_Ready(&pysqlite_ConnectionType); } Modified: python/branches/p3yk/Modules/_sqlite/connection.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/connection.h (original) +++ python/branches/p3yk/Modules/_sqlite/connection.h Mon Jan 15 16:49:28 2007 @@ -66,7 +66,7 @@ /* thread identification of the thread the connection was created in */ long thread_ident; - Cache* statement_cache; + pysqlite_Cache* statement_cache; /* A list of weak references to statements used within this connection */ PyObject* statements; @@ -106,24 +106,23 @@ PyObject* InternalError; PyObject* ProgrammingError; PyObject* NotSupportedError; -} Connection; +} pysqlite_Connection; -extern PyTypeObject ConnectionType; +extern PyTypeObject pysqlite_ConnectionType; -PyObject* connection_alloc(PyTypeObject* type, int aware); -void connection_dealloc(Connection* self); -PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs); -PyObject* connection_close(Connection* self, PyObject* args); -PyObject* _connection_begin(Connection* self); -PyObject* connection_begin(Connection* self, PyObject* args); -PyObject* connection_commit(Connection* self, PyObject* args); -PyObject* connection_rollback(Connection* self, PyObject* args); -PyObject* connection_new(PyTypeObject* type, PyObject* args, PyObject* kw); -int connection_init(Connection* self, PyObject* args, PyObject* kwargs); +PyObject* pysqlite_connection_alloc(PyTypeObject* type, int aware); +void pysqlite_connection_dealloc(pysqlite_Connection* self); +PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs); +PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args); +PyObject* _pysqlite_connection_begin(pysqlite_Connection* self); +PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args); +PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args); +PyObject* pysqlite_connection_new(PyTypeObject* type, PyObject* args, PyObject* kw); +int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs); -int check_thread(Connection* self); -int check_connection(Connection* con); +int pysqlite_check_thread(pysqlite_Connection* self); +int pysqlite_check_connection(pysqlite_Connection* con); -int connection_setup_types(void); +int pysqlite_connection_setup_types(void); #endif Modified: python/branches/p3yk/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/cursor.c (original) +++ python/branches/p3yk/Modules/_sqlite/cursor.c Mon Jan 15 16:49:28 2007 @@ -34,9 +34,9 @@ #define INT32_MAX 2147483647 #endif -PyObject* cursor_iternext(Cursor *self); +PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self); -static StatementKind detect_statement_type(char* statement) +static pysqlite_StatementKind detect_statement_type(char* statement) { char buf[20]; char* src; @@ -74,11 +74,11 @@ } } -int cursor_init(Cursor* self, PyObject* args, PyObject* kwargs) +int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs) { - Connection* connection; + pysqlite_Connection* connection; - if (!PyArg_ParseTuple(args, "O!", &ConnectionType, &connection)) + if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection)) { return -1; } @@ -109,20 +109,20 @@ Py_INCREF(Py_None); self->row_factory = Py_None; - if (!check_thread(self->connection)) { + if (!pysqlite_check_thread(self->connection)) { return -1; } return 0; } -void cursor_dealloc(Cursor* self) +void pysqlite_cursor_dealloc(pysqlite_Cursor* self) { int rc; /* Reset the statement if the user has not closed the cursor */ if (self->statement) { - rc = statement_reset(self->statement); + rc = pysqlite_statement_reset(self->statement); Py_DECREF(self->statement); } @@ -137,7 +137,7 @@ self->ob_type->tp_free((PyObject*)self); } -PyObject* _get_converter(PyObject* key) +PyObject* _pysqlite_get_converter(PyObject* key) { PyObject* upcase_key; PyObject* retval; @@ -153,7 +153,7 @@ return retval; } -int build_row_cast_map(Cursor* self) +int pysqlite_build_row_cast_map(pysqlite_Cursor* self) { int i; const char* type_start = (const char*)-1; @@ -175,7 +175,7 @@ for (i = 0; i < sqlite3_column_count(self->statement->st); i++) { converter = NULL; - if (self->connection->detect_types | PARSE_COLNAMES) { + if (self->connection->detect_types & PARSE_COLNAMES) { colname = sqlite3_column_name(self->statement->st, i); if (colname) { for (pos = colname; *pos != 0; pos++) { @@ -190,7 +190,7 @@ break; } - converter = _get_converter(key); + converter = _pysqlite_get_converter(key); Py_DECREF(key); break; } @@ -198,7 +198,7 @@ } } - if (!converter && self->connection->detect_types | PARSE_DECLTYPES) { + if (!converter && self->connection->detect_types & PARSE_DECLTYPES) { decltype = sqlite3_column_decltype(self->statement->st, i); if (decltype) { for (pos = decltype;;pos++) { @@ -211,7 +211,7 @@ } } - converter = _get_converter(py_decltype); + converter = _pysqlite_get_converter(py_decltype); Py_DECREF(py_decltype); } } @@ -234,7 +234,7 @@ return 0; } -PyObject* _build_column_name(const char* colname) +PyObject* _pysqlite_build_column_name(const char* colname) { const char* pos; @@ -253,7 +253,7 @@ } } -PyObject* unicode_from_string(const char* val_str, int optimize) +PyObject* pysqlite_unicode_from_string(const char* val_str, int optimize) { const char* check; int is_ascii = 0; @@ -285,7 +285,7 @@ * Precondidition: * - sqlite3_step() has been called before and it returned SQLITE_ROW. */ -PyObject* _fetch_one_row(Cursor* self) +PyObject* _pysqlite_fetch_one_row(pysqlite_Cursor* self) { int i, numcols; PyObject* row; @@ -356,10 +356,10 @@ } else if (coltype == SQLITE_TEXT) { val_str = (const char*)sqlite3_column_text(self->statement->st, i); if ((self->connection->text_factory == (PyObject*)&PyUnicode_Type) - || (self->connection->text_factory == OptimizedUnicode)) { + || (self->connection->text_factory == pysqlite_OptimizedUnicode)) { - converted = unicode_from_string(val_str, - self->connection->text_factory == OptimizedUnicode ? 1 : 0); + converted = pysqlite_unicode_from_string(val_str, + self->connection->text_factory == pysqlite_OptimizedUnicode ? 1 : 0); if (!converted) { colname = sqlite3_column_name(self->statement->st, i); @@ -368,7 +368,7 @@ } PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'", colname , val_str); - PyErr_SetString(OperationalError, buf); + PyErr_SetString(pysqlite_OperationalError, buf); } } else if (self->connection->text_factory == (PyObject*)&PyString_Type) { converted = PyString_FromString(val_str); @@ -406,7 +406,7 @@ return row; } -PyObject* _query_execute(Cursor* self, int multiple, PyObject* args) +PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args) { PyObject* operation; PyObject* operation_bytestr = NULL; @@ -425,7 +425,7 @@ PyObject* second_argument = NULL; long rowcount = 0; - if (!check_thread(self->connection) || !check_connection(self->connection)) { + if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { return NULL; } @@ -492,7 +492,7 @@ if (self->statement != NULL) { /* There is an active statement */ - rc = statement_reset(self->statement); + rc = pysqlite_statement_reset(self->statement); } if (PyString_Check(operation)) { @@ -525,7 +525,7 @@ case STATEMENT_INSERT: case STATEMENT_REPLACE: if (!self->connection->inTransaction) { - result = _connection_begin(self->connection); + result = _pysqlite_connection_begin(self->connection); if (!result) { goto error; } @@ -536,7 +536,7 @@ /* it's a DDL statement or something similar - we better COMMIT first so it works for all cases */ if (self->connection->inTransaction) { - result = connection_commit(self->connection, NULL); + result = pysqlite_connection_commit(self->connection, NULL); if (!result) { goto error; } @@ -545,7 +545,7 @@ break; case STATEMENT_SELECT: if (multiple) { - PyErr_SetString(ProgrammingError, + PyErr_SetString(pysqlite_ProgrammingError, "You cannot execute SELECT statements in executemany()."); goto error; } @@ -563,11 +563,11 @@ } if (self->statement) { - (void)statement_reset(self->statement); + (void)pysqlite_statement_reset(self->statement); Py_DECREF(self->statement); } - self->statement = (Statement*)cache_get(self->connection->statement_cache, func_args); + self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args); Py_DECREF(func_args); if (!self->statement) { @@ -576,19 +576,19 @@ if (self->statement->in_use) { Py_DECREF(self->statement); - self->statement = PyObject_New(Statement, &StatementType); + self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType); if (!self->statement) { goto error; } - rc = statement_create(self->statement, self->connection, operation); + rc = pysqlite_statement_create(self->statement, self->connection, operation); if (rc != SQLITE_OK) { self->statement = 0; goto error; } } - statement_reset(self->statement); - statement_mark_dirty(self->statement); + pysqlite_statement_reset(self->statement); + pysqlite_statement_mark_dirty(self->statement); while (1) { parameters = PyIter_Next(parameters_iter); @@ -596,27 +596,37 @@ break; } - statement_mark_dirty(self->statement); + pysqlite_statement_mark_dirty(self->statement); - statement_bind_parameters(self->statement, parameters); + pysqlite_statement_bind_parameters(self->statement, parameters); if (PyErr_Occurred()) { goto error; } - if (build_row_cast_map(self) != 0) { - PyErr_SetString(OperationalError, "Error while building row_cast_map"); + if (pysqlite_build_row_cast_map(self) != 0) { + PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map"); goto error; } - rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); - if (rc != SQLITE_DONE && rc != SQLITE_ROW) { - rc = statement_reset(self->statement); + /* Keep trying the SQL statement until the schema stops changing. */ + while (1) { + /* Actually execute the SQL statement. */ + rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); + if (rc == SQLITE_DONE || rc == SQLITE_ROW) { + /* If it worked, let's get out of the loop */ + break; + } + /* Something went wrong. Re-set the statement and try again. */ + rc = pysqlite_statement_reset(self->statement); if (rc == SQLITE_SCHEMA) { - rc = statement_recompile(self->statement, parameters); + /* If this was a result of the schema changing, let's try + again. */ + rc = pysqlite_statement_recompile(self->statement, parameters); if (rc == SQLITE_OK) { - rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); + continue; } else { - _seterror(self->connection->db); + /* If the database gave us an error, promote it to Python. */ + _pysqlite_seterror(self->connection->db); goto error; } } else { @@ -628,7 +638,7 @@ PyErr_Clear(); } } - _seterror(self->connection->db); + _pysqlite_seterror(self->connection->db); goto error; } } @@ -649,7 +659,7 @@ if (!descriptor) { goto error; } - PyTuple_SetItem(descriptor, 0, _build_column_name(sqlite3_column_name(self->statement->st, i))); + PyTuple_SetItem(descriptor, 0, _pysqlite_build_column_name(sqlite3_column_name(self->statement->st, i))); Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None); Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None); Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None); @@ -663,13 +673,13 @@ if (rc == SQLITE_ROW) { if (multiple) { - PyErr_SetString(ProgrammingError, "executemany() can only execute DML statements."); + PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements."); goto error; } - self->next_row = _fetch_one_row(self); + self->next_row = _pysqlite_fetch_one_row(self); } else if (rc == SQLITE_DONE && !multiple) { - statement_reset(self->statement); + pysqlite_statement_reset(self->statement); Py_DECREF(self->statement); self->statement = 0; } @@ -698,7 +708,7 @@ } if (multiple) { - rc = statement_reset(self->statement); + rc = pysqlite_statement_reset(self->statement); } Py_XDECREF(parameters); } @@ -717,17 +727,17 @@ } } -PyObject* cursor_execute(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args) { - return _query_execute(self, 0, args); + return _pysqlite_query_execute(self, 0, args); } -PyObject* cursor_executemany(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args) { - return _query_execute(self, 1, args); + return _pysqlite_query_execute(self, 1, args); } -PyObject* cursor_executescript(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args) { PyObject* script_obj; PyObject* script_str = NULL; @@ -741,7 +751,7 @@ return NULL; } - if (!check_thread(self->connection) || !check_connection(self->connection)) { + if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { return NULL; } @@ -760,7 +770,7 @@ } /* commit first */ - result = connection_commit(self->connection, NULL); + result = pysqlite_connection_commit(self->connection, NULL); if (!result) { goto error; } @@ -778,7 +788,7 @@ &statement, &script_cstr); if (rc != SQLITE_OK) { - _seterror(self->connection->db); + _pysqlite_seterror(self->connection->db); goto error; } @@ -790,13 +800,13 @@ if (rc != SQLITE_DONE) { (void)sqlite3_finalize(statement); - _seterror(self->connection->db); + _pysqlite_seterror(self->connection->db); goto error; } rc = sqlite3_finalize(statement); if (rc != SQLITE_OK) { - _seterror(self->connection->db); + _pysqlite_seterror(self->connection->db); goto error; } } @@ -805,7 +815,7 @@ Py_XDECREF(script_str); if (!statement_completed) { - PyErr_SetString(ProgrammingError, "you did not provide a complete SQL statement"); + PyErr_SetString(pysqlite_ProgrammingError, "you did not provide a complete SQL statement"); } if (PyErr_Occurred()) { @@ -816,25 +826,25 @@ } } -PyObject* cursor_getiter(Cursor *self) +PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self) { Py_INCREF(self); return (PyObject*)self; } -PyObject* cursor_iternext(Cursor *self) +PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self) { PyObject* next_row_tuple; PyObject* next_row; int rc; - if (!check_thread(self->connection) || !check_connection(self->connection)) { + if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { return NULL; } if (!self->next_row) { if (self->statement) { - (void)statement_reset(self->statement); + (void)pysqlite_statement_reset(self->statement); Py_DECREF(self->statement); self->statement = NULL; } @@ -851,25 +861,27 @@ next_row = next_row_tuple; } - rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); - if (rc != SQLITE_DONE && rc != SQLITE_ROW) { - Py_DECREF(next_row); - _seterror(self->connection->db); - return NULL; - } + if (self->statement) { + rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection); + if (rc != SQLITE_DONE && rc != SQLITE_ROW) { + Py_DECREF(next_row); + _pysqlite_seterror(self->connection->db); + return NULL; + } - if (rc == SQLITE_ROW) { - self->next_row = _fetch_one_row(self); + if (rc == SQLITE_ROW) { + self->next_row = _pysqlite_fetch_one_row(self); + } } return next_row; } -PyObject* cursor_fetchone(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args) { PyObject* row; - row = cursor_iternext(self); + row = pysqlite_cursor_iternext(self); if (!row && !PyErr_Occurred()) { Py_INCREF(Py_None); return Py_None; @@ -878,7 +890,7 @@ return row; } -PyObject* cursor_fetchmany(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args) { PyObject* row; PyObject* list; @@ -898,7 +910,7 @@ row = Py_None; while (row) { - row = cursor_iternext(self); + row = pysqlite_cursor_iternext(self); if (row) { PyList_Append(list, row); Py_DECREF(row); @@ -919,7 +931,7 @@ } } -PyObject* cursor_fetchall(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args) { PyObject* row; PyObject* list; @@ -933,7 +945,7 @@ row = (PyObject*)Py_None; while (row) { - row = cursor_iternext(self); + row = pysqlite_cursor_iternext(self); if (row) { PyList_Append(list, row); Py_DECREF(row); @@ -948,21 +960,21 @@ } } -PyObject* pysqlite_noop(Connection* self, PyObject* args) +PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args) { /* don't care, return None */ Py_INCREF(Py_None); return Py_None; } -PyObject* cursor_close(Cursor* self, PyObject* args) +PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args) { - if (!check_thread(self->connection) || !check_connection(self->connection)) { + if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) { return NULL; } if (self->statement) { - (void)statement_reset(self->statement); + (void)pysqlite_statement_reset(self->statement); Py_DECREF(self->statement); self->statement = 0; } @@ -972,19 +984,19 @@ } static PyMethodDef cursor_methods[] = { - {"execute", (PyCFunction)cursor_execute, METH_VARARGS, + {"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS, PyDoc_STR("Executes a SQL statement.")}, - {"executemany", (PyCFunction)cursor_executemany, METH_VARARGS, + {"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS, PyDoc_STR("Repeatedly executes a SQL statement.")}, - {"executescript", (PyCFunction)cursor_executescript, METH_VARARGS, + {"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS, PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")}, - {"fetchone", (PyCFunction)cursor_fetchone, METH_NOARGS, + {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS, PyDoc_STR("Fetches several rows from the resultset.")}, - {"fetchmany", (PyCFunction)cursor_fetchmany, METH_VARARGS, + {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS, PyDoc_STR("Fetches all rows from the resultset.")}, - {"fetchall", (PyCFunction)cursor_fetchall, METH_NOARGS, + {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS, PyDoc_STR("Fetches one row from the resultset.")}, - {"close", (PyCFunction)cursor_close, METH_NOARGS, + {"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS, PyDoc_STR("Closes the cursor.")}, {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS, PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")}, @@ -995,25 +1007,25 @@ static struct PyMemberDef cursor_members[] = { - {"connection", T_OBJECT, offsetof(Cursor, connection), RO}, - {"description", T_OBJECT, offsetof(Cursor, description), RO}, - {"arraysize", T_INT, offsetof(Cursor, arraysize), 0}, - {"lastrowid", T_OBJECT, offsetof(Cursor, lastrowid), RO}, - {"rowcount", T_OBJECT, offsetof(Cursor, rowcount), RO}, - {"row_factory", T_OBJECT, offsetof(Cursor, row_factory), 0}, + {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), RO}, + {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), RO}, + {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0}, + {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), RO}, + {"rowcount", T_OBJECT, offsetof(pysqlite_Cursor, rowcount), RO}, + {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0}, {NULL} }; static char cursor_doc[] = PyDoc_STR("SQLite database cursor class."); -PyTypeObject CursorType = { +PyTypeObject pysqlite_CursorType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".Cursor", /* tp_name */ - sizeof(Cursor), /* tp_basicsize */ + sizeof(pysqlite_Cursor), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)cursor_dealloc, /* tp_dealloc */ + (destructor)pysqlite_cursor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -1034,8 +1046,8 @@ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ - (getiterfunc)cursor_getiter, /* tp_iter */ - (iternextfunc)cursor_iternext, /* tp_iternext */ + (getiterfunc)pysqlite_cursor_getiter, /* tp_iter */ + (iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */ cursor_methods, /* tp_methods */ cursor_members, /* tp_members */ 0, /* tp_getset */ @@ -1044,14 +1056,14 @@ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)cursor_init, /* tp_init */ + (initproc)pysqlite_cursor_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0 /* tp_free */ }; -extern int cursor_setup_types(void) +extern int pysqlite_cursor_setup_types(void) { - CursorType.tp_new = PyType_GenericNew; - return PyType_Ready(&CursorType); + pysqlite_CursorType.tp_new = PyType_GenericNew; + return PyType_Ready(&pysqlite_CursorType); } Modified: python/branches/p3yk/Modules/_sqlite/cursor.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/cursor.h (original) +++ python/branches/p3yk/Modules/_sqlite/cursor.h Mon Jan 15 16:49:28 2007 @@ -32,40 +32,40 @@ typedef struct { PyObject_HEAD - Connection* connection; + pysqlite_Connection* connection; PyObject* description; PyObject* row_cast_map; int arraysize; PyObject* lastrowid; PyObject* rowcount; PyObject* row_factory; - Statement* statement; + pysqlite_Statement* statement; /* the next row to be returned, NULL if no next row available */ PyObject* next_row; -} Cursor; +} pysqlite_Cursor; typedef enum { STATEMENT_INVALID, STATEMENT_INSERT, STATEMENT_DELETE, STATEMENT_UPDATE, STATEMENT_REPLACE, STATEMENT_SELECT, STATEMENT_OTHER -} StatementKind; +} pysqlite_StatementKind; -extern PyTypeObject CursorType; +extern PyTypeObject pysqlite_CursorType; -int cursor_init(Cursor* self, PyObject* args, PyObject* kwargs); -void cursor_dealloc(Cursor* self); -PyObject* cursor_execute(Cursor* self, PyObject* args); -PyObject* cursor_executemany(Cursor* self, PyObject* args); -PyObject* cursor_getiter(Cursor *self); -PyObject* cursor_iternext(Cursor *self); -PyObject* cursor_fetchone(Cursor* self, PyObject* args); -PyObject* cursor_fetchmany(Cursor* self, PyObject* args); -PyObject* cursor_fetchall(Cursor* self, PyObject* args); -PyObject* pysqlite_noop(Connection* self, PyObject* args); -PyObject* cursor_close(Cursor* self, PyObject* args); +int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs); +void pysqlite_cursor_dealloc(pysqlite_Cursor* self); +PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self); +PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self); +PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args); +PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args); +PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args); -int cursor_setup_types(void); +int pysqlite_cursor_setup_types(void); #define UNKNOWN (-1) #endif Modified: python/branches/p3yk/Modules/_sqlite/microprotocols.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/microprotocols.c (original) +++ python/branches/p3yk/Modules/_sqlite/microprotocols.c Mon Jan 15 16:49:28 2007 @@ -57,7 +57,7 @@ PyObject* key; int rc; - if (proto == NULL) proto = (PyObject*)&SQLitePrepareProtocolType; + if (proto == NULL) proto = (PyObject*)&pysqlite_PrepareProtocolType; key = Py_BuildValue("(OO)", (PyObject*)type, proto); if (!key) { @@ -78,7 +78,7 @@ PyObject *adapter, *key; /* we don't check for exact type conformance as specified in PEP 246 - because the SQLitePrepareProtocolType type is abstract and there is no + because the pysqlite_PrepareProtocolType type is abstract and there is no way to get a quotable object to be its instance */ /* look for an adapter in the registry */ @@ -125,17 +125,17 @@ } /* else set the right exception and return NULL */ - PyErr_SetString(ProgrammingError, "can't adapt"); + PyErr_SetString(pysqlite_ProgrammingError, "can't adapt"); return NULL; } /** module-level functions **/ PyObject * -psyco_microprotocols_adapt(Cursor *self, PyObject *args) +psyco_microprotocols_adapt(pysqlite_Cursor *self, PyObject *args) { PyObject *obj, *alt = NULL; - PyObject *proto = (PyObject*)&SQLitePrepareProtocolType; + PyObject *proto = (PyObject*)&pysqlite_PrepareProtocolType; if (!PyArg_ParseTuple(args, "O|OO", &obj, &proto, &alt)) return NULL; return microprotocols_adapt(obj, proto, alt); Modified: python/branches/p3yk/Modules/_sqlite/microprotocols.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/microprotocols.h (original) +++ python/branches/p3yk/Modules/_sqlite/microprotocols.h Mon Jan 15 16:49:28 2007 @@ -52,7 +52,7 @@ PyObject *obj, PyObject *proto, PyObject *alt); extern PyObject * - psyco_microprotocols_adapt(Cursor* self, PyObject *args); + psyco_microprotocols_adapt(pysqlite_Cursor* self, PyObject *args); #define psyco_microprotocols_adapt_doc \ "adapt(obj, protocol, alternate) -> adapt obj to given protocol. Non-standard." Modified: python/branches/p3yk/Modules/_sqlite/module.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/module.c (original) +++ python/branches/p3yk/Modules/_sqlite/module.c Mon Jan 15 16:49:28 2007 @@ -35,9 +35,9 @@ /* static objects at module-level */ -PyObject* Error, *Warning, *InterfaceError, *DatabaseError, *InternalError, - *OperationalError, *ProgrammingError, *IntegrityError, *DataError, - *NotSupportedError, *OptimizedUnicode; +PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite_DatabaseError, + *pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError, + *pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError, *pysqlite_OptimizedUnicode; PyObject* converters; int _enable_callback_tracebacks; @@ -67,7 +67,7 @@ } if (factory == NULL) { - factory = (PyObject*)&ConnectionType; + factory = (PyObject*)&pysqlite_ConnectionType; } result = PyObject_Call(factory, args, kwargs); @@ -115,7 +115,7 @@ rc = sqlite3_enable_shared_cache(do_enable); if (rc != SQLITE_OK) { - PyErr_SetString(OperationalError, "Changing the shared_cache flag failed"); + PyErr_SetString(pysqlite_OperationalError, "Changing the shared_cache flag failed"); return NULL; } else { Py_INCREF(Py_None); @@ -133,7 +133,7 @@ return NULL; } - microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster); + microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster); Py_INCREF(Py_None); return Py_None; @@ -141,36 +141,29 @@ static PyObject* module_register_converter(PyObject* self, PyObject* args, PyObject* kwargs) { - char* orig_name; - char* name = NULL; - char* c; + PyObject* orig_name; + PyObject* name = NULL; PyObject* callable; PyObject* retval = NULL; - if (!PyArg_ParseTuple(args, "sO", &orig_name, &callable)) { + if (!PyArg_ParseTuple(args, "SO", &orig_name, &callable)) { return NULL; } - /* convert the name to lowercase */ - name = PyMem_Malloc(strlen(orig_name) + 2); + /* convert the name to upper case */ + name = PyObject_CallMethod(orig_name, "upper", ""); if (!name) { goto error; } - strcpy(name, orig_name); - for (c = name; *c != (char)0; c++) { - *c = (*c) & 0xDF; - } - if (PyDict_SetItemString(converters, name, callable) != 0) { + if (PyDict_SetItem(converters, name, callable) != 0) { goto error; } Py_INCREF(Py_None); retval = Py_None; error: - if (name) { - PyMem_Free(name); - } + Py_XDECREF(name); return retval; } @@ -184,7 +177,7 @@ return Py_None; } -void converters_init(PyObject* dict) +static void converters_init(PyObject* dict) { converters = PyDict_New(); if (!converters) { @@ -265,28 +258,28 @@ module = Py_InitModule("_sqlite3", module_methods); if (!module || - (row_setup_types() < 0) || - (cursor_setup_types() < 0) || - (connection_setup_types() < 0) || - (cache_setup_types() < 0) || - (statement_setup_types() < 0) || - (prepare_protocol_setup_types() < 0) + (pysqlite_row_setup_types() < 0) || + (pysqlite_cursor_setup_types() < 0) || + (pysqlite_connection_setup_types() < 0) || + (pysqlite_cache_setup_types() < 0) || + (pysqlite_statement_setup_types() < 0) || + (pysqlite_prepare_protocol_setup_types() < 0) ) { return; } - Py_INCREF(&ConnectionType); - PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType); - Py_INCREF(&CursorType); - PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType); - Py_INCREF(&CacheType); - PyModule_AddObject(module, "Statement", (PyObject*)&StatementType); - Py_INCREF(&StatementType); - PyModule_AddObject(module, "Cache", (PyObject*) &CacheType); - Py_INCREF(&SQLitePrepareProtocolType); - PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType); - Py_INCREF(&RowType); - PyModule_AddObject(module, "Row", (PyObject*) &RowType); + Py_INCREF(&pysqlite_ConnectionType); + PyModule_AddObject(module, "Connection", (PyObject*) &pysqlite_ConnectionType); + Py_INCREF(&pysqlite_CursorType); + PyModule_AddObject(module, "Cursor", (PyObject*) &pysqlite_CursorType); + Py_INCREF(&pysqlite_CacheType); + PyModule_AddObject(module, "Statement", (PyObject*)&pysqlite_StatementType); + Py_INCREF(&pysqlite_StatementType); + PyModule_AddObject(module, "Cache", (PyObject*) &pysqlite_CacheType); + Py_INCREF(&pysqlite_PrepareProtocolType); + PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &pysqlite_PrepareProtocolType); + Py_INCREF(&pysqlite_RowType); + PyModule_AddObject(module, "Row", (PyObject*) &pysqlite_RowType); if (!(dict = PyModule_GetDict(module))) { goto error; @@ -294,67 +287,67 @@ /*** Create DB-API Exception hierarchy */ - if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) { + if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) { goto error; } - PyDict_SetItemString(dict, "Error", Error); + PyDict_SetItemString(dict, "Error", pysqlite_Error); - if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) { + if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) { goto error; } - PyDict_SetItemString(dict, "Warning", Warning); + PyDict_SetItemString(dict, "Warning", pysqlite_Warning); /* Error subclasses */ - if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) { + if (!(pysqlite_InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", pysqlite_Error, NULL))) { goto error; } - PyDict_SetItemString(dict, "InterfaceError", InterfaceError); + PyDict_SetItemString(dict, "InterfaceError", pysqlite_InterfaceError); - if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) { + if (!(pysqlite_DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", pysqlite_Error, NULL))) { goto error; } - PyDict_SetItemString(dict, "DatabaseError", DatabaseError); + PyDict_SetItemString(dict, "DatabaseError", pysqlite_DatabaseError); - /* DatabaseError subclasses */ + /* pysqlite_DatabaseError subclasses */ - if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) { + if (!(pysqlite_InternalError = PyErr_NewException(MODULE_NAME ".InternalError", pysqlite_DatabaseError, NULL))) { goto error; } - PyDict_SetItemString(dict, "InternalError", InternalError); + PyDict_SetItemString(dict, "InternalError", pysqlite_InternalError); - if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) { + if (!(pysqlite_OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", pysqlite_DatabaseError, NULL))) { goto error; } - PyDict_SetItemString(dict, "OperationalError", OperationalError); + PyDict_SetItemString(dict, "OperationalError", pysqlite_OperationalError); - if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) { + if (!(pysqlite_ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", pysqlite_DatabaseError, NULL))) { goto error; } - PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError); + PyDict_SetItemString(dict, "ProgrammingError", pysqlite_ProgrammingError); - if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) { + if (!(pysqlite_IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", pysqlite_DatabaseError,NULL))) { goto error; } - PyDict_SetItemString(dict, "IntegrityError", IntegrityError); + PyDict_SetItemString(dict, "IntegrityError", pysqlite_IntegrityError); - if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) { + if (!(pysqlite_DataError = PyErr_NewException(MODULE_NAME ".DataError", pysqlite_DatabaseError, NULL))) { goto error; } - PyDict_SetItemString(dict, "DataError", DataError); + PyDict_SetItemString(dict, "DataError", pysqlite_DataError); - if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) { + if (!(pysqlite_NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", pysqlite_DatabaseError, NULL))) { goto error; } - PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError); + PyDict_SetItemString(dict, "NotSupportedError", pysqlite_NotSupportedError); - /* We just need "something" unique for OptimizedUnicode. It does not really + /* We just need "something" unique for pysqlite_OptimizedUnicode. It does not really * need to be a string subclass. Just anything that can act as a special * marker for us. So I pulled PyCell_Type out of my magic hat. */ Py_INCREF((PyObject*)&PyCell_Type); - OptimizedUnicode = (PyObject*)&PyCell_Type; - PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode); + pysqlite_OptimizedUnicode = (PyObject*)&PyCell_Type; + PyDict_SetItemString(dict, "OptimizedUnicode", pysqlite_OptimizedUnicode); /* Set integer constants */ for (i = 0; _int_constants[i].constant_name != 0; i++) { Modified: python/branches/p3yk/Modules/_sqlite/module.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/module.h (original) +++ python/branches/p3yk/Modules/_sqlite/module.h Mon Jan 15 16:49:28 2007 @@ -25,20 +25,20 @@ #define PYSQLITE_MODULE_H #include "Python.h" -#define PYSQLITE_VERSION "2.3.2" +#define PYSQLITE_VERSION "2.3.3" -extern PyObject* Error; -extern PyObject* Warning; -extern PyObject* InterfaceError; -extern PyObject* DatabaseError; -extern PyObject* InternalError; -extern PyObject* OperationalError; -extern PyObject* ProgrammingError; -extern PyObject* IntegrityError; -extern PyObject* DataError; -extern PyObject* NotSupportedError; +extern PyObject* pysqlite_Error; +extern PyObject* pysqlite_Warning; +extern PyObject* pysqlite_InterfaceError; +extern PyObject* pysqlite_DatabaseError; +extern PyObject* pysqlite_InternalError; +extern PyObject* pysqlite_OperationalError; +extern PyObject* pysqlite_ProgrammingError; +extern PyObject* pysqlite_IntegrityError; +extern PyObject* pysqlite_DataError; +extern PyObject* pysqlite_NotSupportedError; -extern PyObject* OptimizedUnicode; +extern PyObject* pysqlite_OptimizedUnicode; /* the functions time.time() and time.sleep() */ extern PyObject* time_time; Modified: python/branches/p3yk/Modules/_sqlite/prepare_protocol.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/prepare_protocol.c (original) +++ python/branches/p3yk/Modules/_sqlite/prepare_protocol.c Mon Jan 15 16:49:28 2007 @@ -23,23 +23,23 @@ #include "prepare_protocol.h" -int prepare_protocol_init(SQLitePrepareProtocol* self, PyObject* args, PyObject* kwargs) +int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs) { return 0; } -void prepare_protocol_dealloc(SQLitePrepareProtocol* self) +void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self) { self->ob_type->tp_free((PyObject*)self); } -PyTypeObject SQLitePrepareProtocolType= { +PyTypeObject pysqlite_PrepareProtocolType= { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".PrepareProtocol", /* tp_name */ - sizeof(SQLitePrepareProtocol), /* tp_basicsize */ + sizeof(pysqlite_PrepareProtocol), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)prepare_protocol_dealloc, /* tp_dealloc */ + (destructor)pysqlite_prepare_protocol_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -70,15 +70,15 @@ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)prepare_protocol_init, /* tp_init */ + (initproc)pysqlite_prepare_protocol_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0 /* tp_free */ }; -extern int prepare_protocol_setup_types(void) +extern int pysqlite_prepare_protocol_setup_types(void) { - SQLitePrepareProtocolType.tp_new = PyType_GenericNew; - SQLitePrepareProtocolType.ob_type= &PyType_Type; - return PyType_Ready(&SQLitePrepareProtocolType); + pysqlite_PrepareProtocolType.tp_new = PyType_GenericNew; + pysqlite_PrepareProtocolType.ob_type= &PyType_Type; + return PyType_Ready(&pysqlite_PrepareProtocolType); } Modified: python/branches/p3yk/Modules/_sqlite/prepare_protocol.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/prepare_protocol.h (original) +++ python/branches/p3yk/Modules/_sqlite/prepare_protocol.h Mon Jan 15 16:49:28 2007 @@ -28,14 +28,14 @@ typedef struct { PyObject_HEAD -} SQLitePrepareProtocol; +} pysqlite_PrepareProtocol; -extern PyTypeObject SQLitePrepareProtocolType; +extern PyTypeObject pysqlite_PrepareProtocolType; -int prepare_protocol_init(SQLitePrepareProtocol* self, PyObject* args, PyObject* kwargs); -void prepare_protocol_dealloc(SQLitePrepareProtocol* self); +int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs); +void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self); -int prepare_protocol_setup_types(void); +int pysqlite_prepare_protocol_setup_types(void); #define UNKNOWN (-1) #endif Modified: python/branches/p3yk/Modules/_sqlite/row.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/row.c (original) +++ python/branches/p3yk/Modules/_sqlite/row.c Mon Jan 15 16:49:28 2007 @@ -25,7 +25,7 @@ #include "cursor.h" #include "sqlitecompat.h" -void row_dealloc(Row* self) +void pysqlite_row_dealloc(pysqlite_Row* self) { Py_XDECREF(self->data); Py_XDECREF(self->description); @@ -33,10 +33,10 @@ self->ob_type->tp_free((PyObject*)self); } -int row_init(Row* self, PyObject* args, PyObject* kwargs) +int pysqlite_row_init(pysqlite_Row* self, PyObject* args, PyObject* kwargs) { PyObject* data; - Cursor* cursor; + pysqlite_Cursor* cursor; self->data = 0; self->description = 0; @@ -45,7 +45,7 @@ return -1; } - if (!PyObject_IsInstance((PyObject*)cursor, (PyObject*)&CursorType)) { + if (!PyObject_IsInstance((PyObject*)cursor, (PyObject*)&pysqlite_CursorType)) { PyErr_SetString(PyExc_TypeError, "instance of cursor required for first argument"); return -1; } @@ -64,7 +64,7 @@ return 0; } -PyObject* row_subscript(Row* self, PyObject* idx) +PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx) { long _idx; char* key; @@ -133,32 +133,63 @@ } } -Py_ssize_t row_length(Row* self, PyObject* args, PyObject* kwargs) +Py_ssize_t pysqlite_row_length(pysqlite_Row* self, PyObject* args, PyObject* kwargs) { return PyTuple_GET_SIZE(self->data); } -static int row_print(Row* self, FILE *fp, int flags) +PyObject* pysqlite_row_keys(pysqlite_Row* self, PyObject* args, PyObject* kwargs) +{ + PyObject* list; + int nitems, i; + + list = PyList_New(0); + if (!list) { + return NULL; + } + nitems = PyTuple_Size(self->description); + + for (i = 0; i < nitems; i++) { + if (PyList_Append(list, PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0)) != 0) { + Py_DECREF(list); + return NULL; + } + } + + return list; +} + +static int pysqlite_row_print(pysqlite_Row* self, FILE *fp, int flags) { return (&PyTuple_Type)->tp_print(self->data, fp, flags); } +static PyObject* pysqlite_iter(pysqlite_Row* self) +{ + return PyObject_GetIter(self->data); +} -PyMappingMethods row_as_mapping = { - /* mp_length */ (lenfunc)row_length, - /* mp_subscript */ (binaryfunc)row_subscript, +PyMappingMethods pysqlite_row_as_mapping = { + /* mp_length */ (lenfunc)pysqlite_row_length, + /* mp_subscript */ (binaryfunc)pysqlite_row_subscript, /* mp_ass_subscript */ (objobjargproc)0, }; +static PyMethodDef pysqlite_row_methods[] = { + {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS, + PyDoc_STR("Returns the keys of the row.")}, + {NULL, NULL} +}; + -PyTypeObject RowType = { +PyTypeObject pysqlite_RowType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".Row", /* tp_name */ - sizeof(Row), /* tp_basicsize */ + sizeof(pysqlite_Row), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)row_dealloc, /* tp_dealloc */ - (printfunc)row_print, /* tp_print */ + (destructor)pysqlite_row_dealloc, /* tp_dealloc */ + (printfunc)pysqlite_row_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ @@ -174,13 +205,13 @@ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ 0, /* tp_doc */ - 0, /* tp_traverse */ + (traverseproc)0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ + (getiterfunc)pysqlite_iter, /* tp_iter */ 0, /* tp_iternext */ - 0, /* tp_methods */ + pysqlite_row_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ @@ -188,15 +219,15 @@ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)row_init, /* tp_init */ + (initproc)pysqlite_row_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0 /* tp_free */ }; -extern int row_setup_types(void) +extern int pysqlite_row_setup_types(void) { - RowType.tp_new = PyType_GenericNew; - RowType.tp_as_mapping = &row_as_mapping; - return PyType_Ready(&RowType); + pysqlite_RowType.tp_new = PyType_GenericNew; + pysqlite_RowType.tp_as_mapping = &pysqlite_row_as_mapping; + return PyType_Ready(&pysqlite_RowType); } Modified: python/branches/p3yk/Modules/_sqlite/row.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/row.h (original) +++ python/branches/p3yk/Modules/_sqlite/row.h Mon Jan 15 16:49:28 2007 @@ -30,10 +30,10 @@ PyObject_HEAD PyObject* data; PyObject* description; -} Row; +} pysqlite_Row; -extern PyTypeObject RowType; +extern PyTypeObject pysqlite_RowType; -int row_setup_types(void); +int pysqlite_row_setup_types(void); #endif Modified: python/branches/p3yk/Modules/_sqlite/statement.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/statement.c (original) +++ python/branches/p3yk/Modules/_sqlite/statement.c Mon Jan 15 16:49:28 2007 @@ -29,7 +29,7 @@ #include "sqlitecompat.h" /* prototypes */ -int check_remaining_sql(const char* tail); +static int pysqlite_check_remaining_sql(const char* tail); typedef enum { LINECOMMENT_1, @@ -40,7 +40,7 @@ NORMAL } parse_remaining_sql_state; -int statement_create(Statement* self, Connection* connection, PyObject* sql) +int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql) { const char* tail; int rc; @@ -77,7 +77,7 @@ self->db = connection->db; - if (rc == SQLITE_OK && check_remaining_sql(tail)) { + if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) { (void)sqlite3_finalize(self->st); self->st = NULL; rc = PYSQLITE_TOO_MUCH_SQL; @@ -86,7 +86,7 @@ return rc; } -int statement_bind_parameter(Statement* self, int pos, PyObject* parameter) +int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter) { int rc = SQLITE_OK; long longval; @@ -133,7 +133,7 @@ return rc; } -void statement_bind_parameters(Statement* self, PyObject* parameters) +void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters) { PyObject* current_param; PyObject* adapted; @@ -154,19 +154,19 @@ binding_name = sqlite3_bind_parameter_name(self->st, i); Py_END_ALLOW_THREADS if (!binding_name) { - PyErr_Format(ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i); + PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i); return; } binding_name++; /* skip first char (the colon) */ current_param = PyDict_GetItemString(parameters, binding_name); if (!current_param) { - PyErr_Format(ProgrammingError, "You did not supply a value for binding %d.", i); + PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i); return; } Py_INCREF(current_param); - adapted = microprotocols_adapt(current_param, (PyObject*)&SQLitePrepareProtocolType, NULL); + adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); if (adapted) { Py_DECREF(current_param); } else { @@ -174,11 +174,11 @@ adapted = current_param; } - rc = statement_bind_parameter(self, i, adapted); + rc = pysqlite_statement_bind_parameter(self, i, adapted); Py_DECREF(adapted); if (rc != SQLITE_OK) { - PyErr_Format(InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name); + PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name); return; } } @@ -186,7 +186,7 @@ /* parameters passed as sequence */ num_params = PySequence_Length(parameters); if (num_params != num_params_needed) { - PyErr_Format(ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.", + PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.", num_params_needed, num_params); return; } @@ -195,7 +195,7 @@ if (!current_param) { return; } - adapted = microprotocols_adapt(current_param, (PyObject*)&SQLitePrepareProtocolType, NULL); + adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL); if (adapted) { Py_DECREF(current_param); @@ -204,18 +204,18 @@ adapted = current_param; } - rc = statement_bind_parameter(self, i + 1, adapted); + rc = pysqlite_statement_bind_parameter(self, i + 1, adapted); Py_DECREF(adapted); if (rc != SQLITE_OK) { - PyErr_Format(InterfaceError, "Error binding parameter %d - probably unsupported type.", i); + PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i); return; } } } } -int statement_recompile(Statement* self, PyObject* params) +int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params) { const char* tail; int rc; @@ -250,7 +250,7 @@ return rc; } -int statement_finalize(Statement* self) +int pysqlite_statement_finalize(pysqlite_Statement* self) { int rc; @@ -267,7 +267,7 @@ return rc; } -int statement_reset(Statement* self) +int pysqlite_statement_reset(pysqlite_Statement* self) { int rc; @@ -286,12 +286,12 @@ return rc; } -void statement_mark_dirty(Statement* self) +void pysqlite_statement_mark_dirty(pysqlite_Statement* self) { self->in_use = 1; } -void statement_dealloc(Statement* self) +void pysqlite_statement_dealloc(pysqlite_Statement* self) { int rc; @@ -320,7 +320,7 @@ * * Returns 1 if there is more left than should be. 0 if ok. */ -int check_remaining_sql(const char* tail) +static int pysqlite_check_remaining_sql(const char* tail) { const char* pos = tail; @@ -382,13 +382,13 @@ return 0; } -PyTypeObject StatementType = { +PyTypeObject pysqlite_StatementType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ MODULE_NAME ".Statement", /* tp_name */ - sizeof(Statement), /* tp_basicsize */ + sizeof(pysqlite_Statement), /* tp_basicsize */ 0, /* tp_itemsize */ - (destructor)statement_dealloc, /* tp_dealloc */ + (destructor)pysqlite_statement_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ @@ -408,7 +408,7 @@ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ - offsetof(Statement, in_weakreflist), /* tp_weaklistoffset */ + offsetof(pysqlite_Statement, in_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ @@ -425,8 +425,8 @@ 0 /* tp_free */ }; -extern int statement_setup_types(void) +extern int pysqlite_statement_setup_types(void) { - StatementType.tp_new = PyType_GenericNew; - return PyType_Ready(&StatementType); + pysqlite_StatementType.tp_new = PyType_GenericNew; + return PyType_Ready(&pysqlite_StatementType); } Modified: python/branches/p3yk/Modules/_sqlite/statement.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/statement.h (original) +++ python/branches/p3yk/Modules/_sqlite/statement.h Mon Jan 15 16:49:28 2007 @@ -39,21 +39,21 @@ PyObject* sql; int in_use; PyObject* in_weakreflist; /* List of weak references */ -} Statement; +} pysqlite_Statement; -extern PyTypeObject StatementType; +extern PyTypeObject pysqlite_StatementType; -int statement_create(Statement* self, Connection* connection, PyObject* sql); -void statement_dealloc(Statement* self); +int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql); +void pysqlite_statement_dealloc(pysqlite_Statement* self); -int statement_bind_parameter(Statement* self, int pos, PyObject* parameter); -void statement_bind_parameters(Statement* self, PyObject* parameters); +int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter); +void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters); -int statement_recompile(Statement* self, PyObject* parameters); -int statement_finalize(Statement* self); -int statement_reset(Statement* self); -void statement_mark_dirty(Statement* self); +int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* parameters); +int pysqlite_statement_finalize(pysqlite_Statement* self); +int pysqlite_statement_reset(pysqlite_Statement* self); +void pysqlite_statement_mark_dirty(pysqlite_Statement* self); -int statement_setup_types(void); +int pysqlite_statement_setup_types(void); #endif Modified: python/branches/p3yk/Modules/_sqlite/util.c ============================================================================== --- python/branches/p3yk/Modules/_sqlite/util.c (original) +++ python/branches/p3yk/Modules/_sqlite/util.c Mon Jan 15 16:49:28 2007 @@ -24,8 +24,7 @@ #include "module.h" #include "connection.h" -int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, Connection* connection -) +int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, pysqlite_Connection* connection) { int rc; @@ -40,7 +39,7 @@ * Checks the SQLite error code and sets the appropriate DB-API exception. * Returns the error code (0 means no error occurred). */ -int _seterror(sqlite3* db) +int _pysqlite_seterror(sqlite3* db) { int errorcode; @@ -53,7 +52,7 @@ break; case SQLITE_INTERNAL: case SQLITE_NOTFOUND: - PyErr_SetString(InternalError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_InternalError, sqlite3_errmsg(db)); break; case SQLITE_NOMEM: (void)PyErr_NoMemory(); @@ -71,23 +70,23 @@ case SQLITE_PROTOCOL: case SQLITE_EMPTY: case SQLITE_SCHEMA: - PyErr_SetString(OperationalError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_OperationalError, sqlite3_errmsg(db)); break; case SQLITE_CORRUPT: - PyErr_SetString(DatabaseError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db)); break; case SQLITE_TOOBIG: - PyErr_SetString(DataError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_DataError, sqlite3_errmsg(db)); break; case SQLITE_CONSTRAINT: case SQLITE_MISMATCH: - PyErr_SetString(IntegrityError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_IntegrityError, sqlite3_errmsg(db)); break; case SQLITE_MISUSE: - PyErr_SetString(ProgrammingError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_ProgrammingError, sqlite3_errmsg(db)); break; default: - PyErr_SetString(DatabaseError, sqlite3_errmsg(db)); + PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db)); break; } Modified: python/branches/p3yk/Modules/_sqlite/util.h ============================================================================== --- python/branches/p3yk/Modules/_sqlite/util.h (original) +++ python/branches/p3yk/Modules/_sqlite/util.h Mon Jan 15 16:49:28 2007 @@ -28,11 +28,11 @@ #include "sqlite3.h" #include "connection.h" -int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, Connection* connection); +int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, pysqlite_Connection* connection); /** * Checks the SQLite error code and sets the appropriate DB-API exception. * Returns the error code (0 means no error occurred). */ -int _seterror(sqlite3* db); +int _pysqlite_seterror(sqlite3* db); #endif Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Mon Jan 15 16:49:28 2007 @@ -1050,8 +1050,9 @@ argument will be truncated towards zero (this does not include a string\n\ representation of a floating point number!) When converting a string, use\n\ the optional base. It is an error to supply a base when converting a\n\ -non-string. If the argument is outside the integer range a long object\n\ -will be returned instead."); +non-string. If base is zero, the proper base is guessed based on the\n\ +string content. If the argument is outside the integer range a\n\ +long object will be returned instead."); static PyNumberMethods int_as_number = { (binaryfunc)int_add, /*nb_add*/ Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Mon Jan 15 16:49:28 2007 @@ -1024,7 +1024,7 @@ { PyObject *iterable = NULL, *result; - if (!_PyArg_NoKeywords("frozenset()", kwds)) + if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) @@ -1068,7 +1068,7 @@ static PyObject * set_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if (!_PyArg_NoKeywords("set()", kwds)) + if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) return NULL; return make_new_set(type, NULL); Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Jan 15 16:49:28 2007 @@ -3126,7 +3126,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "53170") < 0) + if (PyModule_AddStringConstant(m, "__version__", "53349") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) Modified: python/branches/p3yk/Tools/pybench/pybench.py ============================================================================== --- python/branches/p3yk/Tools/pybench/pybench.py (original) +++ python/branches/p3yk/Tools/pybench/pybench.py Mon Jan 15 16:49:28 2007 @@ -34,7 +34,7 @@ WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! """ -import sys, time, operator, string +import sys, time, operator, string, platform from CommandLine import * try: @@ -102,27 +102,26 @@ def get_machine_details(): - import platform if _debug: print 'Getting machine details...' buildno, builddate = platform.python_build() python = platform.python_version() - if python > '2.0': - try: - unichr(100000) - except ValueError: - # UCS2 build (standard) - unicode = 'UCS2' - else: - # UCS4 build (most recent Linux distros) - unicode = 'UCS4' - else: + try: + unichr(100000) + except ValueError: + # UCS2 build (standard) + unicode = 'UCS2' + except NameError: unicode = None + else: + # UCS4 build (most recent Linux distros) + unicode = 'UCS4' bits, linkage = platform.architecture() return { 'platform': platform.platform(), 'processor': platform.processor(), 'executable': sys.executable, + 'implementation': platform.python_implementation(), 'python': platform.python_version(), 'compiler': platform.python_compiler(), 'buildno': buildno, @@ -134,17 +133,18 @@ def print_machine_details(d, indent=''): l = ['Machine Details:', - ' Platform ID: %s' % d.get('platform', 'n/a'), - ' Processor: %s' % d.get('processor', 'n/a'), + ' Platform ID: %s' % d.get('platform', 'n/a'), + ' Processor: %s' % d.get('processor', 'n/a'), '', 'Python:', - ' Executable: %s' % d.get('executable', 'n/a'), - ' Version: %s' % d.get('python', 'n/a'), - ' Compiler: %s' % d.get('compiler', 'n/a'), - ' Bits: %s' % d.get('bits', 'n/a'), - ' Build: %s (#%s)' % (d.get('builddate', 'n/a'), - d.get('buildno', 'n/a')), - ' Unicode: %s' % d.get('unicode', 'n/a'), + ' Implementation: %s' % d.get('implementation', 'n/a'), + ' Executable: %s' % d.get('executable', 'n/a'), + ' Version: %s' % d.get('python', 'n/a'), + ' Compiler: %s' % d.get('compiler', 'n/a'), + ' Bits: %s' % d.get('bits', 'n/a'), + ' Build: %s (#%s)' % (d.get('builddate', 'n/a'), + d.get('buildno', 'n/a')), + ' Unicode: %s' % d.get('unicode', 'n/a'), ] print indent + string.join(l, '\n' + indent) + '\n' @@ -499,9 +499,10 @@ def calibrate(self): - print 'Calibrating tests. Please wait...' + print 'Calibrating tests. Please wait...', if self.verbose: print + print print 'Test min max' print '-' * LINE tests = self.tests.items() @@ -514,6 +515,11 @@ (name, min(test.overhead_times) * MILLI_SECONDS, max(test.overhead_times) * MILLI_SECONDS) + if self.verbose: + print + print 'Done with the calibration.' + else: + print 'done.' print def run(self): @@ -830,7 +836,9 @@ print '-' * LINE print 'PYBENCH %s' % __version__ print '-' * LINE - print '* using Python %s' % (string.split(sys.version)[0]) + print '* using %s %s' % ( + platform.python_implementation(), + string.join(string.split(sys.version), ' ')) # Switch off garbage collection if not withgc: @@ -839,15 +847,23 @@ except ImportError: print '* Python version doesn\'t support garbage collection' else: - gc.disable() - print '* disabled garbage collection' + try: + gc.disable() + except NotImplementedError: + print '* Python version doesn\'t support gc.disable' + else: + print '* disabled garbage collection' # "Disable" sys check interval if not withsyscheck: # Too bad the check interval uses an int instead of a long... value = 2147483647 - sys.setcheckinterval(value) - print '* system check interval set to maximum: %s' % value + try: + sys.setcheckinterval(value) + except (AttributeError, NotImplementedError): + print '* Python version doesn\'t support sys.setcheckinterval' + else: + print '* system check interval set to maximum: %s' % value if timer == TIMER_SYSTIMES_PROCESSTIME: import systimes From python-3000-checkins at python.org Mon Jan 15 17:59:26 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 17:59:26 +0100 (CET) Subject: [Python-3000-checkins] r53452 - in python/branches/p3yk: Lib/BaseHTTPServer.py Lib/UserString.py Lib/aifc.py Lib/asynchat.py Lib/base64.py Lib/copy.py Lib/csv.py Lib/ctypes/__init__.py Lib/ctypes/test/test_as_parameter.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_pointers.py Lib/ctypes/test/test_prototypes.py Lib/decimal.py Lib/dis.py Lib/email/test/test_email_codecs.py Lib/email/test/test_email_codecs_renamed.py Lib/ftplib.py Lib/gettext.py Lib/gzip.py Lib/imputil.py Lib/logging/__init__.py Lib/mailbox.py Lib/msilib/__init__.py Lib/optparse.py Lib/pickle.py Lib/pickletools.py Lib/plat-aix3/IN.py Lib/plat-aix4/IN.py Lib/plat-atheos/IN.py Lib/plat-atheos/TYPES.py Lib/plat-beos5/IN.py Lib/plat-freebsd2/IN.py Lib/plat-freebsd3/IN.py Lib/plat-irix5/IN.py Lib/plat-irix6/FILE.py Lib/plat-irix6/IN.py Lib/plat-irix6/WAIT.py Lib/plat-linux2/DLFCN.py Lib/plat-linux2/IN.py Lib/plat-linux2/TYPES.py Lib/plat-mac/Carbon/CarbonEvents.py Lib/plat-mac/Carbon/Components.py Lib/plat-mac/Carbon/Controls.py Lib/plat-mac/Carbon/Dragconst.py Lib/plat-mac/Carbon/Folders.py Lib/plat-mac/Carbon/Fonts.py Lib/plat-mac/Carbon/Icons.py Lib/plat-mac/Carbon/MacTextEditor.py Lib/plat-mac/Carbon/OSAconst.py Lib/plat-mac/Carbon/QDOffscreen.py Lib/plat-mac/Carbon/QuickDraw.py Lib/plat-mac/Carbon/QuickTime.py Lib/plat-mac/Carbon/Sound.py Lib/plat-mac/Carbon/Windows.py Lib/plat-mac/aepack.py Lib/plat-mac/macfs.py Lib/plat-mac/pimp.py Lib/plat-os2emx/IN.py Lib/plat-sunos5/IN.py Lib/plat-sunos5/STROPTS.py Lib/plat-sunos5/TYPES.py Lib/plat-unixware7/IN.py Lib/plat-unixware7/STROPTS.py Lib/platform.py Lib/py_compile.py Lib/random.py Lib/sre_compile.py Lib/sre_parse.py Lib/string.py Lib/stringold.py Lib/subprocess.py Lib/sunau.py Lib/tarfile.py Lib/test/list_tests.py Lib/test/mapping_tests.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/seq_tests.py Lib/test/string_tests.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asynchat.py Lib/test/test_bigmem.py Lib/test/test_binop.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_class.py Lib/test/test_code.py Lib/test/test_compare.py Lib/test/test_compile.py Lib/test/test_complex.py Lib/test/test_cookielib.py Lib/test/test_copy.py Lib/test/test_copy_reg.py Lib/test/test_datetime.py Lib/test/test_decimal.py Lib/test/test_descr.py Lib/test/test_dict.py Lib/test/test_format.py Lib/test/test_functools.py Lib/test/test_generators.py Lib/test/test_getargs2.py Lib/test/test_grammar.py Lib/test/test_hash.py Lib/test/test_hexoct.py Lib/test/test_index.py Lib/test/test_isinstance.py Lib/test/test_largefile.py Lib/test/test_long.py Lib/test/test_long_future.py Lib/test/test_marshal.py Lib/test/test_multibytecodec_support.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_poll.py Lib/test/test_pow.py Lib/test/test_pprint.py Lib/test/test_random.py Lib/test/test_repr.py Lib/test/test_resource.py Lib/test/test_slice.py Lib/test/test_socket.py Lib/test/test_strftime.py Lib/test/test_string.py Lib/test/test_strop.py Lib/test/test_struct.py Lib/test/test_time.py Lib/test/test_timeout.py Lib/test/test_types.py Lib/test/test_unary.py Lib/test/test_unicode.py Lib/test/test_uuid.py Lib/test/test_xdrlib.py Lib/test/test_xmlrpc.py Lib/test/test_xrange.py Lib/test/test_zipimport.py Lib/test/test_zlib.py Lib/types.py Lib/uuid.py Lib/xdrlib.py Lib/xml/dom/NodeFilter.py Lib/xmlrpclib.py Lib/zipfile.py Parser/tokenizer.c Python/bltinmodule.c Message-ID: <20070115165926.743191E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 17:59:06 2007 New Revision: 53452 Modified: python/branches/p3yk/Lib/BaseHTTPServer.py python/branches/p3yk/Lib/UserString.py python/branches/p3yk/Lib/aifc.py python/branches/p3yk/Lib/asynchat.py python/branches/p3yk/Lib/base64.py python/branches/p3yk/Lib/copy.py python/branches/p3yk/Lib/csv.py python/branches/p3yk/Lib/ctypes/__init__.py python/branches/p3yk/Lib/ctypes/test/test_as_parameter.py python/branches/p3yk/Lib/ctypes/test/test_functions.py python/branches/p3yk/Lib/ctypes/test/test_numbers.py python/branches/p3yk/Lib/ctypes/test/test_pointers.py python/branches/p3yk/Lib/ctypes/test/test_prototypes.py python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/dis.py python/branches/p3yk/Lib/email/test/test_email_codecs.py python/branches/p3yk/Lib/email/test/test_email_codecs_renamed.py python/branches/p3yk/Lib/ftplib.py python/branches/p3yk/Lib/gettext.py python/branches/p3yk/Lib/gzip.py python/branches/p3yk/Lib/imputil.py python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/msilib/__init__.py python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Lib/pickle.py python/branches/p3yk/Lib/pickletools.py python/branches/p3yk/Lib/plat-aix3/IN.py python/branches/p3yk/Lib/plat-aix4/IN.py python/branches/p3yk/Lib/plat-atheos/IN.py python/branches/p3yk/Lib/plat-atheos/TYPES.py python/branches/p3yk/Lib/plat-beos5/IN.py python/branches/p3yk/Lib/plat-freebsd2/IN.py python/branches/p3yk/Lib/plat-freebsd3/IN.py python/branches/p3yk/Lib/plat-irix5/IN.py python/branches/p3yk/Lib/plat-irix6/FILE.py python/branches/p3yk/Lib/plat-irix6/IN.py python/branches/p3yk/Lib/plat-irix6/WAIT.py python/branches/p3yk/Lib/plat-linux2/DLFCN.py python/branches/p3yk/Lib/plat-linux2/IN.py python/branches/p3yk/Lib/plat-linux2/TYPES.py python/branches/p3yk/Lib/plat-mac/Carbon/CarbonEvents.py python/branches/p3yk/Lib/plat-mac/Carbon/Components.py python/branches/p3yk/Lib/plat-mac/Carbon/Controls.py python/branches/p3yk/Lib/plat-mac/Carbon/Dragconst.py python/branches/p3yk/Lib/plat-mac/Carbon/Folders.py python/branches/p3yk/Lib/plat-mac/Carbon/Fonts.py python/branches/p3yk/Lib/plat-mac/Carbon/Icons.py python/branches/p3yk/Lib/plat-mac/Carbon/MacTextEditor.py python/branches/p3yk/Lib/plat-mac/Carbon/OSAconst.py python/branches/p3yk/Lib/plat-mac/Carbon/QDOffscreen.py python/branches/p3yk/Lib/plat-mac/Carbon/QuickDraw.py python/branches/p3yk/Lib/plat-mac/Carbon/QuickTime.py python/branches/p3yk/Lib/plat-mac/Carbon/Sound.py python/branches/p3yk/Lib/plat-mac/Carbon/Windows.py python/branches/p3yk/Lib/plat-mac/aepack.py python/branches/p3yk/Lib/plat-mac/macfs.py python/branches/p3yk/Lib/plat-mac/pimp.py python/branches/p3yk/Lib/plat-os2emx/IN.py python/branches/p3yk/Lib/plat-sunos5/IN.py python/branches/p3yk/Lib/plat-sunos5/STROPTS.py python/branches/p3yk/Lib/plat-sunos5/TYPES.py python/branches/p3yk/Lib/plat-unixware7/IN.py python/branches/p3yk/Lib/plat-unixware7/STROPTS.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/py_compile.py python/branches/p3yk/Lib/random.py python/branches/p3yk/Lib/sre_compile.py python/branches/p3yk/Lib/sre_parse.py python/branches/p3yk/Lib/string.py python/branches/p3yk/Lib/stringold.py python/branches/p3yk/Lib/subprocess.py python/branches/p3yk/Lib/sunau.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/list_tests.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/pickletester.py python/branches/p3yk/Lib/test/regrtest.py python/branches/p3yk/Lib/test/seq_tests.py python/branches/p3yk/Lib/test/string_tests.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_ast.py python/branches/p3yk/Lib/test/test_asynchat.py python/branches/p3yk/Lib/test/test_bigmem.py python/branches/p3yk/Lib/test/test_binop.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_code.py python/branches/p3yk/Lib/test/test_compare.py python/branches/p3yk/Lib/test/test_compile.py python/branches/p3yk/Lib/test/test_complex.py python/branches/p3yk/Lib/test/test_cookielib.py python/branches/p3yk/Lib/test/test_copy.py python/branches/p3yk/Lib/test/test_copy_reg.py python/branches/p3yk/Lib/test/test_datetime.py python/branches/p3yk/Lib/test/test_decimal.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Lib/test/test_format.py python/branches/p3yk/Lib/test/test_functools.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_getargs2.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_hash.py python/branches/p3yk/Lib/test/test_hexoct.py python/branches/p3yk/Lib/test/test_index.py python/branches/p3yk/Lib/test/test_isinstance.py python/branches/p3yk/Lib/test/test_largefile.py python/branches/p3yk/Lib/test/test_long.py python/branches/p3yk/Lib/test/test_long_future.py python/branches/p3yk/Lib/test/test_marshal.py python/branches/p3yk/Lib/test/test_multibytecodec_support.py python/branches/p3yk/Lib/test/test_operator.py python/branches/p3yk/Lib/test/test_optparse.py python/branches/p3yk/Lib/test/test_poll.py python/branches/p3yk/Lib/test/test_pow.py python/branches/p3yk/Lib/test/test_pprint.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Lib/test/test_repr.py python/branches/p3yk/Lib/test/test_resource.py python/branches/p3yk/Lib/test/test_slice.py python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Lib/test/test_strftime.py python/branches/p3yk/Lib/test/test_string.py python/branches/p3yk/Lib/test/test_strop.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_time.py python/branches/p3yk/Lib/test/test_timeout.py python/branches/p3yk/Lib/test/test_types.py python/branches/p3yk/Lib/test/test_unary.py python/branches/p3yk/Lib/test/test_unicode.py python/branches/p3yk/Lib/test/test_uuid.py python/branches/p3yk/Lib/test/test_xdrlib.py python/branches/p3yk/Lib/test/test_xmlrpc.py python/branches/p3yk/Lib/test/test_xrange.py python/branches/p3yk/Lib/test/test_zipimport.py python/branches/p3yk/Lib/test/test_zlib.py python/branches/p3yk/Lib/types.py python/branches/p3yk/Lib/uuid.py python/branches/p3yk/Lib/xdrlib.py python/branches/p3yk/Lib/xml/dom/NodeFilter.py python/branches/p3yk/Lib/xmlrpclib.py python/branches/p3yk/Lib/zipfile.py python/branches/p3yk/Parser/tokenizer.c python/branches/p3yk/Python/bltinmodule.c Log: Rip out 'long' and 'L'-suffixed integer literals. (Rough first cut.) Modified: python/branches/p3yk/Lib/BaseHTTPServer.py ============================================================================== --- python/branches/p3yk/Lib/BaseHTTPServer.py (original) +++ python/branches/p3yk/Lib/BaseHTTPServer.py Mon Jan 15 17:59:06 2007 @@ -331,12 +331,12 @@ """ try: - short, long = self.responses[code] + shortmsg, longmsg = self.responses[code] except KeyError: - short, long = '???', '???' + shortmsg, longmsg = '???', '???' if message is None: - message = short - explain = long + message = shortmsg + explain = longmsg self.log_error("code %d, message %s", code, message) # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201) content = (self.error_message_format % Modified: python/branches/p3yk/Lib/UserString.py ============================================================================== --- python/branches/p3yk/Lib/UserString.py (original) +++ python/branches/p3yk/Lib/UserString.py Mon Jan 15 17:59:06 2007 @@ -20,7 +20,7 @@ def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def __int__(self): return int(self.data) - def __long__(self): return long(self.data) + def __long__(self): return int(self.data) def __float__(self): return float(self.data) def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) Modified: python/branches/p3yk/Lib/aifc.py ============================================================================== --- python/branches/p3yk/Lib/aifc.py (original) +++ python/branches/p3yk/Lib/aifc.py Mon Jan 15 17:59:06 2007 @@ -142,7 +142,7 @@ class Error(Exception): pass -_AIFC_version = 0xA2805140L # Version 1 of AIFF-C +_AIFC_version = 0xA2805140 # Version 1 of AIFF-C _skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \ 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO' @@ -191,7 +191,7 @@ f = _HUGE_VAL else: expon = expon - 16383 - f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63) + f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63) return sign * f def _write_short(f, x): @@ -233,10 +233,10 @@ expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) - himant = long(fsmant) + himant = int(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) - lomant = long(fsmant) + lomant = int(fsmant) _write_short(f, expon) _write_long(f, himant) _write_long(f, lomant) Modified: python/branches/p3yk/Lib/asynchat.py ============================================================================== --- python/branches/p3yk/Lib/asynchat.py (original) +++ python/branches/p3yk/Lib/asynchat.py Mon Jan 15 17:59:06 2007 @@ -105,7 +105,7 @@ # no terminator, collect it all self.collect_incoming_data (self.ac_in_buffer) self.ac_in_buffer = '' - elif isinstance(terminator, int) or isinstance(terminator, long): + elif isinstance(terminator, int) or isinstance(terminator, int): # numeric terminator n = terminator if lb < n: Modified: python/branches/p3yk/Lib/base64.py ============================================================================== --- python/branches/p3yk/Lib/base64.py (original) +++ python/branches/p3yk/Lib/base64.py Mon Jan 15 17:59:06 2007 @@ -129,7 +129,7 @@ _b32tab = _b32alphabet.items() _b32tab.sort() _b32tab = [v for k, v in _b32tab] -_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()]) +_b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()]) def b32encode(s): Modified: python/branches/p3yk/Lib/copy.py ============================================================================== --- python/branches/p3yk/Lib/copy.py (original) +++ python/branches/p3yk/Lib/copy.py Mon Jan 15 17:59:06 2007 @@ -99,7 +99,7 @@ def _copy_immutable(x): return x -for t in (type(None), int, long, float, bool, str, tuple, +for t in (type(None), int, int, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType, types.FunctionType): @@ -178,7 +178,7 @@ return x d[type(None)] = _deepcopy_atomic d[int] = _deepcopy_atomic -d[long] = _deepcopy_atomic +d[int] = _deepcopy_atomic d[float] = _deepcopy_atomic d[bool] = _deepcopy_atomic try: @@ -315,7 +315,7 @@ pass def _test(): - l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], + l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'], {'abc': 'ABC'}, (), [], {}] l1 = copy(l) print l1==l Modified: python/branches/p3yk/Lib/csv.py ============================================================================== --- python/branches/p3yk/Lib/csv.py (original) +++ python/branches/p3yk/Lib/csv.py Mon Jan 15 17:59:06 2007 @@ -369,7 +369,7 @@ for col in columnTypes.keys(): - for thisType in [int, long, float, complex]: + for thisType in [int, int, float, complex]: try: thisType(row[col]) break @@ -380,7 +380,7 @@ thisType = len(row[col]) # treat longs as ints - if thisType == long: + if thisType == int: thisType = int if thisType != columnTypes[col]: Modified: python/branches/p3yk/Lib/ctypes/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/__init__.py Mon Jan 15 17:59:06 2007 @@ -66,7 +66,7 @@ buf = buftype() buf.value = init return buf - elif isinstance(init, (int, long)): + elif isinstance(init, (int, int)): buftype = c_char * init buf = buftype() return buf @@ -285,7 +285,7 @@ buf = buftype() buf.value = init return buf - elif isinstance(init, (int, long)): + elif isinstance(init, (int, int)): buftype = c_wchar * init buf = buftype() return buf @@ -356,7 +356,7 @@ def __getitem__(self, name_or_ordinal): func = self._FuncPtr((name_or_ordinal, self)) - if not isinstance(name_or_ordinal, (int, long)): + if not isinstance(name_or_ordinal, (int, int)): func.__name__ = name_or_ordinal return func Modified: python/branches/p3yk/Lib/ctypes/test/test_as_parameter.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_as_parameter.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_as_parameter.py Mon Jan 15 17:59:06 2007 @@ -133,7 +133,7 @@ f.argtypes = [c_longlong, MyCallback] def callback(value): - self.failUnless(isinstance(value, (int, long))) + self.failUnless(isinstance(value, (int, int))) return value & 0x7FFFFFFF cb = MyCallback(callback) Modified: python/branches/p3yk/Lib/ctypes/test/test_functions.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_functions.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_functions.py Mon Jan 15 17:59:06 2007 @@ -291,7 +291,7 @@ f.argtypes = [c_longlong, MyCallback] def callback(value): - self.failUnless(isinstance(value, (int, long))) + self.failUnless(isinstance(value, (int, int))) return value & 0x7FFFFFFF cb = MyCallback(callback) Modified: python/branches/p3yk/Lib/ctypes/test/test_numbers.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_numbers.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_numbers.py Mon Jan 15 17:59:06 2007 @@ -93,7 +93,7 @@ for t in float_types: self.failUnlessEqual(t(2.0).value, 2.0) self.failUnlessEqual(t(2).value, 2.0) - self.failUnlessEqual(t(2L).value, 2.0) + self.failUnlessEqual(t(2).value, 2.0) def test_integers(self): # integers cannot be constructed from floats Modified: python/branches/p3yk/Lib/ctypes/test/test_pointers.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_pointers.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_pointers.py Mon Jan 15 17:59:06 2007 @@ -5,8 +5,8 @@ ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float] -python_types = [int, int, int, int, int, long, - int, long, long, long, float, float] +python_types = [int, int, int, int, int, int, + int, int, int, int, float, float] class PointersTestCase(unittest.TestCase): @@ -160,16 +160,16 @@ def test_c_void_p(self): # http://sourceforge.net/tracker/?func=detail&aid=1518190&group_id=5470&atid=105470 if sizeof(c_void_p) == 4: - self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value, + self.failUnlessEqual(c_void_p(0xFFFFFFFF).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, + self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) elif sizeof(c_void_p) == 8: - self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value, - 0xFFFFFFFFL) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, + self.failUnlessEqual(c_void_p(0xFFFFFFFF).value, + 0xFFFFFFFF) + self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) - self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFFL).value, + self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFF).value, c_void_p(-1).value) self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted Modified: python/branches/p3yk/Lib/ctypes/test/test_prototypes.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_prototypes.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_prototypes.py Mon Jan 15 17:59:06 2007 @@ -33,7 +33,7 @@ # View the bits in `a` as unsigned instead. import struct num_bits = struct.calcsize("P") * 8 # num bits in native machine address - a += 1L << num_bits + a += 1 << num_bits assert a >= 0 return a Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Mon Jan 15 17:59:06 2007 @@ -545,7 +545,7 @@ return self # From an integer - if isinstance(value, (int,long)): + if isinstance(value, (int,int)): if value >= 0: self._sign = 0 else: @@ -561,7 +561,7 @@ if value[0] not in (0,1): raise ValueError, 'Invalid sign' for digit in value[1]: - if not isinstance(digit, (int,long)) or digit < 0: + if not isinstance(digit, (int,int)) or digit < 0: raise ValueError, "The second value in the tuple must be composed of non negative integer elements." self._sign = value[0] @@ -740,32 +740,32 @@ return 1 def __eq__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) == 0 def __ne__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) != 0 def __lt__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) < 0 def __le__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) <= 0 def __gt__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) > 0 def __ge__(self, other): - if not isinstance(other, (Decimal, int, long)): + if not isinstance(other, (Decimal, int, int)): return NotImplemented return self.__cmp__(other) >= 0 @@ -1529,7 +1529,7 @@ Equivalent to long(int(self)) """ - return long(self.__int__()) + return int(self.__int__()) def _fix(self, context): """Round if it is necessary to keep self within prec precision. @@ -2986,7 +2986,7 @@ """ if isinstance(other, Decimal): return other - if isinstance(other, (int, long)): + if isinstance(other, (int, int)): return Decimal(other) return NotImplemented Modified: python/branches/p3yk/Lib/dis.py ============================================================================== --- python/branches/p3yk/Lib/dis.py (original) +++ python/branches/p3yk/Lib/dis.py Mon Jan 15 17:59:06 2007 @@ -86,7 +86,7 @@ extended_arg = 0 i = i+2 if op == EXTENDED_ARG: - extended_arg = oparg*65536L + extended_arg = oparg*65536 print repr(oparg).rjust(5), if op in hasconst: print '(' + repr(co.co_consts[oparg]) + ')', Modified: python/branches/p3yk/Lib/email/test/test_email_codecs.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email_codecs.py (original) +++ python/branches/p3yk/Lib/email/test/test_email_codecs.py Mon Jan 15 17:59:06 2007 @@ -41,8 +41,8 @@ [('Hello World!', None), ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')]) - long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' - h = Header(long, j, header_name="Subject") + int = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' + h = Header(int, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding @@ -50,7 +50,7 @@ =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison - eq(h.__unicode__().encode('euc-jp'), long) + eq(h.__unicode__().encode('euc-jp'), int) def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' Modified: python/branches/p3yk/Lib/email/test/test_email_codecs_renamed.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email_codecs_renamed.py (original) +++ python/branches/p3yk/Lib/email/test/test_email_codecs_renamed.py Mon Jan 15 17:59:06 2007 @@ -41,8 +41,8 @@ [('Hello World!', None), ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')]) - long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' - h = Header(long, j, header_name="Subject") + int = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' + h = Header(int, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding @@ -50,7 +50,7 @@ =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison - eq(h.__unicode__().encode('euc-jp'), long) + eq(h.__unicode__().encode('euc-jp'), int) def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' Modified: python/branches/p3yk/Lib/ftplib.py ============================================================================== --- python/branches/p3yk/Lib/ftplib.py (original) +++ python/branches/p3yk/Lib/ftplib.py Mon Jan 15 17:59:06 2007 @@ -514,7 +514,7 @@ try: return int(s) except (OverflowError, ValueError): - return long(s) + return int(s) def mkd(self, dirname): '''Make a directory, return its full pathname.''' @@ -564,7 +564,7 @@ try: return int(s) except (OverflowError, ValueError): - return long(s) + return int(s) _227_re = None Modified: python/branches/p3yk/Lib/gettext.py ============================================================================== --- python/branches/p3yk/Lib/gettext.py (original) +++ python/branches/p3yk/Lib/gettext.py Mon Jan 15 17:59:06 2007 @@ -256,8 +256,8 @@ class GNUTranslations(NullTranslations): # Magic number of .mo files - LE_MAGIC = 0x950412deL - BE_MAGIC = 0xde120495L + LE_MAGIC = 0x950412de + BE_MAGIC = 0xde120495 def _parse(self, fp): """Override this method to support alternative .mo formats.""" Modified: python/branches/p3yk/Lib/gzip.py ============================================================================== --- python/branches/p3yk/Lib/gzip.py (original) +++ python/branches/p3yk/Lib/gzip.py Mon Jan 15 17:59:06 2007 @@ -21,12 +21,12 @@ If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: - i += 1L << 32 + i += 1 << 32 return i def LOWU32(i): """Return the low-order 32 bits of an int, as a non-negative int.""" - return i & 0xFFFFFFFFL + return i & 0xFFFFFFFF def write32(output, value): output.write(struct.pack(">> encode_long(0L) + >>> encode_long(0) '' - >>> encode_long(255L) + >>> encode_long(255) '\xff\x00' - >>> encode_long(32767L) + >>> encode_long(32767) '\xff\x7f' - >>> encode_long(-256L) + >>> encode_long(-256) '\x00\xff' - >>> encode_long(-32768L) + >>> encode_long(-32768) '\x00\x80' - >>> encode_long(-128L) + >>> encode_long(-128) '\x80' - >>> encode_long(127L) + >>> encode_long(127) '\x7f' >>> """ @@ -1284,7 +1284,7 @@ # Extend to a full byte. nibbles += 1 nbits = nibbles * 4 - x += 1L << nbits + x += 1 << nbits assert x > 0 ashex = hex(x) njunkchars = 2 + ashex.endswith('L') @@ -1324,11 +1324,11 @@ nbytes = len(data) if nbytes == 0: - return 0L + return 0 ashex = _binascii.hexlify(data[::-1]) - n = long(ashex, 16) # quadratic time before Python 2.3; linear now + n = int(ashex, 16) # quadratic time before Python 2.3; linear now if data[-1] >= '\x80': - n -= 1L << (nbytes * 8) + n -= 1 << (nbytes * 8) return n # Shorthands Modified: python/branches/p3yk/Lib/pickletools.py ============================================================================== --- python/branches/p3yk/Lib/pickletools.py (original) +++ python/branches/p3yk/Lib/pickletools.py Mon Jan 15 17:59:06 2007 @@ -511,7 +511,7 @@ try: return int(s) except OverflowError: - return long(s) + return int(s) def read_decimalnl_long(f): r""" @@ -525,7 +525,7 @@ """ s = read_stringnl(f, decode=False, stripquotes=False) - return long(s) + return int(s) decimalnl_short = ArgumentDescriptor( @@ -676,7 +676,7 @@ This first reads four bytes as a signed size (but requires the size to be >= 0), then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken - as a shortcut for the long 0L, although LONG1 should really be used + as a shortcut for the int 0, although LONG1 should really be used then instead (and in any case where # of bytes < 256). """) @@ -724,12 +724,12 @@ pylong = StackObject( name='long', - obtype=long, + obtype=int, doc="A long (as opposed to short) Python integer object.") pyinteger_or_bool = StackObject( name='int_or_bool', - obtype=(int, long, bool), + obtype=(int, int, bool), doc="A Python integer object (short or long), or " "a Python bool.") Modified: python/branches/p3yk/Lib/plat-aix3/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-aix3/IN.py (original) +++ python/branches/p3yk/Lib/plat-aix3/IN.py Mon Jan 15 17:59:06 2007 @@ -86,30 +86,30 @@ IPPORT_RESERVED = 1024 IPPORT_USERRESERVED = 5000 IPPORT_TIMESERVER = 37 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_LOOPBACK = 0x7f000001 Modified: python/branches/p3yk/Lib/plat-aix4/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-aix4/IN.py (original) +++ python/branches/p3yk/Lib/plat-aix4/IN.py Mon Jan 15 17:59:06 2007 @@ -111,24 +111,24 @@ IPPORT_RESERVED = 1024 IPPORT_USERRESERVED = 5000 IPPORT_TIMESERVER = 37 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) def IN_MULTICAST(i): return IN_CLASSD(i) @@ -138,9 +138,9 @@ INADDR_UNSPEC_GROUP = 0xe0000000 INADDR_ALLHOSTS_GROUP = 0xe0000001 INADDR_MAX_LOCAL_GROUP = 0xe00000ff -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_BROADCAST = 0xffffffff Modified: python/branches/p3yk/Lib/plat-atheos/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-atheos/IN.py (original) +++ python/branches/p3yk/Lib/plat-atheos/IN.py Mon Jan 15 17:59:06 2007 @@ -7,7 +7,7 @@ __FAVOR_BSD = 1 _ISOC9X_SOURCE = 1 _POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _XOPEN_SOURCE = 500 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 @@ -18,7 +18,7 @@ __USE_ISOC9X = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 @@ -110,8 +110,8 @@ CHAR_MIN = (-128) INT_MAX = 2147483647 INT_MIN = (-2147483647-1) -LONG_MAX = 2147483647L -LONG_MIN = (-2147483647L-1L) +LONG_MAX = 2147483647 +LONG_MIN = (-2147483647-1) SCHAR_MAX = 127 SCHAR_MIN = (-128) SHRT_MAX = 32767 @@ -206,10 +206,10 @@ INT_MIN = (-INT_MAX - 1) INT_MAX = 2147483647 UINT_MAX = 4294967295 -LONG_MAX = 9223372036854775807L -LONG_MAX = 2147483647L -LONG_MIN = (-LONG_MAX - 1L) -ULONG_MAX = 4294967295L +LONG_MAX = 9223372036854775807 +LONG_MAX = 2147483647 +LONG_MIN = (-LONG_MAX - 1) +ULONG_MAX = 4294967295 # Included from stdint.h _STDINT_H = 1 @@ -243,27 +243,27 @@ INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) INT_FAST8_MIN = (-128) -INT_FAST16_MIN = (-9223372036854775807L-1) -INT_FAST32_MIN = (-9223372036854775807L-1) +INT_FAST16_MIN = (-9223372036854775807-1) +INT_FAST32_MIN = (-9223372036854775807-1) INT_FAST16_MIN = (-2147483647-1) INT_FAST32_MIN = (-2147483647-1) INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) INT_FAST8_MAX = (127) -INT_FAST16_MAX = (9223372036854775807L) -INT_FAST32_MAX = (9223372036854775807L) +INT_FAST16_MAX = (9223372036854775807) +INT_FAST32_MAX = (9223372036854775807) INT_FAST16_MAX = (2147483647) INT_FAST32_MAX = (2147483647) INT_FAST64_MAX = (__INT64_C(9223372036854775807)) UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) -INTPTR_MIN = (-9223372036854775807L-1) -INTPTR_MAX = (9223372036854775807L) +INTPTR_MIN = (-9223372036854775807-1) +INTPTR_MAX = (9223372036854775807) INTPTR_MIN = (-2147483647-1) INTPTR_MAX = (2147483647) INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) INTMAX_MAX = (__INT64_C(9223372036854775807)) UINTMAX_MAX = (__UINT64_C(18446744073709551615)) -PTRDIFF_MIN = (-9223372036854775807L-1) -PTRDIFF_MAX = (9223372036854775807L) +PTRDIFF_MIN = (-9223372036854775807-1) +PTRDIFF_MAX = (9223372036854775807) PTRDIFF_MIN = (-2147483647-1) PTRDIFF_MAX = (2147483647) SIG_ATOMIC_MIN = (-2147483647-1) @@ -684,7 +684,7 @@ INADDR_ANY = 0x00000000 INADDR_BROADCAST = 0xffffffff INADDR_LOOPBACK = 0x7f000001 -def CMSG_ALIGN(len): return ( ((len)+sizeof(long)-1) & ~(sizeof(long)-1) ) +def CMSG_ALIGN(len): return ( ((len)+sizeof(int)-1) & ~(sizeof(int)-1) ) PROT_SOCK = 1024 SHUTDOWN_MASK = 3 Modified: python/branches/p3yk/Lib/plat-atheos/TYPES.py ============================================================================== --- python/branches/p3yk/Lib/plat-atheos/TYPES.py (original) +++ python/branches/p3yk/Lib/plat-atheos/TYPES.py Mon Jan 15 17:59:06 2007 @@ -7,7 +7,7 @@ __FAVOR_BSD = 1 _ISOC9X_SOURCE = 1 _POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _XOPEN_SOURCE = 500 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 @@ -18,7 +18,7 @@ __USE_ISOC9X = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 Modified: python/branches/p3yk/Lib/plat-beos5/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-beos5/IN.py (original) +++ python/branches/p3yk/Lib/plat-beos5/IN.py Mon Jan 15 17:59:06 2007 @@ -34,7 +34,7 @@ # Included from null.h NULL = (0) -NULL = 0L +NULL = 0 # Included from size_t.h @@ -100,8 +100,8 @@ MB_LEN_MAX = (1) SHRT_MIN = (-32767-1) SHRT_MAX = (32767) -LONG_MIN = (-2147483647L-1) -LONG_MAX = (2147483647L) +LONG_MIN = (-2147483647-1) +LONG_MAX = (2147483647) INT_MIN = LONG_MIN INT_MAX = LONG_MAX ARG_MAX = (32768) @@ -118,7 +118,7 @@ OPEN_MAX = (128) PATH_MAX = (1024) PIPE_MAX = (512) -SSIZE_MAX = (2147483647L) +SSIZE_MAX = (2147483647) TTY_NAME_MAX = (256) TZNAME_MAX = (32) SYMLINKS_MAX = (16) @@ -133,7 +133,7 @@ _POSIX_OPEN_MAX = (128) _POSIX_PATH_MAX = (1024) _POSIX_PIPE_BUF = (512) -_POSIX_SSIZE_MAX = (2147483647L) +_POSIX_SSIZE_MAX = (2147483647) _POSIX_STREAM_MAX = (8) _POSIX_TTY_NAME_MAX = (256) _POSIX_TZNAME_MAX = (3) Modified: python/branches/p3yk/Lib/plat-freebsd2/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-freebsd2/IN.py (original) +++ python/branches/p3yk/Lib/plat-freebsd2/IN.py Mon Jan 15 17:59:06 2007 @@ -101,33 +101,33 @@ IPPORT_HIFIRSTAUTO = 40000 IPPORT_HILASTAUTO = 44999 IPPORT_RESERVEDSTART = 600 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_BROADCAST = 0xffffffff Modified: python/branches/p3yk/Lib/plat-freebsd3/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-freebsd3/IN.py (original) +++ python/branches/p3yk/Lib/plat-freebsd3/IN.py Mon Jan 15 17:59:06 2007 @@ -101,33 +101,33 @@ IPPORT_HIFIRSTAUTO = 49152 IPPORT_HILASTAUTO = 65535 IPPORT_RESERVEDSTART = 600 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_LOOPBACK = 0x7f000001 Modified: python/branches/p3yk/Lib/plat-irix5/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix5/IN.py (original) +++ python/branches/p3yk/Lib/plat-irix5/IN.py Mon Jan 15 17:59:06 2007 @@ -61,33 +61,33 @@ IPPORT_RESERVED = 1024 IPPORT_USERRESERVED = 5000 IPPORT_MAXPORT = 65535 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_BROADCAST = 0xffffffff Modified: python/branches/p3yk/Lib/plat-irix6/FILE.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/FILE.py (original) +++ python/branches/p3yk/Lib/plat-irix6/FILE.py Mon Jan 15 17:59:06 2007 @@ -43,7 +43,7 @@ __NBBY = 8 # Included from string.h -NULL = 0L +NULL = 0 NBBY = 8 # Included from sys/cpumask.h @@ -332,9 +332,9 @@ SV_ONSTACK = 0x0001 SV_INTERRUPT = 0x0002 NUMBSDSIGS = (32) -def sigmask(sig): return (1L << ((sig)-1)) +def sigmask(sig): return (1 << ((sig)-1)) -def sigmask(sig): return (1L << ((sig)-1)) +def sigmask(sig): return (1 << ((sig)-1)) SIG_ERR = (-1) SIG_IGN = (1) @@ -356,7 +356,7 @@ BRK_PSEUDO_OP_MAX = 0x3 BRK_CACHE_SYNC = 0x80 BRK_MULOVF = 1023 -_POSIX_VERSION = 199506L +_POSIX_VERSION = 199506 _POSIX_VERSION = 199506 _POSIX_VDISABLE = 0 MAX_INPUT = 512 @@ -414,7 +414,7 @@ CPSSHIFT = 12 CPSSHIFT = 11 BPSSHIFT = (BPCSHIFT+CPSSHIFT) -NULL = 0L +NULL = 0 CMASK = 022 NODEV = (-1) NOPAGE = (-1) @@ -464,7 +464,7 @@ def DELAYBUS(n): return us_delaybus(n) -TIMEPOKE_NOW = -100L +TIMEPOKE_NOW = -100 MUTEX_DEFAULT = 0x0 METER_NAMSZ = 16 METER_NO_SEQ = -1 Modified: python/branches/p3yk/Lib/plat-irix6/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/IN.py (original) +++ python/branches/p3yk/Lib/plat-irix6/IN.py Mon Jan 15 17:59:06 2007 @@ -37,7 +37,7 @@ __NBBY = 8 # Included from string.h -NULL = 0L +NULL = 0 NBBY = 8 # Included from sys/endian.h Modified: python/branches/p3yk/Lib/plat-irix6/WAIT.py ============================================================================== --- python/branches/p3yk/Lib/plat-irix6/WAIT.py (original) +++ python/branches/p3yk/Lib/plat-irix6/WAIT.py Mon Jan 15 17:59:06 2007 @@ -68,7 +68,7 @@ __NBBY = 8 # Included from string.h -NULL = 0L +NULL = 0 NBBY = 8 # Included from sys/procset.h @@ -286,9 +286,9 @@ SV_ONSTACK = 0x0001 SV_INTERRUPT = 0x0002 NUMBSDSIGS = (32) -def sigmask(sig): return (1L << ((sig)-1)) +def sigmask(sig): return (1 << ((sig)-1)) -def sigmask(sig): return (1L << ((sig)-1)) +def sigmask(sig): return (1 << ((sig)-1)) SIG_ERR = (-1) SIG_IGN = (1) Modified: python/branches/p3yk/Lib/plat-linux2/DLFCN.py ============================================================================== --- python/branches/p3yk/Lib/plat-linux2/DLFCN.py (original) +++ python/branches/p3yk/Lib/plat-linux2/DLFCN.py Mon Jan 15 17:59:06 2007 @@ -7,7 +7,7 @@ __FAVOR_BSD = 1 _ISOC99_SOURCE = 1 _POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _XOPEN_SOURCE = 600 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 @@ -18,7 +18,7 @@ __USE_ISOC99 = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 @@ -40,7 +40,7 @@ __USE_REENTRANT = 1 __STDC_IEC_559__ = 1 __STDC_IEC_559_COMPLEX__ = 1 -__STDC_ISO_10646__ = 200009L +__STDC_ISO_10646__ = 200009 __GNU_LIBRARY__ = 6 __GLIBC__ = 2 __GLIBC_MINOR__ = 2 Modified: python/branches/p3yk/Lib/plat-linux2/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-linux2/IN.py (original) +++ python/branches/p3yk/Lib/plat-linux2/IN.py Mon Jan 15 17:59:06 2007 @@ -7,7 +7,7 @@ __FAVOR_BSD = 1 _ISOC99_SOURCE = 1 _POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _XOPEN_SOURCE = 600 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 @@ -18,7 +18,7 @@ __USE_ISOC99 = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 @@ -40,7 +40,7 @@ __USE_REENTRANT = 1 __STDC_IEC_559__ = 1 __STDC_IEC_559_COMPLEX__ = 1 -__STDC_ISO_10646__ = 200009L +__STDC_ISO_10646__ = 200009 __GNU_LIBRARY__ = 6 __GLIBC__ = 2 __GLIBC_MINOR__ = 2 @@ -78,8 +78,8 @@ # Included from bits/wchar.h _BITS_WCHAR_H = 1 -__WCHAR_MIN = (-2147483647l - 1l) -__WCHAR_MAX = (2147483647l) +__WCHAR_MIN = (-2147483647 - 1) +__WCHAR_MAX = (2147483647) # Included from bits/wordsize.h __WORDSIZE = 32 @@ -114,28 +114,28 @@ UINT_LEAST16_MAX = (65535) UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) INT_FAST8_MIN = (-128) -INT_FAST16_MIN = (-9223372036854775807L-1) -INT_FAST32_MIN = (-9223372036854775807L-1) +INT_FAST16_MIN = (-9223372036854775807-1) +INT_FAST32_MIN = (-9223372036854775807-1) INT_FAST16_MIN = (-2147483647-1) INT_FAST32_MIN = (-2147483647-1) INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) INT_FAST8_MAX = (127) -INT_FAST16_MAX = (9223372036854775807L) -INT_FAST32_MAX = (9223372036854775807L) +INT_FAST16_MAX = (9223372036854775807) +INT_FAST32_MAX = (9223372036854775807) INT_FAST16_MAX = (2147483647) INT_FAST32_MAX = (2147483647) INT_FAST64_MAX = (__INT64_C(9223372036854775807)) UINT_FAST8_MAX = (255) UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) -INTPTR_MIN = (-9223372036854775807L-1) -INTPTR_MAX = (9223372036854775807L) +INTPTR_MIN = (-9223372036854775807-1) +INTPTR_MAX = (9223372036854775807) INTPTR_MIN = (-2147483647-1) INTPTR_MAX = (2147483647) INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) INTMAX_MAX = (__INT64_C(9223372036854775807)) UINTMAX_MAX = (__UINT64_C(18446744073709551615)) -PTRDIFF_MIN = (-9223372036854775807L-1) -PTRDIFF_MAX = (9223372036854775807L) +PTRDIFF_MIN = (-9223372036854775807-1) +PTRDIFF_MAX = (9223372036854775807) PTRDIFF_MIN = (-2147483647-1) PTRDIFF_MAX = (2147483647) SIG_ATOMIC_MIN = (-2147483647-1) @@ -238,9 +238,9 @@ SHRT_MAX = 32767 USHRT_MAX = 65535 INT_MAX = 2147483647 -LONG_MAX = 9223372036854775807L -LONG_MAX = 2147483647L -LONG_MIN = (-LONG_MAX - 1L) +LONG_MAX = 9223372036854775807 +LONG_MAX = 2147483647 +LONG_MIN = (-LONG_MAX - 1) # Included from bits/posix1_lim.h _BITS_POSIX1_LIM_H = 1 Modified: python/branches/p3yk/Lib/plat-linux2/TYPES.py ============================================================================== --- python/branches/p3yk/Lib/plat-linux2/TYPES.py (original) +++ python/branches/p3yk/Lib/plat-linux2/TYPES.py Mon Jan 15 17:59:06 2007 @@ -7,7 +7,7 @@ __FAVOR_BSD = 1 _ISOC99_SOURCE = 1 _POSIX_SOURCE = 1 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _XOPEN_SOURCE = 600 _XOPEN_SOURCE_EXTENDED = 1 _LARGEFILE64_SOURCE = 1 @@ -18,7 +18,7 @@ __USE_ISOC99 = 1 _POSIX_SOURCE = 1 _POSIX_C_SOURCE = 2 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 __USE_POSIX = 1 __USE_POSIX2 = 1 __USE_POSIX199309 = 1 @@ -40,7 +40,7 @@ __USE_REENTRANT = 1 __STDC_IEC_559__ = 1 __STDC_IEC_559_COMPLEX__ = 1 -__STDC_ISO_10646__ = 200009L +__STDC_ISO_10646__ = 200009 __GNU_LIBRARY__ = 6 __GLIBC__ = 2 __GLIBC_MINOR__ = 2 @@ -99,7 +99,7 @@ # Included from bits/time.h _BITS_TIME_H = 1 -CLOCKS_PER_SEC = 1000000l +CLOCKS_PER_SEC = 1000000 CLOCK_REALTIME = 0 CLOCK_PROCESS_CPUTIME_ID = 2 CLOCK_THREAD_CPUTIME_ID = 3 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/CarbonEvents.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/CarbonEvents.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/CarbonEvents.py Mon Jan 15 17:59:06 2007 @@ -74,8 +74,8 @@ kEventHotKeyReleased = 6 kEventKeyModifierNumLockBit = 16 kEventKeyModifierFnBit = 17 -kEventKeyModifierNumLockMask = 1L << kEventKeyModifierNumLockBit -kEventKeyModifierFnMask = 1L << kEventKeyModifierFnBit +kEventKeyModifierNumLockMask = 1 << kEventKeyModifierNumLockBit +kEventKeyModifierFnMask = 1 << kEventKeyModifierFnBit kEventAppActivated = 1 kEventAppDeactivated = 2 kEventAppQuit = 3 @@ -221,9 +221,9 @@ kHICommandPrint = FOUR_CHAR_CODE('prnt') kHICommandPageSetup = FOUR_CHAR_CODE('page') kHICommandAppHelp = FOUR_CHAR_CODE('ahlp') -kHICommandFromMenu = (1L << 0) -kHICommandFromControl = (1L << 1) -kHICommandFromWindow = (1L << 2) +kHICommandFromMenu = (1 << 0) +kHICommandFromControl = (1 << 1) +kHICommandFromWindow = (1 << 2) kEventControlInitialize = 1000 kEventControlDispose = 1001 kEventControlGetOptimalBounds = 1003 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Components.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Components.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Components.py Mon Jan 15 17:59:06 2007 @@ -8,8 +8,8 @@ kAnyComponentSubType = 0 kAnyComponentManufacturer = 0 kAnyComponentFlagsMask = 0 -cmpIsMissing = 1L << 29 -cmpWantsRegisterMessage = 1L << 31 +cmpIsMissing = 1 << 29 +cmpWantsRegisterMessage = 1 << 31 kComponentOpenSelect = -1 kComponentCloseSelect = -2 kComponentCanDoSelect = -3 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Controls.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Controls.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Controls.py Mon Jan 15 17:59:06 2007 @@ -18,7 +18,7 @@ controlNotifyClick = FOUR_CHAR_CODE('clik') controlNotifyFocus = FOUR_CHAR_CODE('focu') controlNotifyKey = FOUR_CHAR_CODE('key ') -kControlCanAutoInvalidate = 1L << 0 +kControlCanAutoInvalidate = 1 << 0 staticTextProc = 256 editTextProc = 272 iconProc = 288 @@ -529,7 +529,7 @@ kDataBrowserOrderUndefined = 0 kDataBrowserOrderIncreasing = 1 kDataBrowserOrderDecreasing = 2 -kDataBrowserNoItem = 0L +kDataBrowserNoItem = 0 kDataBrowserItemNoState = 0 # kDataBrowserItemAnyState = (unsigned long)(-1) kDataBrowserItemIsSelected = 1 << 0 @@ -569,18 +569,18 @@ kDataBrowserTargetChanged = 15 kDataBrowserUserStateChanged = 13 kDataBrowserSelectionSetChanged = 14 -kDataBrowserItemNoProperty = 0L -kDataBrowserItemIsActiveProperty = 1L -kDataBrowserItemIsSelectableProperty = 2L -kDataBrowserItemIsEditableProperty = 3L -kDataBrowserItemIsContainerProperty = 4L -kDataBrowserContainerIsOpenableProperty = 5L -kDataBrowserContainerIsClosableProperty = 6L -kDataBrowserContainerIsSortableProperty = 7L -kDataBrowserItemSelfIdentityProperty = 8L -kDataBrowserContainerAliasIDProperty = 9L -kDataBrowserColumnViewPreviewProperty = 10L -kDataBrowserItemParentContainerProperty = 11L +kDataBrowserItemNoProperty = 0 +kDataBrowserItemIsActiveProperty = 1 +kDataBrowserItemIsSelectableProperty = 2 +kDataBrowserItemIsEditableProperty = 3 +kDataBrowserItemIsContainerProperty = 4 +kDataBrowserContainerIsOpenableProperty = 5 +kDataBrowserContainerIsClosableProperty = 6 +kDataBrowserContainerIsSortableProperty = 7 +kDataBrowserItemSelfIdentityProperty = 8 +kDataBrowserContainerAliasIDProperty = 9 +kDataBrowserColumnViewPreviewProperty = 10 +kDataBrowserItemParentContainerProperty = 11 kDataBrowserCustomType = 0x3F3F3F3F kDataBrowserIconType = FOUR_CHAR_CODE('icnr') kDataBrowserTextType = FOUR_CHAR_CODE('text') @@ -591,7 +591,7 @@ kDataBrowserRelevanceRankType = FOUR_CHAR_CODE('rank') kDataBrowserPopupMenuType = FOUR_CHAR_CODE('menu') kDataBrowserIconAndTextType = FOUR_CHAR_CODE('ticn') -kDataBrowserPropertyEnclosingPart = 0L +kDataBrowserPropertyEnclosingPart = 0 kDataBrowserPropertyContentPart = FOUR_CHAR_CODE('----') kDataBrowserPropertyDisclosurePart = FOUR_CHAR_CODE('disc') kDataBrowserPropertyTextPart = kDataBrowserTextType Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Dragconst.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Dragconst.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Dragconst.py Mon Jan 15 17:59:06 2007 @@ -14,16 +14,16 @@ flavorSenderTranslated = (1 << 1) flavorNotSaved = (1 << 2) flavorSystemTranslated = (1 << 8) -kDragHasLeftSenderWindow = (1L << 0) -kDragInsideSenderApplication = (1L << 1) -kDragInsideSenderWindow = (1L << 2) +kDragHasLeftSenderWindow = (1 << 0) +kDragInsideSenderApplication = (1 << 1) +kDragInsideSenderWindow = (1 << 2) kDragBehaviorNone = 0 -kDragBehaviorZoomBackAnimation = (1L << 0) -kDragRegionAndImage = (1L << 4) -kDragStandardTranslucency = 0L -kDragDarkTranslucency = 1L -kDragDarkerTranslucency = 2L -kDragOpaqueTranslucency = 3L +kDragBehaviorZoomBackAnimation = (1 << 0) +kDragRegionAndImage = (1 << 4) +kDragStandardTranslucency = 0 +kDragDarkTranslucency = 1 +kDragDarkerTranslucency = 2 +kDragOpaqueTranslucency = 3 kDragRegionBegin = 1 kDragRegionDraw = 2 kDragRegionHide = 3 @@ -56,13 +56,13 @@ kDragTrackingInWindow = 3 kDragTrackingLeaveWindow = 4 kDragTrackingLeaveHandler = 5 -kDragActionNothing = 0L -kDragActionCopy = 1L -kDragActionAlias = (1L << 1) -kDragActionGeneric = (1L << 2) -kDragActionPrivate = (1L << 3) -kDragActionMove = (1L << 4) -kDragActionDelete = (1L << 5) +kDragActionNothing = 0 +kDragActionCopy = 1 +kDragActionAlias = (1 << 1) +kDragActionGeneric = (1 << 2) +kDragActionPrivate = (1 << 3) +kDragActionMove = (1 << 4) +kDragActionDelete = (1 << 5) # kDragActionAll = (long)0xFFFFFFFF dragHasLeftSenderWindow = kDragHasLeftSenderWindow dragInsideSenderApplication = kDragInsideSenderApplication Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Folders.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Folders.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Folders.py Mon Jan 15 17:59:06 2007 @@ -3,7 +3,7 @@ def FOUR_CHAR_CODE(x): return x true = True false = False -kOnSystemDisk = -32768L +kOnSystemDisk = -32768 kOnAppropriateDisk = -32767 kSystemDomain = -32766 kLocalDomain = -32765 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Fonts.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Fonts.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Fonts.py Mon Jan 15 17:59:06 2007 @@ -17,15 +17,15 @@ checkMark = 18 diamondMark = 19 appleMark = 20 -propFont = 36864L -prpFntH = 36865L -prpFntW = 36866L -prpFntHW = 36867L -fixedFont = 45056L -fxdFntH = 45057L -fxdFntW = 45058L -fxdFntHW = 45059L -fontWid = 44208L +propFont = 36864 +prpFntH = 36865 +prpFntW = 36866 +prpFntHW = 36867 +fixedFont = 45056 +fxdFntH = 45057 +fxdFntW = 45058 +fxdFntHW = 45059 +fontWid = 44208 kFMUseGlobalScopeOption = 0x00000001 kFontIDNewYork = 2 kFontIDGeneva = 3 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Icons.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Icons.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Icons.py Mon Jan 15 17:59:06 2007 @@ -375,7 +375,7 @@ kRightContainerArrowIcon = FOUR_CHAR_CODE('rcar') kIconServicesNormalUsageFlag = 0 kIconServicesCatalogInfoMask = (kFSCatInfoNodeID | kFSCatInfoParentDirID | kFSCatInfoVolume | kFSCatInfoNodeFlags | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo | kFSCatInfoUserAccess) -kPlotIconRefNormalFlags = 0L +kPlotIconRefNormalFlags = 0 kPlotIconRefNoImage = (1 << 1) kPlotIconRefNoMask = (1 << 2) kIconFamilyType = FOUR_CHAR_CODE('icns') Modified: python/branches/p3yk/Lib/plat-mac/Carbon/MacTextEditor.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/MacTextEditor.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/MacTextEditor.py Mon Jan 15 17:59:06 2007 @@ -17,18 +17,18 @@ normal = 0 kTXNWillDefaultToATSUIBit = 0 kTXNWillDefaultToCarbonEventBit = 1 -kTXNWillDefaultToATSUIMask = 1L << kTXNWillDefaultToATSUIBit -kTXNWillDefaultToCarbonEventMask = 1L << kTXNWillDefaultToCarbonEventBit +kTXNWillDefaultToATSUIMask = 1 << kTXNWillDefaultToATSUIBit +kTXNWillDefaultToCarbonEventMask = 1 << kTXNWillDefaultToCarbonEventBit kTXNWantMoviesBit = 0 kTXNWantSoundBit = 1 kTXNWantGraphicsBit = 2 kTXNAlwaysUseQuickDrawTextBit = 3 kTXNUseTemporaryMemoryBit = 4 -kTXNWantMoviesMask = 1L << kTXNWantMoviesBit -kTXNWantSoundMask = 1L << kTXNWantSoundBit -kTXNWantGraphicsMask = 1L << kTXNWantGraphicsBit -kTXNAlwaysUseQuickDrawTextMask = 1L << kTXNAlwaysUseQuickDrawTextBit -kTXNUseTemporaryMemoryMask = 1L << kTXNUseTemporaryMemoryBit +kTXNWantMoviesMask = 1 << kTXNWantMoviesBit +kTXNWantSoundMask = 1 << kTXNWantSoundBit +kTXNWantGraphicsMask = 1 << kTXNWantGraphicsBit +kTXNAlwaysUseQuickDrawTextMask = 1 << kTXNAlwaysUseQuickDrawTextBit +kTXNUseTemporaryMemoryMask = 1 << kTXNUseTemporaryMemoryBit kTXNDrawGrowIconBit = 0 kTXNShowWindowBit = 1 kTXNWantHScrollBarBit = 2 @@ -46,23 +46,23 @@ kTXNSingleLineOnlyBit = 14 kTXNDisableDragAndDropBit = 15 kTXNUseQDforImagingBit = 16 -kTXNDrawGrowIconMask = 1L << kTXNDrawGrowIconBit -kTXNShowWindowMask = 1L << kTXNShowWindowBit -kTXNWantHScrollBarMask = 1L << kTXNWantHScrollBarBit -kTXNWantVScrollBarMask = 1L << kTXNWantVScrollBarBit -kTXNNoTSMEverMask = 1L << kTXNNoTSMEverBit -kTXNReadOnlyMask = 1L << kTXNReadOnlyBit -kTXNNoKeyboardSyncMask = 1L << kTXNNoKeyboardSyncBit -kTXNNoSelectionMask = 1L << kTXNNoSelectionBit -kTXNSaveStylesAsSTYLResourceMask = 1L << kTXNSaveStylesAsSTYLResourceBit -kOutputTextInUnicodeEncodingMask = 1L << kOutputTextInUnicodeEncodingBit -kTXNDoNotInstallDragProcsMask = 1L << kTXNDoNotInstallDragProcsBit -kTXNAlwaysWrapAtViewEdgeMask = 1L << kTXNAlwaysWrapAtViewEdgeBit -kTXNDontDrawCaretWhenInactiveMask = 1L << kTXNDontDrawCaretWhenInactiveBit -kTXNDontDrawSelectionWhenInactiveMask = 1L << kTXNDontDrawSelectionWhenInactiveBit -kTXNSingleLineOnlyMask = 1L << kTXNSingleLineOnlyBit -kTXNDisableDragAndDropMask = 1L << kTXNDisableDragAndDropBit -kTXNUseQDforImagingMask = 1L << kTXNUseQDforImagingBit +kTXNDrawGrowIconMask = 1 << kTXNDrawGrowIconBit +kTXNShowWindowMask = 1 << kTXNShowWindowBit +kTXNWantHScrollBarMask = 1 << kTXNWantHScrollBarBit +kTXNWantVScrollBarMask = 1 << kTXNWantVScrollBarBit +kTXNNoTSMEverMask = 1 << kTXNNoTSMEverBit +kTXNReadOnlyMask = 1 << kTXNReadOnlyBit +kTXNNoKeyboardSyncMask = 1 << kTXNNoKeyboardSyncBit +kTXNNoSelectionMask = 1 << kTXNNoSelectionBit +kTXNSaveStylesAsSTYLResourceMask = 1 << kTXNSaveStylesAsSTYLResourceBit +kOutputTextInUnicodeEncodingMask = 1 << kOutputTextInUnicodeEncodingBit +kTXNDoNotInstallDragProcsMask = 1 << kTXNDoNotInstallDragProcsBit +kTXNAlwaysWrapAtViewEdgeMask = 1 << kTXNAlwaysWrapAtViewEdgeBit +kTXNDontDrawCaretWhenInactiveMask = 1 << kTXNDontDrawCaretWhenInactiveBit +kTXNDontDrawSelectionWhenInactiveMask = 1 << kTXNDontDrawSelectionWhenInactiveBit +kTXNSingleLineOnlyMask = 1 << kTXNSingleLineOnlyBit +kTXNDisableDragAndDropMask = 1 << kTXNDisableDragAndDropBit +kTXNUseQDforImagingMask = 1 << kTXNUseQDforImagingBit kTXNSetFlushnessBit = 0 kTXNSetJustificationBit = 1 kTXNUseFontFallBackBit = 2 @@ -73,29 +73,29 @@ kTXNUseCGContextRefBit = 7 kTXNImageWithQDBit = 8 kTXNDontWrapTextBit = 9 -kTXNSetFlushnessMask = 1L << kTXNSetFlushnessBit -kTXNSetJustificationMask = 1L << kTXNSetJustificationBit -kTXNUseFontFallBackMask = 1L << kTXNUseFontFallBackBit -kTXNRotateTextMask = 1L << kTXNRotateTextBit -kTXNUseVerticalTextMask = 1L << kTXNUseVerticalTextBit -kTXNDontUpdateBoxRectMask = 1L << kTXNDontUpdateBoxRectBit -kTXNDontDrawTextMask = 1L << kTXNDontDrawTextBit -kTXNUseCGContextRefMask = 1L << kTXNUseCGContextRefBit -kTXNImageWithQDMask = 1L << kTXNImageWithQDBit -kTXNDontWrapTextMask = 1L << kTXNDontWrapTextBit +kTXNSetFlushnessMask = 1 << kTXNSetFlushnessBit +kTXNSetJustificationMask = 1 << kTXNSetJustificationBit +kTXNUseFontFallBackMask = 1 << kTXNUseFontFallBackBit +kTXNRotateTextMask = 1 << kTXNRotateTextBit +kTXNUseVerticalTextMask = 1 << kTXNUseVerticalTextBit +kTXNDontUpdateBoxRectMask = 1 << kTXNDontUpdateBoxRectBit +kTXNDontDrawTextMask = 1 << kTXNDontDrawTextBit +kTXNUseCGContextRefMask = 1 << kTXNUseCGContextRefBit +kTXNImageWithQDMask = 1 << kTXNImageWithQDBit +kTXNDontWrapTextMask = 1 << kTXNDontWrapTextBit kTXNFontContinuousBit = 0 kTXNSizeContinuousBit = 1 kTXNStyleContinuousBit = 2 kTXNColorContinuousBit = 3 -kTXNFontContinuousMask = 1L << kTXNFontContinuousBit -kTXNSizeContinuousMask = 1L << kTXNSizeContinuousBit -kTXNStyleContinuousMask = 1L << kTXNStyleContinuousBit -kTXNColorContinuousMask = 1L << kTXNColorContinuousBit +kTXNFontContinuousMask = 1 << kTXNFontContinuousBit +kTXNSizeContinuousMask = 1 << kTXNSizeContinuousBit +kTXNStyleContinuousMask = 1 << kTXNStyleContinuousBit +kTXNColorContinuousMask = 1 << kTXNColorContinuousBit kTXNIgnoreCaseBit = 0 kTXNEntireWordBit = 1 kTXNUseEncodingWordRulesBit = 31 -kTXNIgnoreCaseMask = 1L << kTXNIgnoreCaseBit -kTXNEntireWordMask = 1L << kTXNEntireWordBit +kTXNIgnoreCaseMask = 1 << kTXNIgnoreCaseBit +kTXNEntireWordMask = 1 << kTXNEntireWordBit # kTXNUseEncodingWordRulesMask = (unsigned long)(1L << kTXNUseEncodingWordRulesBit) kTXNTextensionFile = FOUR_CHAR_CODE('txtn') kTXNTextFile = FOUR_CHAR_CODE('TEXT') @@ -216,8 +216,8 @@ kTXNBackgroundTypeRGB = 1 kTXNTextInputCountBit = 0 kTXNRunCountBit = 1 -kTXNTextInputCountMask = 1L << kTXNTextInputCountBit -kTXNRunCountMask = 1L << kTXNRunCountBit +kTXNTextInputCountMask = 1 << kTXNTextInputCountBit +kTXNRunCountMask = 1 << kTXNRunCountBit kTXNAllCountMask = kTXNTextInputCountMask | kTXNRunCountMask kTXNNoAppleEventHandlersBit = 0 kTXNRestartAppleEventHandlersBit = 1 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/OSAconst.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/OSAconst.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/OSAconst.py Mon Jan 15 17:59:06 2007 @@ -19,7 +19,7 @@ keyOSADialectCode = FOUR_CHAR_CODE('dcod') keyOSADialectLangCode = FOUR_CHAR_CODE('dlcd') keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd') -kOSANullScript = 0L +kOSANullScript = 0 kOSANullMode = 0 kOSAModeNull = 0 kOSASupportsCompiling = 0x0002 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/QDOffscreen.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/QDOffscreen.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/QDOffscreen.py Mon Jan 15 17:59:06 2007 @@ -18,30 +18,30 @@ stretchPixBit = 29 ditherPixBit = 30 gwFlagErrBit = 31 -pixPurge = 1L << pixPurgeBit -noNewDevice = 1L << noNewDeviceBit -useTempMem = 1L << useTempMemBit -keepLocal = 1L << keepLocalBit -useDistantHdwrMem = 1L << useDistantHdwrMemBit -useLocalHdwrMem = 1L << useLocalHdwrMemBit -pixelsPurgeable = 1L << pixelsPurgeableBit -pixelsLocked = 1L << pixelsLockedBit -kAllocDirectDrawSurface = 1L << 14 -mapPix = 1L << mapPixBit -newDepth = 1L << newDepthBit -alignPix = 1L << alignPixBit -newRowBytes = 1L << newRowBytesBit -reallocPix = 1L << reallocPixBit -clipPix = 1L << clipPixBit -stretchPix = 1L << stretchPixBit -ditherPix = 1L << ditherPixBit -gwFlagErr = 1L << gwFlagErrBit -deviceIsIndirect = (1L << 0) -deviceNeedsLock = (1L << 1) -deviceIsStatic = (1L << 2) -deviceIsExternalBuffer = (1L << 3) -deviceIsDDSurface = (1L << 4) -deviceIsDCISurface = (1L << 5) -deviceIsGDISurface = (1L << 6) -deviceIsAScreen = (1L << 7) -deviceIsOverlaySurface = (1L << 8) +pixPurge = 1 << pixPurgeBit +noNewDevice = 1 << noNewDeviceBit +useTempMem = 1 << useTempMemBit +keepLocal = 1 << keepLocalBit +useDistantHdwrMem = 1 << useDistantHdwrMemBit +useLocalHdwrMem = 1 << useLocalHdwrMemBit +pixelsPurgeable = 1 << pixelsPurgeableBit +pixelsLocked = 1 << pixelsLockedBit +kAllocDirectDrawSurface = 1 << 14 +mapPix = 1 << mapPixBit +newDepth = 1 << newDepthBit +alignPix = 1 << alignPixBit +newRowBytes = 1 << newRowBytesBit +reallocPix = 1 << reallocPixBit +clipPix = 1 << clipPixBit +stretchPix = 1 << stretchPixBit +ditherPix = 1 << ditherPixBit +gwFlagErr = 1 << gwFlagErrBit +deviceIsIndirect = (1 << 0) +deviceNeedsLock = (1 << 1) +deviceIsStatic = (1 << 2) +deviceIsExternalBuffer = (1 << 3) +deviceIsDDSurface = (1 << 4) +deviceIsDCISurface = (1 << 5) +deviceIsGDISurface = (1 << 6) +deviceIsAScreen = (1 << 7) +deviceIsOverlaySurface = (1 << 8) Modified: python/branches/p3yk/Lib/plat-mac/Carbon/QuickDraw.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/QuickDraw.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/QuickDraw.py Mon Jan 15 17:59:06 2007 @@ -160,11 +160,11 @@ kXFerConvertPixelToRGB32 = 0x00000002 kCursorComponentsVersion = 0x00010001 kCursorComponentType = FOUR_CHAR_CODE('curs') -cursorDoesAnimate = 1L << 0 -cursorDoesHardware = 1L << 1 -cursorDoesUnreadableScreenBits = 1L << 2 -kRenderCursorInHardware = 1L << 0 -kRenderCursorInSoftware = 1L << 1 +cursorDoesAnimate = 1 << 0 +cursorDoesHardware = 1 << 1 +cursorDoesUnreadableScreenBits = 1 << 2 +kRenderCursorInHardware = 1 << 0 +kRenderCursorInSoftware = 1 << 1 kCursorComponentInit = 0x0001 kCursorComponentGetInfo = 0x0002 kCursorComponentSetOutputMode = 0x0003 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/QuickTime.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/QuickTime.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/QuickTime.py Mon Jan 15 17:59:06 2007 @@ -94,14 +94,14 @@ kUserDataTextWriter = FOUR_CHAR_CODE('\xa9wrt') kUserDataTextURLLink = FOUR_CHAR_CODE('\xa9url') kUserDataTextEditDate1 = FOUR_CHAR_CODE('\xa9ed1') -kUserDataUnicodeBit = 1L << 7 +kUserDataUnicodeBit = 1 << 7 DoTheRightThing = 0 kQTNetworkStatusNoNetwork = -2 kQTNetworkStatusUncertain = -1 kQTNetworkStatusNotConnected = 0 kQTNetworkStatusConnected = 1 -kMusicFlagDontPlay2Soft = 1L << 0 -kMusicFlagDontSlaveToMovie = 1L << 1 +kMusicFlagDontPlay2Soft = 1 << 0 +kMusicFlagDontSlaveToMovie = 1 << 1 dfDontDisplay = 1 << 0 dfDontAutoScale = 1 << 1 dfClipToTextBox = 1 << 2 @@ -119,10 +119,10 @@ dfKeyedText = 1 << 14 dfInverseHilite = 1 << 15 dfTextColorHilite = 1 << 16 -searchTextDontGoToFoundTime = 1L << 16 -searchTextDontHiliteFoundText = 1L << 17 -searchTextOneTrackOnly = 1L << 18 -searchTextEnabledTracksOnly = 1L << 19 +searchTextDontGoToFoundTime = 1 << 16 +searchTextDontHiliteFoundText = 1 << 17 +searchTextOneTrackOnly = 1 << 18 +searchTextEnabledTracksOnly = 1 << 19 kTextTextHandle = 1 kTextTextPtr = 2 kTextTEStyle = 3 @@ -167,7 +167,7 @@ mediaQualityNormal = 0x0040 mediaQualityBetter = 0x0080 mediaQualityBest = 0x00C0 -kQTEventPayloadIsQTList = 1L << 0 +kQTEventPayloadIsQTList = 1 << 0 kActionMovieSetVolume = 1024 kActionMovieSetRate = 1025 kActionMovieSetLoopingFlags = 1026 @@ -509,19 +509,19 @@ kQTEventRequestToModifyMovie = FOUR_CHAR_CODE('reqm') kQTEventListReceived = FOUR_CHAR_CODE('list') kQTEventKeyUp = FOUR_CHAR_CODE('keyU') -kActionFlagActionIsDelta = 1L << 1 -kActionFlagParameterWrapsAround = 1L << 2 -kActionFlagActionIsToggle = 1L << 3 -kStatusStringIsURLLink = 1L << 1 -kStatusStringIsStreamingStatus = 1L << 2 -kStatusHasCodeNumber = 1L << 3 -kStatusIsError = 1L << 4 -kScriptIsUnknownType = 1L << 0 -kScriptIsJavaScript = 1L << 1 -kScriptIsLingoEvent = 1L << 2 -kScriptIsVBEvent = 1L << 3 -kScriptIsProjectorCommand = 1L << 4 -kScriptIsAppleScript = 1L << 5 +kActionFlagActionIsDelta = 1 << 1 +kActionFlagParameterWrapsAround = 1 << 2 +kActionFlagActionIsToggle = 1 << 3 +kStatusStringIsURLLink = 1 << 1 +kStatusStringIsStreamingStatus = 1 << 2 +kStatusHasCodeNumber = 1 << 3 +kStatusIsError = 1 << 4 +kScriptIsUnknownType = 1 << 0 +kScriptIsJavaScript = 1 << 1 +kScriptIsLingoEvent = 1 << 2 +kScriptIsVBEvent = 1 << 3 +kScriptIsProjectorCommand = 1 << 4 +kScriptIsAppleScript = 1 << 5 kQTRegistrationDialogTimeOutFlag = 1 << 0 kQTRegistrationDialogShowDialog = 1 << 1 kQTRegistrationDialogForceDialog = 1 << 2 @@ -605,16 +605,16 @@ nextTimeStep = 1 << 4 nextTimeEdgeOK = 1 << 14 nextTimeIgnoreActiveSegment = 1 << 15 -createMovieFileDeleteCurFile = 1L << 31 -createMovieFileDontCreateMovie = 1L << 30 -createMovieFileDontOpenFile = 1L << 29 -createMovieFileDontCreateResFile = 1L << 28 -flattenAddMovieToDataFork = 1L << 0 -flattenActiveTracksOnly = 1L << 2 -flattenDontInterleaveFlatten = 1L << 3 -flattenFSSpecPtrIsDataRefRecordPtr = 1L << 4 -flattenCompressMovieResource = 1L << 5 -flattenForceMovieResourceBeforeMovieData = 1L << 6 +createMovieFileDeleteCurFile = 1 << 31 +createMovieFileDontCreateMovie = 1 << 30 +createMovieFileDontOpenFile = 1 << 29 +createMovieFileDontCreateResFile = 1 << 28 +flattenAddMovieToDataFork = 1 << 0 +flattenActiveTracksOnly = 1 << 2 +flattenDontInterleaveFlatten = 1 << 3 +flattenFSSpecPtrIsDataRefRecordPtr = 1 << 4 +flattenCompressMovieResource = 1 << 5 +flattenForceMovieResourceBeforeMovieData = 1 << 6 movieInDataForkResID = -1 mcTopLeftMovie = 1 << 0 mcScaleMovieToFit = 1 << 1 @@ -645,17 +645,17 @@ hintsSingleField = 1 << 20 hintsNoRenderingTimeOut = 1 << 21 hintsFlushVideoInsteadOfDirtying = 1 << 22 -hintsEnableSubPixelPositioning = 1L << 23 +hintsEnableSubPixelPositioning = 1 << 23 mediaHandlerFlagBaseClient = 1 movieTrackMediaType = 1 << 0 movieTrackCharacteristic = 1 << 1 movieTrackEnabledOnly = 1 << 2 -kMovieControlOptionHideController = (1L << 0) -kMovieControlOptionLocateTopLeft = (1L << 1) -kMovieControlOptionEnableEditing = (1L << 2) -kMovieControlOptionHandleEditingHI = (1L << 3) -kMovieControlOptionSetKeysEnabled = (1L << 4) -kMovieControlOptionManuallyIdled = (1L << 5) +kMovieControlOptionHideController = (1 << 0) +kMovieControlOptionLocateTopLeft = (1 << 1) +kMovieControlOptionEnableEditing = (1 << 2) +kMovieControlOptionHandleEditingHI = (1 << 3) +kMovieControlOptionSetKeysEnabled = (1 << 4) +kMovieControlOptionManuallyIdled = (1 << 5) kMovieControlDataMovieController = FOUR_CHAR_CODE('mc ') kMovieControlDataMovie = FOUR_CHAR_CODE('moov') kMovieControlDataManualIdling = FOUR_CHAR_CODE('manu') @@ -663,33 +663,33 @@ movieDrawingCallAlways = 1 kQTCloneShareSamples = 1 << 0 kQTCloneDontCopyEdits = 1 << 1 -kGetMovieImporterValidateToFind = 1L << 0 -kGetMovieImporterAllowNewFile = 1L << 1 -kGetMovieImporterDontConsiderGraphicsImporters = 1L << 2 -kGetMovieImporterDontConsiderFileOnlyImporters = 1L << 6 -kGetMovieImporterAutoImportOnly = 1L << 10 +kGetMovieImporterValidateToFind = 1 << 0 +kGetMovieImporterAllowNewFile = 1 << 1 +kGetMovieImporterDontConsiderGraphicsImporters = 1 << 2 +kGetMovieImporterDontConsiderFileOnlyImporters = 1 << 6 +kGetMovieImporterAutoImportOnly = 1 << 10 kQTGetMIMETypeInfoIsQuickTimeMovieType = FOUR_CHAR_CODE('moov') kQTGetMIMETypeInfoIsUnhelpfulType = FOUR_CHAR_CODE('dumb') kQTCopyUserDataReplace = FOUR_CHAR_CODE('rplc') kQTCopyUserDataMerge = FOUR_CHAR_CODE('merg') -kMovieLoadStateError = -1L +kMovieLoadStateError = -1 kMovieLoadStateLoading = 1000 kMovieLoadStateLoaded = 2000 kMovieLoadStatePlayable = 10000 kMovieLoadStatePlaythroughOK = 20000 -kMovieLoadStateComplete = 100000L -kQTDontUseDataToFindImporter = 1L << 0 -kQTDontLookForMovieImporterIfGraphicsImporterFound = 1L << 1 -kQTAllowOpeningStillImagesAsMovies = 1L << 2 -kQTAllowImportersThatWouldCreateNewFile = 1L << 3 -kQTAllowAggressiveImporters = 1L << 4 -preloadAlways = 1L << 0 -preloadOnlyIfEnabled = 1L << 1 -fullScreenHideCursor = 1L << 0 -fullScreenAllowEvents = 1L << 1 -fullScreenDontChangeMenuBar = 1L << 2 -fullScreenPreflightSize = 1L << 3 -movieExecuteWiredActionDontExecute = 1L << 0 +kMovieLoadStateComplete = 100000 +kQTDontUseDataToFindImporter = 1 << 0 +kQTDontLookForMovieImporterIfGraphicsImporterFound = 1 << 1 +kQTAllowOpeningStillImagesAsMovies = 1 << 2 +kQTAllowImportersThatWouldCreateNewFile = 1 << 3 +kQTAllowAggressiveImporters = 1 << 4 +preloadAlways = 1 << 0 +preloadOnlyIfEnabled = 1 << 1 +fullScreenHideCursor = 1 << 0 +fullScreenAllowEvents = 1 << 1 +fullScreenDontChangeMenuBar = 1 << 2 +fullScreenPreflightSize = 1 << 3 +movieExecuteWiredActionDontExecute = 1 << 0 kRefConNavigationNext = 0 kRefConNavigationPrevious = 1 kRefConPropertyCanHaveFocus = 1 @@ -728,19 +728,19 @@ kSpriteHitTestTreatAllSpritesAsHitTestableMode = 1 kSpriteHitTestTreatAllSpritesAsNotHitTestableMode = 2 kNoQTIdleEvents = -1 -kGetSpriteWorldInvalidRegionAndLeaveIntact = -1L -kGetSpriteWorldInvalidRegionAndThenSetEmpty = -2L -kOnlyDrawToSpriteWorld = 1L << 0 -kSpriteWorldPreflight = 1L << 1 -kSpriteWorldDidDraw = 1L << 0 -kSpriteWorldNeedsToDraw = 1L << 1 -kKeyFrameAndSingleOverride = 1L << 1 -kKeyFrameAndAllOverrides = 1L << 2 -kScaleSpritesToScaleWorld = 1L << 1 -kSpriteWorldHighQuality = 1L << 2 -kSpriteWorldDontAutoInvalidate = 1L << 3 -kSpriteWorldInvisible = 1L << 4 -kSpriteWorldDirtyInsteadOfFlush = 1L << 5 +kGetSpriteWorldInvalidRegionAndLeaveIntact = -1 +kGetSpriteWorldInvalidRegionAndThenSetEmpty = -2 +kOnlyDrawToSpriteWorld = 1 << 0 +kSpriteWorldPreflight = 1 << 1 +kSpriteWorldDidDraw = 1 << 0 +kSpriteWorldNeedsToDraw = 1 << 1 +kKeyFrameAndSingleOverride = 1 << 1 +kKeyFrameAndAllOverrides = 1 << 2 +kScaleSpritesToScaleWorld = 1 << 1 +kSpriteWorldHighQuality = 1 << 2 +kSpriteWorldDontAutoInvalidate = 1 << 3 +kSpriteWorldInvisible = 1 << 4 +kSpriteWorldDirtyInsteadOfFlush = 1 << 5 kParentAtomIsContainer = 0 kTweenRecordNoFlags = 0 kTweenRecordIsAtInterruptTime = 0x00000001 @@ -796,19 +796,19 @@ pdOptionsHidePreview = 0x00000010 effectIsRealtime = 0 kAccessKeyAtomType = FOUR_CHAR_CODE('acky') -kAccessKeySystemFlag = 1L << 0 +kAccessKeySystemFlag = 1 << 0 ConnectionSpeedPrefsType = FOUR_CHAR_CODE('cspd') BandwidthManagementPrefsType = FOUR_CHAR_CODE('bwmg') kQTIdlePriority = 10 kQTNonRealTimePriority = 20 kQTRealTimeSharedPriority = 25 kQTRealTimePriority = 30 -kQTBandwidthNotifyNeedToStop = 1L << 0 -kQTBandwidthNotifyGoodToGo = 1L << 1 -kQTBandwidthChangeRequest = 1L << 2 -kQTBandwidthQueueRequest = 1L << 3 -kQTBandwidthScheduledRequest = 1L << 4 -kQTBandwidthVoluntaryRelease = 1L << 5 +kQTBandwidthNotifyNeedToStop = 1 << 0 +kQTBandwidthNotifyGoodToGo = 1 << 1 +kQTBandwidthChangeRequest = 1 << 2 +kQTBandwidthQueueRequest = 1 << 3 +kQTBandwidthScheduledRequest = 1 << 4 +kQTBandwidthVoluntaryRelease = 1 << 5 kITextRemoveEverythingBut = 0 << 1 kITextRemoveLeaveSuggestedAlternate = 1 << 1 kITextAtomType = FOUR_CHAR_CODE('itxt') @@ -908,20 +908,20 @@ kNameAtom = FOUR_CHAR_CODE('name') kInitialRotationAtom = FOUR_CHAR_CODE('inro') kNonLinearTweenHeader = FOUR_CHAR_CODE('nlth') -kTweenReturnDelta = 1L << 0 +kTweenReturnDelta = 1 << 0 kQTRestrictionClassSave = FOUR_CHAR_CODE('save') -kQTRestrictionSaveDontAddMovieResource = (1L << 0) -kQTRestrictionSaveDontFlatten = (1L << 1) -kQTRestrictionSaveDontExport = (1L << 2) -kQTRestrictionSaveDontExtract = (1L << 3) +kQTRestrictionSaveDontAddMovieResource = (1 << 0) +kQTRestrictionSaveDontFlatten = (1 << 1) +kQTRestrictionSaveDontExport = (1 << 2) +kQTRestrictionSaveDontExtract = (1 << 3) kQTRestrictionClassEdit = FOUR_CHAR_CODE('edit') -kQTRestrictionEditDontCopy = (1L << 0) -kQTRestrictionEditDontCut = (1L << 1) -kQTRestrictionEditDontPaste = (1L << 2) -kQTRestrictionEditDontClear = (1L << 3) -kQTRestrictionEditDontModify = (1L << 4) -kQTRestrictionEditDontExtract = (1L << 5) -videoFlagDontLeanAhead = 1L << 0 +kQTRestrictionEditDontCopy = (1 << 0) +kQTRestrictionEditDontCut = (1 << 1) +kQTRestrictionEditDontPaste = (1 << 2) +kQTRestrictionEditDontClear = (1 << 3) +kQTRestrictionEditDontModify = (1 << 4) +kQTRestrictionEditDontExtract = (1 << 5) +videoFlagDontLeanAhead = 1 << 0 txtProcDefaultDisplay = 0 txtProcDontDisplay = 1 txtProcDoDisplay = 2 @@ -932,12 +932,12 @@ findTextUseOffset = 1 << 4 dropShadowOffsetType = FOUR_CHAR_CODE('drpo') dropShadowTranslucencyType = FOUR_CHAR_CODE('drpt') -spriteHitTestBounds = 1L << 0 -spriteHitTestImage = 1L << 1 -spriteHitTestInvisibleSprites = 1L << 2 -spriteHitTestIsClick = 1L << 3 -spriteHitTestLocInDisplayCoordinates = 1L << 4 -spriteHitTestTreatAllSpritesAsHitTestable = 1L << 5 +spriteHitTestBounds = 1 << 0 +spriteHitTestImage = 1 << 1 +spriteHitTestInvisibleSprites = 1 << 2 +spriteHitTestIsClick = 1 << 3 +spriteHitTestLocInDisplayCoordinates = 1 << 4 +spriteHitTestTreatAllSpritesAsHitTestable = 1 << 5 kSpriteAtomType = FOUR_CHAR_CODE('sprt') kSpriteImagesContainerAtomType = FOUR_CHAR_CODE('imct') kSpriteImageAtomType = FOUR_CHAR_CODE('imag') @@ -1363,68 +1363,68 @@ k4444YpCbCrA8PixelFormat = FOUR_CHAR_CODE('v408') k4444YpCbCrA8RPixelFormat = FOUR_CHAR_CODE('r408') kYUV420PixelFormat = FOUR_CHAR_CODE('y420') -codecInfoDoes1 = (1L << 0) -codecInfoDoes2 = (1L << 1) -codecInfoDoes4 = (1L << 2) -codecInfoDoes8 = (1L << 3) -codecInfoDoes16 = (1L << 4) -codecInfoDoes32 = (1L << 5) -codecInfoDoesDither = (1L << 6) -codecInfoDoesStretch = (1L << 7) -codecInfoDoesShrink = (1L << 8) -codecInfoDoesMask = (1L << 9) -codecInfoDoesTemporal = (1L << 10) -codecInfoDoesDouble = (1L << 11) -codecInfoDoesQuad = (1L << 12) -codecInfoDoesHalf = (1L << 13) -codecInfoDoesQuarter = (1L << 14) -codecInfoDoesRotate = (1L << 15) -codecInfoDoesHorizFlip = (1L << 16) -codecInfoDoesVertFlip = (1L << 17) -codecInfoHasEffectParameterList = (1L << 18) -codecInfoDoesBlend = (1L << 19) -codecInfoDoesWarp = (1L << 20) -codecInfoDoesRecompress = (1L << 21) -codecInfoDoesSpool = (1L << 22) -codecInfoDoesRateConstrain = (1L << 23) -codecInfoDepth1 = (1L << 0) -codecInfoDepth2 = (1L << 1) -codecInfoDepth4 = (1L << 2) -codecInfoDepth8 = (1L << 3) -codecInfoDepth16 = (1L << 4) -codecInfoDepth32 = (1L << 5) -codecInfoDepth24 = (1L << 6) -codecInfoDepth33 = (1L << 7) -codecInfoDepth34 = (1L << 8) -codecInfoDepth36 = (1L << 9) -codecInfoDepth40 = (1L << 10) -codecInfoStoresClut = (1L << 11) -codecInfoDoesLossless = (1L << 12) -codecInfoSequenceSensitive = (1L << 13) -codecFlagUseImageBuffer = (1L << 0) -codecFlagUseScreenBuffer = (1L << 1) -codecFlagUpdatePrevious = (1L << 2) -codecFlagNoScreenUpdate = (1L << 3) -codecFlagWasCompressed = (1L << 4) -codecFlagDontOffscreen = (1L << 5) -codecFlagUpdatePreviousComp = (1L << 6) -codecFlagForceKeyFrame = (1L << 7) -codecFlagOnlyScreenUpdate = (1L << 8) -codecFlagLiveGrab = (1L << 9) -codecFlagDiffFrame = (1L << 9) -codecFlagDontUseNewImageBuffer = (1L << 10) -codecFlagInterlaceUpdate = (1L << 11) -codecFlagCatchUpDiff = (1L << 12) -codecFlagSupportDisable = (1L << 13) -codecFlagReenable = (1L << 14) -codecFlagOutUpdateOnNextIdle = (1L << 9) -codecFlagOutUpdateOnDataSourceChange = (1L << 10) -codecFlagSequenceSensitive = (1L << 11) -codecFlagOutUpdateOnTimeChange = (1L << 12) -codecFlagImageBufferNotSourceImage = (1L << 13) -codecFlagUsedNewImageBuffer = (1L << 14) -codecFlagUsedImageBuffer = (1L << 15) -codecMinimumDataSize = 32768L +codecInfoDoes1 = (1 << 0) +codecInfoDoes2 = (1 << 1) +codecInfoDoes4 = (1 << 2) +codecInfoDoes8 = (1 << 3) +codecInfoDoes16 = (1 << 4) +codecInfoDoes32 = (1 << 5) +codecInfoDoesDither = (1 << 6) +codecInfoDoesStretch = (1 << 7) +codecInfoDoesShrink = (1 << 8) +codecInfoDoesMask = (1 << 9) +codecInfoDoesTemporal = (1 << 10) +codecInfoDoesDouble = (1 << 11) +codecInfoDoesQuad = (1 << 12) +codecInfoDoesHalf = (1 << 13) +codecInfoDoesQuarter = (1 << 14) +codecInfoDoesRotate = (1 << 15) +codecInfoDoesHorizFlip = (1 << 16) +codecInfoDoesVertFlip = (1 << 17) +codecInfoHasEffectParameterList = (1 << 18) +codecInfoDoesBlend = (1 << 19) +codecInfoDoesWarp = (1 << 20) +codecInfoDoesRecompress = (1 << 21) +codecInfoDoesSpool = (1 << 22) +codecInfoDoesRateConstrain = (1 << 23) +codecInfoDepth1 = (1 << 0) +codecInfoDepth2 = (1 << 1) +codecInfoDepth4 = (1 << 2) +codecInfoDepth8 = (1 << 3) +codecInfoDepth16 = (1 << 4) +codecInfoDepth32 = (1 << 5) +codecInfoDepth24 = (1 << 6) +codecInfoDepth33 = (1 << 7) +codecInfoDepth34 = (1 << 8) +codecInfoDepth36 = (1 << 9) +codecInfoDepth40 = (1 << 10) +codecInfoStoresClut = (1 << 11) +codecInfoDoesLossless = (1 << 12) +codecInfoSequenceSensitive = (1 << 13) +codecFlagUseImageBuffer = (1 << 0) +codecFlagUseScreenBuffer = (1 << 1) +codecFlagUpdatePrevious = (1 << 2) +codecFlagNoScreenUpdate = (1 << 3) +codecFlagWasCompressed = (1 << 4) +codecFlagDontOffscreen = (1 << 5) +codecFlagUpdatePreviousComp = (1 << 6) +codecFlagForceKeyFrame = (1 << 7) +codecFlagOnlyScreenUpdate = (1 << 8) +codecFlagLiveGrab = (1 << 9) +codecFlagDiffFrame = (1 << 9) +codecFlagDontUseNewImageBuffer = (1 << 10) +codecFlagInterlaceUpdate = (1 << 11) +codecFlagCatchUpDiff = (1 << 12) +codecFlagSupportDisable = (1 << 13) +codecFlagReenable = (1 << 14) +codecFlagOutUpdateOnNextIdle = (1 << 9) +codecFlagOutUpdateOnDataSourceChange = (1 << 10) +codecFlagSequenceSensitive = (1 << 11) +codecFlagOutUpdateOnTimeChange = (1 << 12) +codecFlagImageBufferNotSourceImage = (1 << 13) +codecFlagUsedNewImageBuffer = (1 << 14) +codecFlagUsedImageBuffer = (1 << 15) +codecMinimumDataSize = 32768 compressorComponentType = FOUR_CHAR_CODE('imco') decompressorComponentType = FOUR_CHAR_CODE('imdc') codecLosslessQuality = 0x00000400 @@ -1466,11 +1466,11 @@ oddField2ToEvenFieldOut = 1 << 6 oddField2ToOddFieldOut = 1 << 7 icmFrameTimeHasVirtualStartTimeAndDuration = 1 << 0 -codecDSequenceDisableOverlaySurface = (1L << 5) -codecDSequenceSingleField = (1L << 6) -codecDSequenceBidirectionalPrediction = (1L << 7) -codecDSequenceFlushInsteadOfDirtying = (1L << 8) -codecDSequenceEnableSubPixelPositioning = (1L << 9) +codecDSequenceDisableOverlaySurface = (1 << 5) +codecDSequenceSingleField = (1 << 6) +codecDSequenceBidirectionalPrediction = (1 << 7) +codecDSequenceFlushInsteadOfDirtying = (1 << 8) +codecDSequenceEnableSubPixelPositioning = (1 << 9) kICMSequenceTaskWeight = FOUR_CHAR_CODE('twei') kICMSequenceTaskName = FOUR_CHAR_CODE('tnam') kICMSequenceUserPreferredCodecs = FOUR_CHAR_CODE('punt') @@ -1487,19 +1487,19 @@ sfpItemCreatePreviewButton = 14 sfpItemShowPreviewButton = 15 kICMPixelFormatIsPlanarMask = 0x0F -kICMPixelFormatIsIndexed = (1L << 4) -kICMPixelFormatIsSupportedByQD = (1L << 5) -kICMPixelFormatIsMonochrome = (1L << 6) -kICMPixelFormatHasAlphaChannel = (1L << 7) +kICMPixelFormatIsIndexed = (1 << 4) +kICMPixelFormatIsSupportedByQD = (1 << 5) +kICMPixelFormatIsMonochrome = (1 << 6) +kICMPixelFormatHasAlphaChannel = (1 << 7) kICMGetChainUltimateParent = 0 kICMGetChainParent = 1 kICMGetChainChild = 2 kICMGetChainUltimateChild = 3 -kDontUseValidateToFindGraphicsImporter = 1L << 0 -kICMTempThenAppMemory = 1L << 12 -kICMAppThenTempMemory = 1L << 13 +kDontUseValidateToFindGraphicsImporter = 1 << 0 +kICMTempThenAppMemory = 1 << 12 +kICMAppThenTempMemory = 1 << 13 kQTUsePlatformDefaultGammaLevel = 0 -kQTUseSourceGammaLevel = -1L +kQTUseSourceGammaLevel = -1 kQTCCIR601VideoGammaLevel = 0x00023333 identityMatrixType = 0x00 translateMatrixType = 0x01 @@ -1509,7 +1509,7 @@ linearTranslateMatrixType = 0x05 perspectiveMatrixType = 0x06 GraphicsImporterComponentType = FOUR_CHAR_CODE('grip') -graphicsImporterUsesImageDecompressor = 1L << 23 +graphicsImporterUsesImageDecompressor = 1 << 23 quickTimeImageFileImageDescriptionAtom = FOUR_CHAR_CODE('idsc') quickTimeImageFileImageDataAtom = FOUR_CHAR_CODE('idat') quickTimeImageFileMetaDataAtom = FOUR_CHAR_CODE('meta') @@ -1517,9 +1517,9 @@ graphicsImporterDrawsAllPixels = 0 graphicsImporterDoesntDrawAllPixels = 1 graphicsImporterDontKnowIfDrawAllPixels = 2 -kGraphicsImporterDontDoGammaCorrection = 1L << 0 -kGraphicsImporterTrustResolutionFromFile = 1L << 1 -kGraphicsImporterEnableSubPixelPositioning = 1L << 2 +kGraphicsImporterDontDoGammaCorrection = 1 << 0 +kGraphicsImporterTrustResolutionFromFile = 1 << 1 +kGraphicsImporterEnableSubPixelPositioning = 1 << 2 kGraphicsExportGroup = FOUR_CHAR_CODE('expo') kGraphicsExportFileType = FOUR_CHAR_CODE('ftyp') kGraphicsExportMIMEType = FOUR_CHAR_CODE('mime') @@ -1624,9 +1624,9 @@ kQTExifUserDataGPSDestDistance = 0x0677001A GraphicsExporterComponentType = FOUR_CHAR_CODE('grex') kBaseGraphicsExporterSubType = FOUR_CHAR_CODE('base') -graphicsExporterIsBaseExporter = 1L << 0 -graphicsExporterCanTranscode = 1L << 1 -graphicsExporterUsesImageCompressor = 1L << 2 +graphicsExporterIsBaseExporter = 1 << 0 +graphicsExporterCanTranscode = 1 << 1 +graphicsExporterUsesImageCompressor = 1 << 2 kQTResolutionSettings = FOUR_CHAR_CODE('reso') kQTTargetDataSize = FOUR_CHAR_CODE('dasz') kQTDontRecompress = FOUR_CHAR_CODE('dntr') @@ -1637,7 +1637,7 @@ kQTMetaData = FOUR_CHAR_CODE('meta') kQTTIFFCompressionMethod = FOUR_CHAR_CODE('tifc') kQTTIFFCompression_None = 1 -kQTTIFFCompression_PackBits = 32773L +kQTTIFFCompression_PackBits = 32773 kQTTIFFLittleEndian = FOUR_CHAR_CODE('tife') kQTPNGFilterPreference = FOUR_CHAR_CODE('pngf') kQTPNGFilterBestForColorType = FOUR_CHAR_CODE('bflt') @@ -1802,13 +1802,13 @@ StandardCompressionType = FOUR_CHAR_CODE('scdi') StandardCompressionSubType = FOUR_CHAR_CODE('imag') StandardCompressionSubTypeSound = FOUR_CHAR_CODE('soun') -scListEveryCodec = 1L << 1 -scAllowZeroFrameRate = 1L << 2 -scAllowZeroKeyFrameRate = 1L << 3 -scShowBestDepth = 1L << 4 -scUseMovableModal = 1L << 5 -scDisableFrameRateItem = 1L << 6 -scShowDataRateAsKilobits = 1L << 7 +scListEveryCodec = 1 << 1 +scAllowZeroFrameRate = 1 << 2 +scAllowZeroKeyFrameRate = 1 << 3 +scShowBestDepth = 1 << 4 +scUseMovableModal = 1 << 5 +scDisableFrameRateItem = 1 << 6 +scShowDataRateAsKilobits = 1 << 7 scPreferCropping = 1 << 0 scPreferScaling = 1 << 1 scPreferScalingAndCropping = scPreferScaling | scPreferCropping @@ -1863,7 +1863,7 @@ scSoundSampleRateChangeOK = FOUR_CHAR_CODE('rcok') scAvailableCompressionListType = FOUR_CHAR_CODE('avai') scGetCompression = 1 -scShowMotionSettings = 1L << 0 +scShowMotionSettings = 1 << 0 scSettingsChangedItem = -1 scCompressFlagIgnoreIdenticalFrames = 1 kQTSettingsVideo = FOUR_CHAR_CODE('vide') @@ -1897,14 +1897,14 @@ hasMovieImportMIMEList = 1 << 14 canMovieImportAvoidBlocking = 1 << 15 canMovieExportFromProcedures = 1 << 15 -canMovieExportValidateMovie = 1L << 16 -movieImportMustGetDestinationMediaType = 1L << 16 -movieExportNeedsResourceFork = 1L << 17 -canMovieImportDataReferences = 1L << 18 -movieExportMustGetSourceMediaType = 1L << 19 -canMovieImportWithIdle = 1L << 20 -canMovieImportValidateDataReferences = 1L << 21 -reservedForUseByGraphicsImporters = 1L << 23 +canMovieExportValidateMovie = 1 << 16 +movieImportMustGetDestinationMediaType = 1 << 16 +movieExportNeedsResourceFork = 1 << 17 +canMovieImportDataReferences = 1 << 18 +movieExportMustGetSourceMediaType = 1 << 19 +canMovieImportWithIdle = 1 << 20 +canMovieImportValidateDataReferences = 1 << 21 +reservedForUseByGraphicsImporters = 1 << 23 movieImportCreateTrack = 1 movieImportInParallel = 2 movieImportMustUseTrack = 4 @@ -1925,20 +1925,20 @@ kQTMediaGroupResourceVersion = 1 kQTBrowserInfoResourceType = FOUR_CHAR_CODE('brws') kQTBrowserInfoResourceVersion = 1 -kQTMediaMIMEInfoHasChanged = (1L << 1) -kQTMediaFileInfoHasChanged = (1L << 2) -kQTMediaConfigCanUseApp = (1L << 18) -kQTMediaConfigCanUsePlugin = (1L << 19) -kQTMediaConfigUNUSED = (1L << 20) -kQTMediaConfigBinaryFile = (1L << 23) +kQTMediaMIMEInfoHasChanged = (1 << 1) +kQTMediaFileInfoHasChanged = (1 << 2) +kQTMediaConfigCanUseApp = (1 << 18) +kQTMediaConfigCanUsePlugin = (1 << 19) +kQTMediaConfigUNUSED = (1 << 20) +kQTMediaConfigBinaryFile = (1 << 23) kQTMediaConfigTextFile = 0 -kQTMediaConfigMacintoshFile = (1L << 24) -kQTMediaConfigAssociateByDefault = (1L << 27) -kQTMediaConfigUseAppByDefault = (1L << 28) -kQTMediaConfigUsePluginByDefault = (1L << 29) +kQTMediaConfigMacintoshFile = (1 << 24) +kQTMediaConfigAssociateByDefault = (1 << 27) +kQTMediaConfigUseAppByDefault = (1 << 28) +kQTMediaConfigUsePluginByDefault = (1 << 29) kQTMediaConfigDefaultsMask = (kQTMediaConfigUseAppByDefault | kQTMediaConfigUsePluginByDefault) kQTMediaConfigDefaultsShift = 12 -kQTMediaConfigHasFileHasQTAtoms = (1L << 30) +kQTMediaConfigHasFileHasQTAtoms = (1 << 30) kQTMediaConfigStreamGroupID = FOUR_CHAR_CODE('strm') kQTMediaConfigInteractiveGroupID = FOUR_CHAR_CODE('intr') kQTMediaConfigVideoGroupID = FOUR_CHAR_CODE('eyes') @@ -2013,17 +2013,17 @@ kQTPresetsPlatformListResourceType = FOUR_CHAR_CODE('stgp') kQTPresetInfoIsDivider = 1 kQTMovieExportSourceInfoResourceType = FOUR_CHAR_CODE('src#') -kQTMovieExportSourceInfoIsMediaType = 1L << 0 -kQTMovieExportSourceInfoIsMediaCharacteristic = 1L << 1 -kQTMovieExportSourceInfoIsSourceType = 1L << 2 +kQTMovieExportSourceInfoIsMediaType = 1 << 0 +kQTMovieExportSourceInfoIsMediaCharacteristic = 1 << 1 +kQTMovieExportSourceInfoIsSourceType = 1 << 2 movieExportUseConfiguredSettings = FOUR_CHAR_CODE('ucfg') movieExportWidth = FOUR_CHAR_CODE('wdth') movieExportHeight = FOUR_CHAR_CODE('hegt') movieExportDuration = FOUR_CHAR_CODE('dura') movieExportVideoFilter = FOUR_CHAR_CODE('iflt') movieExportTimeScale = FOUR_CHAR_CODE('tmsc') -kQTBrowserInfoCanUseSystemFolderPlugin = (1L << 0) -kQTPreFlightOpenComponent = (1L << 1) +kQTBrowserInfoCanUseSystemFolderPlugin = (1 << 0) +kQTPreFlightOpenComponent = (1 << 1) pnotComponentWantsEvents = 1 pnotComponentNeedsNoCache = 2 ShowFilePreviewComponentType = FOUR_CHAR_CODE('pnot') @@ -2032,10 +2032,10 @@ DataDecompressorComponentType = FOUR_CHAR_CODE('ddec') AppleDataCompressorSubType = FOUR_CHAR_CODE('adec') zlibDataCompressorSubType = FOUR_CHAR_CODE('zlib') -kDataHCanRead = 1L << 0 -kDataHSpecialRead = 1L << 1 -kDataHSpecialReadFile = 1L << 2 -kDataHCanWrite = 1L << 3 +kDataHCanRead = 1 << 0 +kDataHSpecialRead = 1 << 1 +kDataHSpecialReadFile = 1 << 2 +kDataHCanWrite = 1 << 3 kDataHSpecialWrite = 1 << 4 kDataHSpecialWriteFile = 1 << 5 kDataHCanStreamingWrite = 1 << 6 @@ -2055,12 +2055,12 @@ kDataHFileTypeMacOSFileType = FOUR_CHAR_CODE('ftyp') kDataHFileTypeExtension = FOUR_CHAR_CODE('fext') kDataHFileTypeMIME = FOUR_CHAR_CODE('mime') -kDataHCreateFileButDontCreateResFile = (1L << 0) -kDataHMovieUsageDoAppendMDAT = 1L << 0 -kDataHTempUseSameDirectory = 1L << 0 -kDataHTempUseSameVolume = 1L << 1 -kDataHTempCreateFile = 1L << 2 -kDataHTempOpenFile = 1L << 3 +kDataHCreateFileButDontCreateResFile = (1 << 0) +kDataHMovieUsageDoAppendMDAT = 1 << 0 +kDataHTempUseSameDirectory = 1 << 0 +kDataHTempUseSameVolume = 1 << 1 +kDataHTempCreateFile = 1 << 2 +kDataHTempOpenFile = 1 << 3 kDataHGetDataRateInfiniteRate = 0x7FFFFFFF kDataHSetTimeHintsSkipBandwidthRequest = 1 << 0 videoDigitizerComponentType = FOUR_CHAR_CODE('vdig') @@ -2091,48 +2091,48 @@ vdTypeAlpha = 1 vdTypeMask = 2 vdTypeKey = 3 -digiInDoesNTSC = 1L << 0 -digiInDoesPAL = 1L << 1 -digiInDoesSECAM = 1L << 2 -digiInDoesGenLock = 1L << 7 -digiInDoesComposite = 1L << 8 -digiInDoesSVideo = 1L << 9 -digiInDoesComponent = 1L << 10 -digiInVTR_Broadcast = 1L << 11 -digiInDoesColor = 1L << 12 -digiInDoesBW = 1L << 13 -digiInSignalLock = 1L << 31 -digiOutDoes1 = 1L << 0 -digiOutDoes2 = 1L << 1 -digiOutDoes4 = 1L << 2 -digiOutDoes8 = 1L << 3 -digiOutDoes16 = 1L << 4 -digiOutDoes32 = 1L << 5 -digiOutDoesDither = 1L << 6 -digiOutDoesStretch = 1L << 7 -digiOutDoesShrink = 1L << 8 -digiOutDoesMask = 1L << 9 -digiOutDoesDouble = 1L << 11 -digiOutDoesQuad = 1L << 12 -digiOutDoesQuarter = 1L << 13 -digiOutDoesSixteenth = 1L << 14 -digiOutDoesRotate = 1L << 15 -digiOutDoesHorizFlip = 1L << 16 -digiOutDoesVertFlip = 1L << 17 -digiOutDoesSkew = 1L << 18 -digiOutDoesBlend = 1L << 19 -digiOutDoesWarp = 1L << 20 -digiOutDoesHW_DMA = 1L << 21 -digiOutDoesHWPlayThru = 1L << 22 -digiOutDoesILUT = 1L << 23 -digiOutDoesKeyColor = 1L << 24 -digiOutDoesAsyncGrabs = 1L << 25 -digiOutDoesUnreadableScreenBits = 1L << 26 -digiOutDoesCompress = 1L << 27 -digiOutDoesCompressOnly = 1L << 28 -digiOutDoesPlayThruDuringCompress = 1L << 29 -digiOutDoesCompressPartiallyVisible = 1L << 30 -digiOutDoesNotNeedCopyOfCompressData = 1L << 31 +digiInDoesNTSC = 1 << 0 +digiInDoesPAL = 1 << 1 +digiInDoesSECAM = 1 << 2 +digiInDoesGenLock = 1 << 7 +digiInDoesComposite = 1 << 8 +digiInDoesSVideo = 1 << 9 +digiInDoesComponent = 1 << 10 +digiInVTR_Broadcast = 1 << 11 +digiInDoesColor = 1 << 12 +digiInDoesBW = 1 << 13 +digiInSignalLock = 1 << 31 +digiOutDoes1 = 1 << 0 +digiOutDoes2 = 1 << 1 +digiOutDoes4 = 1 << 2 +digiOutDoes8 = 1 << 3 +digiOutDoes16 = 1 << 4 +digiOutDoes32 = 1 << 5 +digiOutDoesDither = 1 << 6 +digiOutDoesStretch = 1 << 7 +digiOutDoesShrink = 1 << 8 +digiOutDoesMask = 1 << 9 +digiOutDoesDouble = 1 << 11 +digiOutDoesQuad = 1 << 12 +digiOutDoesQuarter = 1 << 13 +digiOutDoesSixteenth = 1 << 14 +digiOutDoesRotate = 1 << 15 +digiOutDoesHorizFlip = 1 << 16 +digiOutDoesVertFlip = 1 << 17 +digiOutDoesSkew = 1 << 18 +digiOutDoesBlend = 1 << 19 +digiOutDoesWarp = 1 << 20 +digiOutDoesHW_DMA = 1 << 21 +digiOutDoesHWPlayThru = 1 << 22 +digiOutDoesILUT = 1 << 23 +digiOutDoesKeyColor = 1 << 24 +digiOutDoesAsyncGrabs = 1 << 25 +digiOutDoesUnreadableScreenBits = 1 << 26 +digiOutDoesCompress = 1 << 27 +digiOutDoesCompressOnly = 1 << 28 +digiOutDoesPlayThruDuringCompress = 1 << 29 +digiOutDoesCompressPartiallyVisible = 1 << 30 +digiOutDoesNotNeedCopyOfCompressData = 1 << 31 dmaDepth1 = 1 dmaDepth2 = 2 dmaDepth4 = 4 @@ -2160,19 +2160,19 @@ xmlContentTypeInvalid = 0 xmlContentTypeElement = 1 xmlContentTypeCharData = 2 -elementFlagAlwaysSelfContained = 1L << 0 -elementFlagPreserveWhiteSpace = 1L << 1 -xmlParseFlagAllowUppercase = 1L << 0 -xmlParseFlagAllowUnquotedAttributeValues = 1L << 1 -xmlParseFlagEventParseOnly = 1L << 2 +elementFlagAlwaysSelfContained = 1 << 0 +elementFlagPreserveWhiteSpace = 1 << 1 +xmlParseFlagAllowUppercase = 1 << 0 +xmlParseFlagAllowUnquotedAttributeValues = 1 << 1 +xmlParseFlagEventParseOnly = 1 << 2 attributeValueKindCharString = 0 -attributeValueKindInteger = 1L << 0 -attributeValueKindPercent = 1L << 1 -attributeValueKindBoolean = 1L << 2 -attributeValueKindOnOff = 1L << 3 -attributeValueKindColor = 1L << 4 -attributeValueKindEnum = 1L << 5 -attributeValueKindCaseSensEnum = 1L << 6 +attributeValueKindInteger = 1 << 0 +attributeValueKindPercent = 1 << 1 +attributeValueKindBoolean = 1 << 2 +attributeValueKindOnOff = 1 << 3 +attributeValueKindColor = 1 << 4 +attributeValueKindEnum = 1 << 5 +attributeValueKindCaseSensEnum = 1 << 6 MAX_ATTRIBUTE_VALUE_KIND = attributeValueKindCaseSensEnum nameSpaceIDNone = 0 element_xml = 1 @@ -2267,7 +2267,7 @@ sgcVideoDigitizerType = FOUR_CHAR_CODE('vdig') QTVideoOutputComponentType = FOUR_CHAR_CODE('vout') QTVideoOutputComponentBaseSubType = FOUR_CHAR_CODE('base') -kQTVideoOutputDontDisplayToUser = 1L << 0 +kQTVideoOutputDontDisplayToUser = 1 << 0 kQTVODisplayModeItem = FOUR_CHAR_CODE('qdmi') kQTVODimensions = FOUR_CHAR_CODE('dimn') kQTVOResolution = FOUR_CHAR_CODE('resl') @@ -2801,12 +2801,12 @@ mWantIdleActions = 1 << 5 forceUpdateRedraw = 1 << 0 forceUpdateNewBuffer = 1 << 1 -mHitTestBounds = 1L << 0 -mHitTestImage = 1L << 1 -mHitTestInvisible = 1L << 2 -mHitTestIsClick = 1L << 3 -mOpaque = 1L << 0 -mInvisible = 1L << 1 +mHitTestBounds = 1 << 0 +mHitTestImage = 1 << 1 +mHitTestInvisible = 1 << 2 +mHitTestIsClick = 1 << 3 +mOpaque = 1 << 0 +mInvisible = 1 << 1 kMediaQTIdleFrequencySelector = FOUR_CHAR_CODE('idfq') kMediaVideoParamBrightness = 1 kMediaVideoParamContrast = 2 @@ -3244,8 +3244,8 @@ kGeneralEventType = 0x0000000F kXEventLengthBits = 0x00000002 kGeneralEventLengthBits = 0x00000003 -kEventLen = 1L -kXEventLen = 2L +kEventLen = 1 +kXEventLen = 2 kRestEventLen = kEventLen kNoteEventLen = kEventLen kControlEventLen = kEventLen @@ -3265,7 +3265,7 @@ kXEventPartFieldWidth = 12 kRestEventDurationFieldPos = 0 kRestEventDurationFieldWidth = 24 -kRestEventDurationMax = ((1L << kRestEventDurationFieldWidth) - 1) +kRestEventDurationMax = ((1 << kRestEventDurationFieldWidth) - 1) kNoteEventPitchFieldPos = 18 kNoteEventPitchFieldWidth = 6 kNoteEventPitchOffset = 32 @@ -3274,12 +3274,12 @@ kNoteEventVolumeOffset = 0 kNoteEventDurationFieldPos = 0 kNoteEventDurationFieldWidth = 11 -kNoteEventDurationMax = ((1L << kNoteEventDurationFieldWidth) - 1) +kNoteEventDurationMax = ((1 << kNoteEventDurationFieldWidth) - 1) kXNoteEventPitchFieldPos = 0 kXNoteEventPitchFieldWidth = 16 kXNoteEventDurationFieldPos = 0 kXNoteEventDurationFieldWidth = 22 -kXNoteEventDurationMax = ((1L << kXNoteEventDurationFieldWidth) - 1) +kXNoteEventDurationMax = ((1 << kXNoteEventDurationFieldWidth) - 1) kXNoteEventVolumeFieldPos = 22 kXNoteEventVolumeFieldWidth = 7 kControlEventControllerFieldPos = 16 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Sound.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Sound.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Sound.py Mon Jan 15 17:59:06 2007 @@ -300,15 +300,15 @@ k8BitTwosOut = (1 << 9) k16BitOut = (1 << 10) kStereoOut = (1 << 11) -kReverse = (1L << 16) -kRateConvert = (1L << 17) -kCreateSoundSource = (1L << 18) -kVMAwareness = (1L << 21) -kHighQuality = (1L << 22) -kNonRealTime = (1L << 23) +kReverse = (1 << 16) +kRateConvert = (1 << 17) +kCreateSoundSource = (1 << 18) +kVMAwareness = (1 << 21) +kHighQuality = (1 << 22) +kNonRealTime = (1 << 23) kSourcePaused = (1 << 0) -kPassThrough = (1L << 16) -kNoSoundComponentChain = (1L << 17) +kPassThrough = (1 << 16) +kNoSoundComponentChain = (1 << 17) kNoMixing = (1 << 0) kNoSampleRateConversion = (1 << 1) kNoSampleSizeConversion = (1 << 2) @@ -343,9 +343,9 @@ audioRightChannel = 2 audioUnmuted = 0 audioMuted = 1 -audioDoesMono = (1L << 0) -audioDoesStereo = (1L << 1) -audioDoesIndependentChannels = (1L << 2) +audioDoesMono = (1 << 0) +audioDoesStereo = (1 << 1) +audioDoesIndependentChannels = (1 << 2) siCDQuality = FOUR_CHAR_CODE('cd ') siBestQuality = FOUR_CHAR_CODE('best') siBetterQuality = FOUR_CHAR_CODE('betr') @@ -358,8 +358,8 @@ siWritePermission = 1 kSoundConverterDidntFillBuffer = (1 << 0) kSoundConverterHasLeftOverData = (1 << 1) -kExtendedSoundSampleCountNotValid = 1L << 0 -kExtendedSoundBufferSizeValid = 1L << 1 +kExtendedSoundSampleCountNotValid = 1 << 0 +kExtendedSoundBufferSizeValid = 1 << 1 kScheduledSoundDoScheduled = 1 << 0 kScheduledSoundDoCallBack = 1 << 1 kScheduledSoundExtendedHdr = 1 << 2 Modified: python/branches/p3yk/Lib/plat-mac/Carbon/Windows.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/Carbon/Windows.py (original) +++ python/branches/p3yk/Lib/plat-mac/Carbon/Windows.py Mon Jan 15 17:59:06 2007 @@ -20,24 +20,24 @@ kAltPlainWindowClass = 16 kDrawerWindowClass = 20 # kAllWindowClasses = (unsigned long)0xFFFFFFFF -kWindowNoAttributes = 0L -kWindowCloseBoxAttribute = (1L << 0) -kWindowHorizontalZoomAttribute = (1L << 1) -kWindowVerticalZoomAttribute = (1L << 2) +kWindowNoAttributes = 0 +kWindowCloseBoxAttribute = (1 << 0) +kWindowHorizontalZoomAttribute = (1 << 1) +kWindowVerticalZoomAttribute = (1 << 2) kWindowFullZoomAttribute = (kWindowVerticalZoomAttribute | kWindowHorizontalZoomAttribute) -kWindowCollapseBoxAttribute = (1L << 3) -kWindowResizableAttribute = (1L << 4) -kWindowSideTitlebarAttribute = (1L << 5) -kWindowToolbarButtonAttribute = (1L << 6) -kWindowNoUpdatesAttribute = (1L << 16) -kWindowNoActivatesAttribute = (1L << 17) -kWindowOpaqueForEventsAttribute = (1L << 18) -kWindowNoShadowAttribute = (1L << 21) -kWindowHideOnSuspendAttribute = (1L << 24) -kWindowStandardHandlerAttribute = (1L << 25) -kWindowHideOnFullScreenAttribute = (1L << 26) -kWindowInWindowMenuAttribute = (1L << 27) -kWindowLiveResizeAttribute = (1L << 28) +kWindowCollapseBoxAttribute = (1 << 3) +kWindowResizableAttribute = (1 << 4) +kWindowSideTitlebarAttribute = (1 << 5) +kWindowToolbarButtonAttribute = (1 << 6) +kWindowNoUpdatesAttribute = (1 << 16) +kWindowNoActivatesAttribute = (1 << 17) +kWindowOpaqueForEventsAttribute = (1 << 18) +kWindowNoShadowAttribute = (1 << 21) +kWindowHideOnSuspendAttribute = (1 << 24) +kWindowStandardHandlerAttribute = (1 << 25) +kWindowHideOnFullScreenAttribute = (1 << 26) +kWindowInWindowMenuAttribute = (1 << 27) +kWindowLiveResizeAttribute = (1 << 28) # kWindowNoConstrainAttribute = (unsigned long)((1L << 31)) kWindowStandardDocumentAttributes = (kWindowCloseBoxAttribute | kWindowFullZoomAttribute | kWindowCollapseBoxAttribute | kWindowResizableAttribute) kWindowStandardFloatingAttributes = (kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute) @@ -225,7 +225,7 @@ # kMouseUpOutOfSlop = (long)0x80008000 kWindowDefinitionVersionOne = 1 kWindowDefinitionVersionTwo = 2 -kWindowIsCollapsedState = (1 << 0L) +kWindowIsCollapsedState = (1 << 0) kStoredWindowSystemTag = FOUR_CHAR_CODE('appl') kStoredBasicWindowDescriptionID = FOUR_CHAR_CODE('sbas') kStoredWindowPascalTitleID = FOUR_CHAR_CODE('s255') @@ -251,8 +251,8 @@ kWindowGroupContentsVisible = 1 << 2 kWindowPaintProcOptionsNone = 0 kScrollWindowNoOptions = 0 -kScrollWindowInvalidate = (1L << 0) -kScrollWindowEraseToPortBackground = (1L << 1) +kScrollWindowInvalidate = (1 << 0) +kScrollWindowEraseToPortBackground = (1 << 1) kWindowMenuIncludeRotate = 1 << 0 kWindowZoomTransitionEffect = 1 kWindowSheetTransitionEffect = 2 @@ -261,11 +261,11 @@ kWindowHideTransitionAction = 2 kWindowMoveTransitionAction = 3 kWindowResizeTransitionAction = 4 -kWindowConstrainMayResize = (1L << 0) -kWindowConstrainMoveRegardlessOfFit = (1L << 1) -kWindowConstrainAllowPartial = (1L << 2) -kWindowConstrainCalcOnly = (1L << 3) -kWindowConstrainUseTransitionWindow = (1L << 4) +kWindowConstrainMayResize = (1 << 0) +kWindowConstrainMoveRegardlessOfFit = (1 << 1) +kWindowConstrainAllowPartial = (1 << 2) +kWindowConstrainCalcOnly = (1 << 3) +kWindowConstrainUseTransitionWindow = (1 << 4) kWindowConstrainStandardOptions = kWindowConstrainMoveRegardlessOfFit kWindowLatentVisibleFloater = 1 << 0 kWindowLatentVisibleSuspend = 1 << 1 Modified: python/branches/p3yk/Lib/plat-mac/aepack.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aepack.py (original) +++ python/branches/p3yk/Lib/plat-mac/aepack.py Mon Jan 15 17:59:06 2007 @@ -189,13 +189,13 @@ return struct.unpack('l', desc.data)[0] if t == typeLongDateTime: a, b = struct.unpack('lL', desc.data) - return (long(a) << 32) + b + return (int(a) << 32) + b if t == typeNull: return None if t == typeMagnitude: v = struct.unpack('l', desc.data) if v < 0: - v = 0x100000000L + v + v = 0x100000000 + v return v if t == typeObjectSpecifier: record = desc.AECoerceDesc('reco') Modified: python/branches/p3yk/Lib/plat-mac/macfs.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/macfs.py (original) +++ python/branches/p3yk/Lib/plat-mac/macfs.py Mon Jan 15 17:59:06 2007 @@ -28,24 +28,24 @@ # Find the epoch conversion for file dates in a way that works on OS9 and OSX import time if time.gmtime(0)[0] == 1970: - _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000L + _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000 def _utc2time(utc): t = utc[1] + _EPOCHCONVERT return int(t) def _time2utc(t): t = int(t) - _EPOCHCONVERT if t < -0x7fffffff: - t = t + 0x10000000L + t = t + 0x10000000 return (0, int(t), 0) else: def _utc2time(utc): t = utc[1] if t < 0: - t = t + 0x100000000L + t = t + 0x100000000 return t def _time2utc(t): if t > 0x7fffffff: - t = t - 0x100000000L + t = t - 0x100000000 return (0, int(t), 0) # The old name of the error object: Modified: python/branches/p3yk/Lib/plat-mac/pimp.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/pimp.py (original) +++ python/branches/p3yk/Lib/plat-mac/pimp.py Mon Jan 15 17:59:06 2007 @@ -148,7 +148,7 @@ keepgoing = True download = urllib2.urlopen(url) if "content-length" in download.headers: - length = long(download.headers['content-length']) + length = int(download.headers['content-length']) else: length = -1 Modified: python/branches/p3yk/Lib/plat-os2emx/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-os2emx/IN.py (original) +++ python/branches/p3yk/Lib/plat-os2emx/IN.py Mon Jan 15 17:59:06 2007 @@ -28,33 +28,33 @@ IPPROTO_MAX = 256 IPPORT_RESERVED = 1024 IPPORT_USERRESERVED = 5000 -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_LOOPBACK = 0x7f000001 Modified: python/branches/p3yk/Lib/plat-sunos5/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-sunos5/IN.py (original) +++ python/branches/p3yk/Lib/plat-sunos5/IN.py Mon Jan 15 17:59:06 2007 @@ -42,7 +42,7 @@ _LARGEFILE_SOURCE = 1 _FILE_OFFSET_BITS = 64 _FILE_OFFSET_BITS = 32 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _POSIX_PTHREAD_SEMANTICS = 1 _XOPEN_VERSION = 500 _XOPEN_VERSION = 4 @@ -95,10 +95,10 @@ NGROUPS_UMAX = 32 NGROUPS_MAX_DEFAULT = 16 NZERO = 20 -NULL = 0L +NULL = 0 NULL = 0 CMASK = 022 -CDLIMIT = (1L<<11) +CDLIMIT = (1<<11) NBPS = 0x20000 NBPSCTR = 512 UBSIZE = 512 @@ -117,9 +117,9 @@ DEV_BSHIFT = 9 MAXFRAG = 8 MAXOFF32_T = 0x7fffffff -MAXOFF_T = 0x7fffffffffffffffl -MAXOFFSET_T = 0x7fffffffffffffffl -MAXOFF_T = 0x7fffffffl +MAXOFF_T = 0x7fffffffffffffff +MAXOFFSET_T = 0x7fffffffffffffff +MAXOFF_T = 0x7fffffff MAXOFFSET_T = 0x7fffffff def btodb(bytes): return \ @@ -312,9 +312,9 @@ _PC_SYNC_IO = 12 _PC_FILESIZEBITS = 67 _PC_LAST = 67 -_POSIX_VERSION = 199506L -_POSIX2_VERSION = 199209L -_POSIX2_C_VERSION = 199209L +_POSIX_VERSION = 199506 +_POSIX2_VERSION = 199209 +_POSIX2_C_VERSION = 199209 _XOPEN_XCU_VERSION = 4 _XOPEN_REALTIME = 1 _XOPEN_ENH_I18N = 1 @@ -431,7 +431,7 @@ from TYPES import * # Included from iso/time_iso.h -NULL = 0L +NULL = 0 NULL = 0 CLOCKS_PER_SEC = 1000000 @@ -869,9 +869,9 @@ RLIMIT_VMEM = 6 RLIMIT_AS = RLIMIT_VMEM RLIM_NLIMITS = 7 -RLIM_INFINITY = (-3l) -RLIM_SAVED_MAX = (-2l) -RLIM_SAVED_CUR = (-1l) +RLIM_INFINITY = (-3) +RLIM_SAVED_MAX = (-2) +RLIM_SAVED_CUR = (-1) RLIM_INFINITY = 0x7fffffff RLIM_SAVED_MAX = 0x7ffffffe RLIM_SAVED_CUR = 0x7ffffffd @@ -1063,7 +1063,7 @@ POLLCLOSED = 0x8000 # Included from sys/strmdep.h -def str_aligned(X): return (((ulong_t)(X) & (sizeof (long) - 1)) == 0) +def str_aligned(X): return (((ulong_t)(X) & (sizeof (int) - 1)) == 0) # Included from sys/strft.h Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py ============================================================================== --- python/branches/p3yk/Lib/plat-sunos5/STROPTS.py (original) +++ python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Mon Jan 15 17:59:06 2007 @@ -42,7 +42,7 @@ _LARGEFILE_SOURCE = 1 _FILE_OFFSET_BITS = 64 _FILE_OFFSET_BITS = 32 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _POSIX_PTHREAD_SEMANTICS = 1 _XOPEN_VERSION = 500 _XOPEN_VERSION = 4 @@ -92,10 +92,10 @@ NGROUPS_UMAX = 32 NGROUPS_MAX_DEFAULT = 16 NZERO = 20 -NULL = 0L +NULL = 0 NULL = 0 CMASK = 022 -CDLIMIT = (1L<<11) +CDLIMIT = (1<<11) NBPS = 0x20000 NBPSCTR = 512 UBSIZE = 512 @@ -114,9 +114,9 @@ DEV_BSHIFT = 9 MAXFRAG = 8 MAXOFF32_T = 0x7fffffff -MAXOFF_T = 0x7fffffffffffffffl -MAXOFFSET_T = 0x7fffffffffffffffl -MAXOFF_T = 0x7fffffffl +MAXOFF_T = 0x7fffffffffffffff +MAXOFFSET_T = 0x7fffffffffffffff +MAXOFF_T = 0x7fffffff MAXOFFSET_T = 0x7fffffff def btodb(bytes): return \ @@ -309,9 +309,9 @@ _PC_SYNC_IO = 12 _PC_FILESIZEBITS = 67 _PC_LAST = 67 -_POSIX_VERSION = 199506L -_POSIX2_VERSION = 199209L -_POSIX2_C_VERSION = 199209L +_POSIX_VERSION = 199506 +_POSIX2_VERSION = 199209 +_POSIX2_C_VERSION = 199209 _XOPEN_XCU_VERSION = 4 _XOPEN_REALTIME = 1 _XOPEN_ENH_I18N = 1 @@ -428,7 +428,7 @@ from TYPES import * # Included from iso/time_iso.h -NULL = 0L +NULL = 0 NULL = 0 CLOCKS_PER_SEC = 1000000 @@ -872,9 +872,9 @@ RLIMIT_VMEM = 6 RLIMIT_AS = RLIMIT_VMEM RLIM_NLIMITS = 7 -RLIM_INFINITY = (-3l) -RLIM_SAVED_MAX = (-2l) -RLIM_SAVED_CUR = (-1l) +RLIM_INFINITY = (-3) +RLIM_SAVED_MAX = (-2) +RLIM_SAVED_CUR = (-1) RLIM_INFINITY = 0x7fffffff RLIM_SAVED_MAX = 0x7ffffffe RLIM_SAVED_CUR = 0x7ffffffd Modified: python/branches/p3yk/Lib/plat-sunos5/TYPES.py ============================================================================== --- python/branches/p3yk/Lib/plat-sunos5/TYPES.py (original) +++ python/branches/p3yk/Lib/plat-sunos5/TYPES.py Mon Jan 15 17:59:06 2007 @@ -42,7 +42,7 @@ _LARGEFILE_SOURCE = 1 _FILE_OFFSET_BITS = 64 _FILE_OFFSET_BITS = 32 -_POSIX_C_SOURCE = 199506L +_POSIX_C_SOURCE = 199506 _POSIX_PTHREAD_SEMANTICS = 1 _XOPEN_VERSION = 500 _XOPEN_VERSION = 4 @@ -216,10 +216,10 @@ USHRT_MAX = 65535 INT_MIN = (-2147483647-1) INT_MAX = 2147483647 -LONG_MIN = (-9223372036854775807L-1L) -LONG_MAX = 9223372036854775807L -LONG_MIN = (-2147483647L-1L) -LONG_MAX = 2147483647L +LONG_MIN = (-9223372036854775807-1) +LONG_MAX = 9223372036854775807 +LONG_MIN = (-2147483647-1) +LONG_MAX = 2147483647 P_MYID = (-1) # Included from sys/select.h @@ -303,7 +303,7 @@ from TYPES import * # Included from iso/time_iso.h -NULL = 0L +NULL = 0 NULL = 0 CLOCKS_PER_SEC = 1000000 FD_SETSIZE = 65536 Modified: python/branches/p3yk/Lib/plat-unixware7/IN.py ============================================================================== --- python/branches/p3yk/Lib/plat-unixware7/IN.py (original) +++ python/branches/p3yk/Lib/plat-unixware7/IN.py Mon Jan 15 17:59:06 2007 @@ -1,33 +1,33 @@ # Generated by h2py from /usr/include/netinet/in.h # Included from netinet/in_f.h -def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) +def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 -def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) +def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 -def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) +def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff -def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) +def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000) IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) -def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000) +def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000) -def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) +def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_LOOPBACK = 0x7f000001 @@ -330,7 +330,7 @@ MSG_EOR = 0x30 MSG_WAITALL = 0x20 MSG_MAXIOVLEN = 16 -def OPTLEN(x): return ((((x) + sizeof(long) - 1) / sizeof(long)) * sizeof(long)) +def OPTLEN(x): return ((((x) + sizeof(int) - 1) / sizeof(int)) * sizeof(int)) GIARG = 0x1 CONTI = 0x2 @@ -715,7 +715,7 @@ STRHIGH = 5120 STRLOW = 1024 MAXIOCBSZ = 1024 -def straln(a): return (caddr_t)((long)(a) & ~(sizeof(int)-1)) +def straln(a): return (caddr_t)((int)(a) & ~(sizeof(int)-1)) IPM_ID = 200 ICMPM_ID = 201 Modified: python/branches/p3yk/Lib/plat-unixware7/STROPTS.py ============================================================================== --- python/branches/p3yk/Lib/plat-unixware7/STROPTS.py (original) +++ python/branches/p3yk/Lib/plat-unixware7/STROPTS.py Mon Jan 15 17:59:06 2007 @@ -213,7 +213,7 @@ _PC_VDISABLE = 8 _PC_CHOWN_RESTRICTED = 9 _PC_FILESIZEBITS = 10 -_POSIX_VERSION = 199009L +_POSIX_VERSION = 199009 _XOPEN_VERSION = 4 GF_PATH = "/etc/group" PF_PATH = "/etc/passwd" @@ -231,8 +231,8 @@ _XOPEN_UNIX = 1 _XOPEN_ENH_I18N = 1 _XOPEN_XPG4 = 1 -_POSIX2_C_VERSION = 199209L -_POSIX2_VERSION = 199209L +_POSIX2_C_VERSION = 199209 +_POSIX2_VERSION = 199209 _XOPEN_XCU_VERSION = 4 _POSIX_SEMAPHORES = 1 _POSIX_THREADS = 1 Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Mon Jan 15 17:59:06 2007 @@ -682,7 +682,7 @@ patch = (sysv & 0x000F) release = '%s.%i.%i' % (_bcd2str(major),minor,patch) if sysu: - major = int((sysu & 0xFF000000L) >> 24) + major = int((sysu & 0xFF000000) >> 24) minor = (sysu & 0x00F00000) >> 20 bugfix = (sysu & 0x000F0000) >> 16 stage = (sysu & 0x0000FF00) >> 8 Modified: python/branches/p3yk/Lib/py_compile.py ============================================================================== --- python/branches/p3yk/Lib/py_compile.py (original) +++ python/branches/p3yk/Lib/py_compile.py Mon Jan 15 17:59:06 2007 @@ -114,9 +114,9 @@ """ f = open(file, 'U') try: - timestamp = long(os.fstat(f.fileno()).st_mtime) + timestamp = int(os.fstat(f.fileno()).st_mtime) except AttributeError: - timestamp = long(os.stat(file).st_mtime) + timestamp = int(os.stat(file).st_mtime) codestring = f.read() f.close() if codestring and codestring[-1] != '\n': Modified: python/branches/p3yk/Lib/random.py ============================================================================== --- python/branches/p3yk/Lib/random.py (original) +++ python/branches/p3yk/Lib/random.py Mon Jan 15 17:59:06 2007 @@ -105,10 +105,10 @@ if a is None: try: - a = long(_hexlify(_urandom(16)), 16) + a = int(_hexlify(_urandom(16)), 16) except NotImplementedError: import time - a = long(time.time() * 256) # use fractional seconds + a = int(time.time() * 256) # use fractional seconds super(Random, self).seed(a) self.gauss_next = None @@ -145,7 +145,7 @@ ## -------------------- integer methods ------------------- def randrange(self, start, stop=None, step=1, int=int, default=None, - maxwidth=1L<>24)) t, x = divmod(t, 256) t, y = divmod(t, 256) @@ -766,7 +766,7 @@ def random(self): """Get the next random number in the range [0.0, 1.0).""" - return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF + return (int(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF def getrandbits(self, k): """getrandbits(k) -> x. Generates a long int with k random bits.""" @@ -775,7 +775,7 @@ if k != int(k): raise TypeError('number of bits should be an integer') bytes = (k + 7) // 8 # bits / 8 and rounded up - x = long(_hexlify(_urandom(bytes)), 16) + x = int(_hexlify(_urandom(bytes)), 16) return x >> (bytes * 8 - k) # trim excess bits def _stub(self, *args, **kwds): Modified: python/branches/p3yk/Lib/sre_compile.py ============================================================================== --- python/branches/p3yk/Lib/sre_compile.py (original) +++ python/branches/p3yk/Lib/sre_compile.py Mon Jan 15 17:59:06 2007 @@ -19,7 +19,7 @@ if _sre.CODESIZE == 2: MAXCODE = 65535 else: - MAXCODE = 0xFFFFFFFFL + MAXCODE = 0xFFFFFFFF def _identityfunction(x): return x @@ -267,7 +267,7 @@ if _sre.CODESIZE == 2: start = (1, 0) else: - start = (1L, 0L) + start = (1, 0) m, v = start for c in bits: if c: Modified: python/branches/p3yk/Lib/sre_parse.py ============================================================================== --- python/branches/p3yk/Lib/sre_parse.py (original) +++ python/branches/p3yk/Lib/sre_parse.py Mon Jan 15 17:59:06 2007 @@ -149,7 +149,7 @@ # determine the width (min, max) for this subpattern if self.width: return self.width - lo = hi = 0L + lo = hi = 0 UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY) REPEATCODES = (MIN_REPEAT, MAX_REPEAT) for op, av in self.data: @@ -172,8 +172,8 @@ hi = hi + j elif op in REPEATCODES: i, j = av[2].getwidth() - lo = lo + long(i) * av[0] - hi = hi + long(j) * av[1] + lo = lo + int(i) * av[0] + hi = hi + int(j) * av[1] elif op in UNITCODES: lo = lo + 1 hi = hi + 1 Modified: python/branches/p3yk/Lib/string.py ============================================================================== --- python/branches/p3yk/Lib/string.py (original) +++ python/branches/p3yk/Lib/string.py Mon Jan 15 17:59:06 2007 @@ -374,7 +374,7 @@ # for a bit of speed _float = float _int = int -_long = long +_long = int # Convert string to float def atof(s): Modified: python/branches/p3yk/Lib/stringold.py ============================================================================== --- python/branches/p3yk/Lib/stringold.py (original) +++ python/branches/p3yk/Lib/stringold.py Mon Jan 15 17:59:06 2007 @@ -184,7 +184,7 @@ # for a bit of speed _float = float _int = int -_long = long +_long = int _StringType = type('') # Convert string to float Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Mon Jan 15 17:59:06 2007 @@ -541,7 +541,7 @@ _cleanup() self._child_created = False - if not isinstance(bufsize, (int, long)): + if not isinstance(bufsize, (int, int)): raise TypeError("bufsize must be an integer") if mswindows: @@ -764,7 +764,7 @@ startupinfo.wShowWindow = SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args - if (GetVersion() >= 0x80000000L or + if (GetVersion() >= 0x80000000 or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more Modified: python/branches/p3yk/Lib/sunau.py ============================================================================== --- python/branches/p3yk/Lib/sunau.py (original) +++ python/branches/p3yk/Lib/sunau.py Mon Jan 15 17:59:06 2007 @@ -119,7 +119,7 @@ AUDIO_FILE_ENCODING_ALAW_8 = 27 # from -AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0)) +AUDIO_UNKNOWN_SIZE = 0xFFFFFFFF # ((unsigned)(~0)) _simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8, AUDIO_FILE_ENCODING_LINEAR_8, @@ -132,7 +132,7 @@ pass def _read_u32(file): - x = 0L + x = 0 for i in range(4): byte = file.read(1) if byte == '': Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Mon Jan 15 17:59:06 2007 @@ -80,7 +80,7 @@ LENGTH_NAME = 100 # maximum length of a filename LENGTH_LINK = 100 # maximum length of a linkname LENGTH_PREFIX = 155 # maximum length of the prefix field -MAXSIZE_MEMBER = 077777777777L # maximum size of a file (11 octal digits) +MAXSIZE_MEMBER = 077777777777 # maximum size of a file (11 octal digits) REGTYPE = "0" # regular file AREGTYPE = "\0" # regular file @@ -152,7 +152,7 @@ except ValueError: raise HeaderError("invalid header") else: - n = 0L + n = 0 for i in xrange(len(s) - 1): n <<= 8 n += ord(s[i + 1]) @@ -347,7 +347,7 @@ self.fileobj = fileobj self.bufsize = bufsize self.buf = "" - self.pos = 0L + self.pos = 0 self.closed = False if comptype == "gz": @@ -384,7 +384,7 @@ -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) - timestamp = struct.pack(" 32 bits (for 64-bit archs) # see SF bug #689659 - x = 4503599627370496L + x = 4503599627370496 y = 4503599627370496 h = self._full_mapping({x: 'anything', y: 'something else'}) self.assertEqual(h[x], h[y]) @@ -626,7 +626,7 @@ def test_eq(self): self.assertEqual(self._empty_mapping(), self._empty_mapping()) self.assertEqual(self._full_mapping({1: 2}), - self._full_mapping({1L: 2L})) + self._full_mapping({1: 2})) class Exc(Exception): pass Modified: python/branches/p3yk/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk/Lib/test/pickletester.py (original) +++ python/branches/p3yk/Lib/test/pickletester.py Mon Jan 15 17:59:06 2007 @@ -349,7 +349,7 @@ c = C() c.foo = 1 c.bar = 2 - x = [0, 1L, 2.0, 3.0+0j] + x = [0, 1, 2.0, 3.0+0j] # Append some integer test cases at cPickle.c's internal size # cutoffs. uint1max = 0xff @@ -504,7 +504,7 @@ n = n >> 1 def test_maxint64(self): - maxint64 = (1L << 63) - 1 + maxint64 = (1 << 63) - 1 data = 'I' + str(maxint64) + '\n.' got = self.loads(data) self.assertEqual(got, maxint64) @@ -517,7 +517,7 @@ 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 + nbase = 1 << nbits for npos in nbase-1, nbase, nbase+1: for n in npos, -npos: pickle = self.dumps(n, proto) @@ -525,7 +525,7 @@ self.assertEqual(n, got) # Try a monster. This is quadratic-time in protos 0 & 1, so don't # bother with those. - nbase = long("deadbeeffeedface", 16) + nbase = int("deadbeeffeedface", 16) nbase += nbase << 1000000 for n in nbase, -nbase: p = self.dumps(n, 2) @@ -592,7 +592,7 @@ self.fail("expected bad protocol number to raise ValueError") def test_long1(self): - x = 12345678910111213141516178920L + x = 12345678910111213141516178920 for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) @@ -600,7 +600,7 @@ self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2) def test_long4(self): - x = 12345678910111213141516178920L << (256*8) + x = 12345678910111213141516178920 << (256*8) for proto in protocols: s = self.dumps(x, proto) y = self.loads(s) @@ -864,8 +864,8 @@ class MyInt(int): sample = 1 -class MyLong(long): - sample = 1L +class MyLong(int): + sample = 1 class MyFloat(float): sample = 1.0 Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Mon Jan 15 17:59:06 2007 @@ -1324,7 +1324,7 @@ if test_timeout.skip_expected: self.expected.add('test_timeout') - if sys.maxint == 9223372036854775807L: + if sys.maxint == 9223372036854775807: self.expected.add('test_rgbimg') self.expected.add('test_imageop') Modified: python/branches/p3yk/Lib/test/seq_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/seq_tests.py (original) +++ python/branches/p3yk/Lib/test/seq_tests.py Mon Jan 15 17:59:06 2007 @@ -138,10 +138,10 @@ u = self.type2test([0, 1, 2, 3, 4]) for i in xrange(len(u)): self.assertEqual(u[i], i) - self.assertEqual(u[long(i)], i) + self.assertEqual(u[int(i)], i) for i in xrange(-len(u), -1): self.assertEqual(u[i], len(u)+i) - self.assertEqual(u[long(i)], len(u)+i) + self.assertEqual(u[int(i)], len(u)+i) self.assertRaises(IndexError, u.__getitem__, -len(u)-1) self.assertRaises(IndexError, u.__getitem__, len(u)) self.assertRaises(ValueError, u.__getitem__, slice(0,10,0)) @@ -189,12 +189,12 @@ self.assertEqual(u[-100:100:], u) self.assertEqual(u[100:-100:-1], u[::-1]) self.assertEqual(u[-100:100:-1], self.type2test([])) - self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4])) + self.assertEqual(u[-100:100:2], self.type2test([0, 2, 4])) # Test extreme cases with long ints a = self.type2test([0,1,2,3,4]) - self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2])) - self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4])) + self.assertEqual(a[ -pow(2,128): 3 ], self.type2test([0,1,2])) + self.assertEqual(a[ 3: pow(2,145) ], self.type2test([3,4])) self.assertRaises(TypeError, u.__getslice__) @@ -254,16 +254,16 @@ self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0])) self.assertEqual(self.type2test(), u2*0) self.assertEqual(self.type2test(), 0*u2) - self.assertEqual(self.type2test(), u2*0L) - self.assertEqual(self.type2test(), 0L*u2) + self.assertEqual(self.type2test(), u2*0) + self.assertEqual(self.type2test(), 0*u2) + self.assertEqual(u2, u2*1) + self.assertEqual(u2, 1*u2) self.assertEqual(u2, u2*1) self.assertEqual(u2, 1*u2) - self.assertEqual(u2, u2*1L) - self.assertEqual(u2, 1L*u2) self.assertEqual(u2+u2, u2*2) self.assertEqual(u2+u2, 2*u2) - self.assertEqual(u2+u2, u2*2L) - self.assertEqual(u2+u2, 2L*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) @@ -308,10 +308,10 @@ def test_subscript(self): a = self.type2test([10, 11]) - self.assertEqual(a.__getitem__(0L), 10) - self.assertEqual(a.__getitem__(1L), 11) - self.assertEqual(a.__getitem__(-2L), 10) - self.assertEqual(a.__getitem__(-1L), 11) + self.assertEqual(a.__getitem__(0), 10) + self.assertEqual(a.__getitem__(1), 11) + self.assertEqual(a.__getitem__(-2), 10) + self.assertEqual(a.__getitem__(-1), 11) self.assertRaises(IndexError, a.__getitem__, -3) self.assertRaises(IndexError, a.__getitem__, 3) self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10])) Modified: python/branches/p3yk/Lib/test/string_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/string_tests.py (original) +++ python/branches/p3yk/Lib/test/string_tests.py Mon Jan 15 17:59:06 2007 @@ -12,7 +12,7 @@ def __getitem__(self, i): return self.seq[i] class BadSeq1(Sequence): - def __init__(self): self.seq = [7, 'hello', 123L] + def __init__(self): self.seq = [7, 'hello', 123] class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] @@ -902,7 +902,7 @@ 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'a', 'abc', '__getitem__', 0) 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)) @@ -965,7 +965,7 @@ self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', 7) - self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L])) + self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123])) try: def f(): yield 4 + "" Modified: python/branches/p3yk/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk/Lib/test/test_array.py (original) +++ python/branches/p3yk/Lib/test/test_array.py Mon Jan 15 17:59:06 2007 @@ -61,7 +61,7 @@ bi = a.buffer_info() self.assert_(isinstance(bi, tuple)) self.assertEqual(len(bi), 2) - self.assert_(isinstance(bi[0], (int, long))) + self.assert_(isinstance(bi[0], (int, int))) self.assert_(isinstance(bi[1], int)) self.assertEqual(bi[1], len(a)) @@ -323,9 +323,9 @@ def test_getitem(self): a = array.array(self.typecode, self.example) self.assertEntryEqual(a[0], self.example[0]) - self.assertEntryEqual(a[0L], self.example[0]) + self.assertEntryEqual(a[0], self.example[0]) + self.assertEntryEqual(a[-1], self.example[-1]) self.assertEntryEqual(a[-1], self.example[-1]) - self.assertEntryEqual(a[-1L], self.example[-1]) self.assertEntryEqual(a[len(self.example)-1], self.example[-1]) self.assertEntryEqual(a[-len(self.example)], self.example[0]) self.assertRaises(TypeError, a.__getitem__) @@ -338,7 +338,7 @@ self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) - a[0L] = a[-1] + a[0] = a[-1] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) @@ -346,7 +346,7 @@ self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) - a[-1L] = a[0] + a[-1] = a[0] self.assertEntryEqual(a[0], a[-1]) a = array.array(self.typecode, self.example) @@ -777,7 +777,7 @@ self.assertEqual(a[3::-2], array.array(self.typecode, [3,1])) self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) - self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4])) + self.assertEqual(a[-100:100:2], array.array(self.typecode, [0,2,4])) self.assertEqual(a[1000:2000:2], array.array(self.typecode, [])) self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, [])) @@ -863,8 +863,8 @@ def test_overflow(self): a = array.array(self.typecode) - lower = -1 * long(pow(2, a.itemsize * 8 - 1)) - upper = long(pow(2, a.itemsize * 8 - 1)) - 1L + lower = -1 * int(pow(2, a.itemsize * 8 - 1)) + upper = int(pow(2, a.itemsize * 8 - 1)) - 1 self.check_overflow(lower, upper) class UnsignedNumberTest(NumberTest): @@ -876,7 +876,7 @@ def test_overflow(self): a = array.array(self.typecode) lower = 0 - upper = long(pow(2, a.itemsize * 8)) - 1L + upper = int(pow(2, a.itemsize * 8)) - 1 self.check_overflow(lower, upper) Modified: python/branches/p3yk/Lib/test/test_ast.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ast.py (original) +++ python/branches/p3yk/Lib/test/test_ast.py Mon Jan 15 17:59:06 2007 @@ -2,7 +2,7 @@ import _ast def to_tuple(t): - if t is None or isinstance(t, (basestring, int, long, complex)): + if t is None or isinstance(t, (basestring, int, int, complex)): return t elif isinstance(t, list): return [to_tuple(e) for e in t] @@ -93,7 +93,7 @@ # Call "f(1,2,c=3,*d,**e)", # Num - "10L", + "10", # Str "'string'", # Attribute Modified: python/branches/p3yk/Lib/test/test_asynchat.py ============================================================================== --- python/branches/p3yk/Lib/test/test_asynchat.py (original) +++ python/branches/p3yk/Lib/test/test_asynchat.py Mon Jan 15 17:59:06 2007 @@ -77,7 +77,7 @@ s = echo_server() s.start() time.sleep(1) # Give server time to initialize - c = echo_client(6L) + c = echo_client(6) c.push("hello ") c.push("world\n") asyncore.loop() Modified: python/branches/p3yk/Lib/test/test_bigmem.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bigmem.py (original) +++ python/branches/p3yk/Lib/test/test_bigmem.py Mon Jan 15 17:59:06 2007 @@ -866,13 +866,13 @@ @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) def test_index(self, size): - l = [1L, 2L, 3L, 4L, 5L] * size + l = [1, 2, 3, 4, 5] * size size *= 5 self.assertEquals(l.index(1), 0) self.assertEquals(l.index(5, size - 5), size - 1) self.assertEquals(l.index(5, size - 5, size), size - 1) self.assertRaises(ValueError, l.index, 1, size - 4, size) - self.assertRaises(ValueError, l.index, 6L) + self.assertRaises(ValueError, l.index, 6) # This tests suffers from overallocation, just like test_append. @bigmemtest(minsize=_2G + 10, memuse=9) Modified: python/branches/p3yk/Lib/test/test_binop.py ============================================================================== --- python/branches/p3yk/Lib/test/test_binop.py (original) +++ python/branches/p3yk/Lib/test/test_binop.py Mon Jan 15 17:59:06 2007 @@ -11,11 +11,11 @@ def isint(x): """Test whether an object is an instance of int or long.""" - return isinstance(x, int) or isinstance(x, long) + return isinstance(x, int) or isinstance(x, int) def isnum(x): """Test whether an object is an instance of a built-in numeric type.""" - for T in int, long, float, complex: + for T in int, int, float, complex: if isinstance(x, T): return 1 return 0 @@ -30,7 +30,7 @@ __slots__ = ['_Rat__num', '_Rat__den'] - def __init__(self, num=0L, den=1L): + def __init__(self, num=0, den=1): """Constructor: Rat([num[, den]]). The arguments must be ints or longs, and default to (0, 1).""" @@ -42,8 +42,8 @@ if den == 0: raise ZeroDivisionError, "zero denominator" g = gcd(den, num) - self.__num = long(num//g) - self.__den = long(den//g) + self.__num = int(num//g) + self.__den = int(den//g) def _get_num(self): """Accessor function for read-only 'num' attribute of Rat.""" @@ -80,7 +80,7 @@ def __long__(self): """Convert a Rat to an long; self.den must be 1.""" if self.__den == 1: - return long(self.__num) + return int(self.__num) raise ValueError, "can't convert %s to long" % repr(self) def __add__(self, other): @@ -225,7 +225,7 @@ a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) - a = Rat(10L, 15L) + a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10, -15) Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Mon Jan 15 17:59:06 2007 @@ -122,9 +122,9 @@ self.assertEqual(abs(3.14), 3.14) self.assertEqual(abs(-3.14), 3.14) # long - self.assertEqual(abs(0L), 0L) - self.assertEqual(abs(1234L), 1234L) - self.assertEqual(abs(-1234L), 1234L) + self.assertEqual(abs(0), 0) + self.assertEqual(abs(1234), 1234) + self.assertEqual(abs(-1234), 1234) # str self.assertRaises(TypeError, abs, 'a') @@ -235,15 +235,15 @@ self.assertEqual(divmod(12, -7), (-2, -2)) self.assertEqual(divmod(-12, -7), (1, -5)) - self.assertEqual(divmod(12L, 7L), (1L, 5L)) - self.assertEqual(divmod(-12L, 7L), (-2L, 2L)) - self.assertEqual(divmod(12L, -7L), (-2L, -2L)) - self.assertEqual(divmod(-12L, -7L), (1L, -5L)) - - self.assertEqual(divmod(12, 7L), (1, 5L)) - self.assertEqual(divmod(-12, 7L), (-2, 2L)) - self.assertEqual(divmod(12L, -7), (-2L, -2)) - self.assertEqual(divmod(-12L, -7), (1L, -5)) + self.assertEqual(divmod(12, 7), (1, 5)) + self.assertEqual(divmod(-12, 7), (-2, 2)) + self.assertEqual(divmod(12, -7), (-2, -2)) + self.assertEqual(divmod(-12, -7), (1, -5)) + + self.assertEqual(divmod(12, 7), (1, 5)) + self.assertEqual(divmod(-12, 7), (-2, 2)) + self.assertEqual(divmod(12, -7), (-2, -2)) + self.assertEqual(divmod(-12, -7), (1, -5)) self.assertEqual(divmod(-sys.maxint-1, -1), (sys.maxint+1, 0)) @@ -538,7 +538,7 @@ def test_float(self): self.assertEqual(float(3.14), 3.14) self.assertEqual(float(314), 314.0) - self.assertEqual(float(314L), 314.0) + self.assertEqual(float(314), 314.0) self.assertEqual(float(" 3.14 "), 3.14) self.assertRaises(ValueError, float, " 0x3.1 ") self.assertRaises(ValueError, float, " -0x3.p-1 ") @@ -624,7 +624,7 @@ def test_hash(self): hash(None) - self.assertEqual(hash(1), hash(1L)) + self.assertEqual(hash(1), hash(1)) self.assertEqual(hash(1), hash(1.0)) hash('spam') if have_unicode: @@ -642,22 +642,22 @@ def __hash__(self): return 2**100 self.assertEquals(type(hash(Y())), int) - class Z(long): + class Z(int): def __hash__(self): return self - self.assertEquals(hash(Z(42)), hash(42L)) + self.assertEquals(hash(Z(42)), hash(42)) def test_hex(self): self.assertEqual(hex(16), '0x10') - self.assertEqual(hex(16L), '0x10') + self.assertEqual(hex(16), '0x10') + self.assertEqual(hex(-16), '-0x10') self.assertEqual(hex(-16), '-0x10') - self.assertEqual(hex(-16L), '-0x10') self.assertRaises(TypeError, hex, {}) def test_id(self): id(None) id(1) - id(1L) + id(1) id(1.0) id('spam') id((0,1,2,3)) @@ -667,7 +667,7 @@ def test_int(self): self.assertEqual(int(314), 314) self.assertEqual(int(3.14), 3) - self.assertEqual(int(314L), 314) + self.assertEqual(int(314), 314) # Check that conversion from float truncates towards zero self.assertEqual(int(-3.14), -3) self.assertEqual(int(3.9), 3) @@ -675,9 +675,9 @@ self.assertEqual(int(3.5), 3) self.assertEqual(int(-3.5), -3) # Different base: - self.assertEqual(int("10",16), 16L) + self.assertEqual(int("10",16), 16) if have_unicode: - self.assertEqual(int(unicode("10"),16), 16L) + self.assertEqual(int(unicode("10"),16), 16) # Test conversion from strings and various anomalies for s, v in L: for sign in "", "+", "-": @@ -700,9 +700,9 @@ # should return long x = int(1e100) - self.assert_(isinstance(x, long)) + self.assert_(isinstance(x, int)) x = int(-1e100) - self.assert_(isinstance(x, long)) + self.assert_(isinstance(x, int)) # SF bug 434186: 0x80000000/2 != 0x80000000>>1. @@ -720,11 +720,11 @@ self.assertRaises(ValueError, int, '123\x00 245', 20) x = int('1' * 600) - self.assert_(isinstance(x, long)) + self.assert_(isinstance(x, int)) if have_unicode: x = int(unichr(0x661) * 600) - self.assert_(isinstance(x, long)) + self.assert_(isinstance(x, int)) self.assertRaises(TypeError, int, 1, 12) @@ -735,79 +735,79 @@ # Various representations of 2**32 evaluated to 0 # rather than 2**32 in previous versions - self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296L) - self.assertEqual(int('102002022201221111211', 3), 4294967296L) - self.assertEqual(int('10000000000000000', 4), 4294967296L) - self.assertEqual(int('32244002423141', 5), 4294967296L) - self.assertEqual(int('1550104015504', 6), 4294967296L) - self.assertEqual(int('211301422354', 7), 4294967296L) - self.assertEqual(int('40000000000', 8), 4294967296L) - self.assertEqual(int('12068657454', 9), 4294967296L) - self.assertEqual(int('4294967296', 10), 4294967296L) - self.assertEqual(int('1904440554', 11), 4294967296L) - self.assertEqual(int('9ba461594', 12), 4294967296L) - self.assertEqual(int('535a79889', 13), 4294967296L) - self.assertEqual(int('2ca5b7464', 14), 4294967296L) - self.assertEqual(int('1a20dcd81', 15), 4294967296L) - self.assertEqual(int('100000000', 16), 4294967296L) - self.assertEqual(int('a7ffda91', 17), 4294967296L) - self.assertEqual(int('704he7g4', 18), 4294967296L) - self.assertEqual(int('4f5aff66', 19), 4294967296L) - self.assertEqual(int('3723ai4g', 20), 4294967296L) - self.assertEqual(int('281d55i4', 21), 4294967296L) - self.assertEqual(int('1fj8b184', 22), 4294967296L) - self.assertEqual(int('1606k7ic', 23), 4294967296L) - self.assertEqual(int('mb994ag', 24), 4294967296L) - self.assertEqual(int('hek2mgl', 25), 4294967296L) - self.assertEqual(int('dnchbnm', 26), 4294967296L) - self.assertEqual(int('b28jpdm', 27), 4294967296L) - self.assertEqual(int('8pfgih4', 28), 4294967296L) - self.assertEqual(int('76beigg', 29), 4294967296L) - self.assertEqual(int('5qmcpqg', 30), 4294967296L) - self.assertEqual(int('4q0jto4', 31), 4294967296L) - self.assertEqual(int('4000000', 32), 4294967296L) - self.assertEqual(int('3aokq94', 33), 4294967296L) - self.assertEqual(int('2qhxjli', 34), 4294967296L) - self.assertEqual(int('2br45qb', 35), 4294967296L) - self.assertEqual(int('1z141z4', 36), 4294967296L) + self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296) + self.assertEqual(int('102002022201221111211', 3), 4294967296) + self.assertEqual(int('10000000000000000', 4), 4294967296) + self.assertEqual(int('32244002423141', 5), 4294967296) + self.assertEqual(int('1550104015504', 6), 4294967296) + self.assertEqual(int('211301422354', 7), 4294967296) + self.assertEqual(int('40000000000', 8), 4294967296) + self.assertEqual(int('12068657454', 9), 4294967296) + self.assertEqual(int('4294967296', 10), 4294967296) + self.assertEqual(int('1904440554', 11), 4294967296) + self.assertEqual(int('9ba461594', 12), 4294967296) + self.assertEqual(int('535a79889', 13), 4294967296) + self.assertEqual(int('2ca5b7464', 14), 4294967296) + self.assertEqual(int('1a20dcd81', 15), 4294967296) + self.assertEqual(int('100000000', 16), 4294967296) + self.assertEqual(int('a7ffda91', 17), 4294967296) + self.assertEqual(int('704he7g4', 18), 4294967296) + self.assertEqual(int('4f5aff66', 19), 4294967296) + self.assertEqual(int('3723ai4g', 20), 4294967296) + self.assertEqual(int('281d55i4', 21), 4294967296) + self.assertEqual(int('1fj8b184', 22), 4294967296) + self.assertEqual(int('1606k7ic', 23), 4294967296) + self.assertEqual(int('mb994ag', 24), 4294967296) + self.assertEqual(int('hek2mgl', 25), 4294967296) + self.assertEqual(int('dnchbnm', 26), 4294967296) + self.assertEqual(int('b28jpdm', 27), 4294967296) + self.assertEqual(int('8pfgih4', 28), 4294967296) + self.assertEqual(int('76beigg', 29), 4294967296) + self.assertEqual(int('5qmcpqg', 30), 4294967296) + self.assertEqual(int('4q0jto4', 31), 4294967296) + self.assertEqual(int('4000000', 32), 4294967296) + self.assertEqual(int('3aokq94', 33), 4294967296) + self.assertEqual(int('2qhxjli', 34), 4294967296) + self.assertEqual(int('2br45qb', 35), 4294967296) + self.assertEqual(int('1z141z4', 36), 4294967296) # SF bug 1334662: int(string, base) wrong answers # Checks for proper evaluation of 2**32 + 1 - self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297L) - self.assertEqual(int('102002022201221111212', 3), 4294967297L) - self.assertEqual(int('10000000000000001', 4), 4294967297L) - self.assertEqual(int('32244002423142', 5), 4294967297L) - self.assertEqual(int('1550104015505', 6), 4294967297L) - self.assertEqual(int('211301422355', 7), 4294967297L) - self.assertEqual(int('40000000001', 8), 4294967297L) - self.assertEqual(int('12068657455', 9), 4294967297L) - self.assertEqual(int('4294967297', 10), 4294967297L) - self.assertEqual(int('1904440555', 11), 4294967297L) - self.assertEqual(int('9ba461595', 12), 4294967297L) - self.assertEqual(int('535a7988a', 13), 4294967297L) - self.assertEqual(int('2ca5b7465', 14), 4294967297L) - self.assertEqual(int('1a20dcd82', 15), 4294967297L) - self.assertEqual(int('100000001', 16), 4294967297L) - self.assertEqual(int('a7ffda92', 17), 4294967297L) - self.assertEqual(int('704he7g5', 18), 4294967297L) - self.assertEqual(int('4f5aff67', 19), 4294967297L) - self.assertEqual(int('3723ai4h', 20), 4294967297L) - self.assertEqual(int('281d55i5', 21), 4294967297L) - self.assertEqual(int('1fj8b185', 22), 4294967297L) - self.assertEqual(int('1606k7id', 23), 4294967297L) - self.assertEqual(int('mb994ah', 24), 4294967297L) - self.assertEqual(int('hek2mgm', 25), 4294967297L) - self.assertEqual(int('dnchbnn', 26), 4294967297L) - self.assertEqual(int('b28jpdn', 27), 4294967297L) - self.assertEqual(int('8pfgih5', 28), 4294967297L) - self.assertEqual(int('76beigh', 29), 4294967297L) - self.assertEqual(int('5qmcpqh', 30), 4294967297L) - self.assertEqual(int('4q0jto5', 31), 4294967297L) - self.assertEqual(int('4000001', 32), 4294967297L) - self.assertEqual(int('3aokq95', 33), 4294967297L) - self.assertEqual(int('2qhxjlj', 34), 4294967297L) - self.assertEqual(int('2br45qc', 35), 4294967297L) - self.assertEqual(int('1z141z5', 36), 4294967297L) + self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297) + self.assertEqual(int('102002022201221111212', 3), 4294967297) + self.assertEqual(int('10000000000000001', 4), 4294967297) + self.assertEqual(int('32244002423142', 5), 4294967297) + self.assertEqual(int('1550104015505', 6), 4294967297) + self.assertEqual(int('211301422355', 7), 4294967297) + self.assertEqual(int('40000000001', 8), 4294967297) + self.assertEqual(int('12068657455', 9), 4294967297) + self.assertEqual(int('4294967297', 10), 4294967297) + self.assertEqual(int('1904440555', 11), 4294967297) + self.assertEqual(int('9ba461595', 12), 4294967297) + self.assertEqual(int('535a7988a', 13), 4294967297) + self.assertEqual(int('2ca5b7465', 14), 4294967297) + self.assertEqual(int('1a20dcd82', 15), 4294967297) + self.assertEqual(int('100000001', 16), 4294967297) + self.assertEqual(int('a7ffda92', 17), 4294967297) + self.assertEqual(int('704he7g5', 18), 4294967297) + self.assertEqual(int('4f5aff67', 19), 4294967297) + self.assertEqual(int('3723ai4h', 20), 4294967297) + self.assertEqual(int('281d55i5', 21), 4294967297) + self.assertEqual(int('1fj8b185', 22), 4294967297) + self.assertEqual(int('1606k7id', 23), 4294967297) + self.assertEqual(int('mb994ah', 24), 4294967297) + self.assertEqual(int('hek2mgm', 25), 4294967297) + self.assertEqual(int('dnchbnn', 26), 4294967297) + self.assertEqual(int('b28jpdn', 27), 4294967297) + self.assertEqual(int('8pfgih5', 28), 4294967297) + self.assertEqual(int('76beigh', 29), 4294967297) + self.assertEqual(int('5qmcpqh', 30), 4294967297) + self.assertEqual(int('4q0jto5', 31), 4294967297) + self.assertEqual(int('4000001', 32), 4294967297) + self.assertEqual(int('3aokq95', 33), 4294967297) + self.assertEqual(int('2qhxjlj', 34), 4294967297) + self.assertEqual(int('2br45qc', 35), 4294967297) + self.assertEqual(int('1z141z5', 36), 4294967297) def test_intconversion(self): # Test __int__() @@ -829,7 +829,7 @@ class Foo4(int): def __int__(self): - return 42L + return 42 class Foo5(int): def __int__(self): @@ -839,7 +839,7 @@ self.assertEqual(int(Foo1()), 42) self.assertEqual(int(Foo2()), 42) self.assertEqual(int(Foo3()), 0) - self.assertEqual(int(Foo4()), 42L) + self.assertEqual(int(Foo4()), 42) self.assertRaises(TypeError, int, Foo5()) def test_iter(self): @@ -935,32 +935,32 @@ self.assertEqual(x, []) def test_long(self): - self.assertEqual(long(314), 314L) - self.assertEqual(long(3.14), 3L) - self.assertEqual(long(314L), 314L) + self.assertEqual(int(314), 314) + self.assertEqual(int(3.14), 3) + self.assertEqual(int(314), 314) # Check that conversion from float truncates towards zero - self.assertEqual(long(-3.14), -3L) - self.assertEqual(long(3.9), 3L) - self.assertEqual(long(-3.9), -3L) - self.assertEqual(long(3.5), 3L) - self.assertEqual(long(-3.5), -3L) - self.assertEqual(long("-3"), -3L) + self.assertEqual(int(-3.14), -3) + self.assertEqual(int(3.9), 3) + self.assertEqual(int(-3.9), -3) + self.assertEqual(int(3.5), 3) + self.assertEqual(int(-3.5), -3) + self.assertEqual(int("-3"), -3) if have_unicode: - self.assertEqual(long(unicode("-3")), -3L) + self.assertEqual(int(unicode("-3")), -3) # Different base: - self.assertEqual(long("10",16), 16L) + self.assertEqual(int("10",16), 16) if have_unicode: - self.assertEqual(long(unicode("10"),16), 16L) + self.assertEqual(int(unicode("10"),16), 16) # Check conversions from string (same test set as for int(), and then some) LL = [ - ('1' + '0'*20, 10L**20), - ('1' + '0'*100, 10L**100) + ('1' + '0'*20, 10**20), + ('1' + '0'*100, 10**100) ] L2 = L[:] if have_unicode: L2 += [ - (unicode('1') + unicode('0')*20, 10L**20), - (unicode('1') + unicode('0')*100, 10L**100), + (unicode('1') + unicode('0')*20, 10**20), + (unicode('1') + unicode('0')*100, 10**100), ] for s, v in L2 + LL: for sign in "", "+", "-": @@ -970,120 +970,120 @@ if sign == "-" and v is not ValueError: vv = -v try: - self.assertEqual(long(ss), long(vv)) + self.assertEqual(int(ss), int(vv)) except v: pass - self.assertRaises(ValueError, long, '123\0') - self.assertRaises(ValueError, long, '53', 40) - self.assertRaises(TypeError, long, 1, 12) + self.assertRaises(ValueError, int, '123\0') + self.assertRaises(ValueError, int, '53', 40) + self.assertRaises(TypeError, int, 1, 12) - self.assertEqual(long('100000000000000000000000000000000', 2), + self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296) - self.assertEqual(long('102002022201221111211', 3), 4294967296) - self.assertEqual(long('10000000000000000', 4), 4294967296) - self.assertEqual(long('32244002423141', 5), 4294967296) - self.assertEqual(long('1550104015504', 6), 4294967296) - self.assertEqual(long('211301422354', 7), 4294967296) - self.assertEqual(long('40000000000', 8), 4294967296) - self.assertEqual(long('12068657454', 9), 4294967296) - self.assertEqual(long('4294967296', 10), 4294967296) - self.assertEqual(long('1904440554', 11), 4294967296) - self.assertEqual(long('9ba461594', 12), 4294967296) - self.assertEqual(long('535a79889', 13), 4294967296) - self.assertEqual(long('2ca5b7464', 14), 4294967296) - self.assertEqual(long('1a20dcd81', 15), 4294967296) - self.assertEqual(long('100000000', 16), 4294967296) - self.assertEqual(long('a7ffda91', 17), 4294967296) - self.assertEqual(long('704he7g4', 18), 4294967296) - self.assertEqual(long('4f5aff66', 19), 4294967296) - self.assertEqual(long('3723ai4g', 20), 4294967296) - self.assertEqual(long('281d55i4', 21), 4294967296) - self.assertEqual(long('1fj8b184', 22), 4294967296) - self.assertEqual(long('1606k7ic', 23), 4294967296) - self.assertEqual(long('mb994ag', 24), 4294967296) - self.assertEqual(long('hek2mgl', 25), 4294967296) - self.assertEqual(long('dnchbnm', 26), 4294967296) - self.assertEqual(long('b28jpdm', 27), 4294967296) - self.assertEqual(long('8pfgih4', 28), 4294967296) - self.assertEqual(long('76beigg', 29), 4294967296) - self.assertEqual(long('5qmcpqg', 30), 4294967296) - self.assertEqual(long('4q0jto4', 31), 4294967296) - self.assertEqual(long('4000000', 32), 4294967296) - self.assertEqual(long('3aokq94', 33), 4294967296) - self.assertEqual(long('2qhxjli', 34), 4294967296) - self.assertEqual(long('2br45qb', 35), 4294967296) - self.assertEqual(long('1z141z4', 36), 4294967296) + self.assertEqual(int('102002022201221111211', 3), 4294967296) + self.assertEqual(int('10000000000000000', 4), 4294967296) + self.assertEqual(int('32244002423141', 5), 4294967296) + self.assertEqual(int('1550104015504', 6), 4294967296) + self.assertEqual(int('211301422354', 7), 4294967296) + self.assertEqual(int('40000000000', 8), 4294967296) + self.assertEqual(int('12068657454', 9), 4294967296) + self.assertEqual(int('4294967296', 10), 4294967296) + self.assertEqual(int('1904440554', 11), 4294967296) + self.assertEqual(int('9ba461594', 12), 4294967296) + self.assertEqual(int('535a79889', 13), 4294967296) + self.assertEqual(int('2ca5b7464', 14), 4294967296) + self.assertEqual(int('1a20dcd81', 15), 4294967296) + self.assertEqual(int('100000000', 16), 4294967296) + self.assertEqual(int('a7ffda91', 17), 4294967296) + self.assertEqual(int('704he7g4', 18), 4294967296) + self.assertEqual(int('4f5aff66', 19), 4294967296) + self.assertEqual(int('3723ai4g', 20), 4294967296) + self.assertEqual(int('281d55i4', 21), 4294967296) + self.assertEqual(int('1fj8b184', 22), 4294967296) + self.assertEqual(int('1606k7ic', 23), 4294967296) + self.assertEqual(int('mb994ag', 24), 4294967296) + self.assertEqual(int('hek2mgl', 25), 4294967296) + self.assertEqual(int('dnchbnm', 26), 4294967296) + self.assertEqual(int('b28jpdm', 27), 4294967296) + self.assertEqual(int('8pfgih4', 28), 4294967296) + self.assertEqual(int('76beigg', 29), 4294967296) + self.assertEqual(int('5qmcpqg', 30), 4294967296) + self.assertEqual(int('4q0jto4', 31), 4294967296) + self.assertEqual(int('4000000', 32), 4294967296) + self.assertEqual(int('3aokq94', 33), 4294967296) + self.assertEqual(int('2qhxjli', 34), 4294967296) + self.assertEqual(int('2br45qb', 35), 4294967296) + self.assertEqual(int('1z141z4', 36), 4294967296) - self.assertEqual(long('100000000000000000000000000000001', 2), + self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297) - self.assertEqual(long('102002022201221111212', 3), 4294967297) - self.assertEqual(long('10000000000000001', 4), 4294967297) - self.assertEqual(long('32244002423142', 5), 4294967297) - self.assertEqual(long('1550104015505', 6), 4294967297) - self.assertEqual(long('211301422355', 7), 4294967297) - self.assertEqual(long('40000000001', 8), 4294967297) - self.assertEqual(long('12068657455', 9), 4294967297) - self.assertEqual(long('4294967297', 10), 4294967297) - self.assertEqual(long('1904440555', 11), 4294967297) - self.assertEqual(long('9ba461595', 12), 4294967297) - self.assertEqual(long('535a7988a', 13), 4294967297) - self.assertEqual(long('2ca5b7465', 14), 4294967297) - self.assertEqual(long('1a20dcd82', 15), 4294967297) - self.assertEqual(long('100000001', 16), 4294967297) - self.assertEqual(long('a7ffda92', 17), 4294967297) - self.assertEqual(long('704he7g5', 18), 4294967297) - self.assertEqual(long('4f5aff67', 19), 4294967297) - self.assertEqual(long('3723ai4h', 20), 4294967297) - self.assertEqual(long('281d55i5', 21), 4294967297) - self.assertEqual(long('1fj8b185', 22), 4294967297) - self.assertEqual(long('1606k7id', 23), 4294967297) - self.assertEqual(long('mb994ah', 24), 4294967297) - self.assertEqual(long('hek2mgm', 25), 4294967297) - self.assertEqual(long('dnchbnn', 26), 4294967297) - self.assertEqual(long('b28jpdn', 27), 4294967297) - self.assertEqual(long('8pfgih5', 28), 4294967297) - self.assertEqual(long('76beigh', 29), 4294967297) - self.assertEqual(long('5qmcpqh', 30), 4294967297) - self.assertEqual(long('4q0jto5', 31), 4294967297) - self.assertEqual(long('4000001', 32), 4294967297) - self.assertEqual(long('3aokq95', 33), 4294967297) - self.assertEqual(long('2qhxjlj', 34), 4294967297) - self.assertEqual(long('2br45qc', 35), 4294967297) - self.assertEqual(long('1z141z5', 36), 4294967297) + self.assertEqual(int('102002022201221111212', 3), 4294967297) + self.assertEqual(int('10000000000000001', 4), 4294967297) + self.assertEqual(int('32244002423142', 5), 4294967297) + self.assertEqual(int('1550104015505', 6), 4294967297) + self.assertEqual(int('211301422355', 7), 4294967297) + self.assertEqual(int('40000000001', 8), 4294967297) + self.assertEqual(int('12068657455', 9), 4294967297) + self.assertEqual(int('4294967297', 10), 4294967297) + self.assertEqual(int('1904440555', 11), 4294967297) + self.assertEqual(int('9ba461595', 12), 4294967297) + self.assertEqual(int('535a7988a', 13), 4294967297) + self.assertEqual(int('2ca5b7465', 14), 4294967297) + self.assertEqual(int('1a20dcd82', 15), 4294967297) + self.assertEqual(int('100000001', 16), 4294967297) + self.assertEqual(int('a7ffda92', 17), 4294967297) + self.assertEqual(int('704he7g5', 18), 4294967297) + self.assertEqual(int('4f5aff67', 19), 4294967297) + self.assertEqual(int('3723ai4h', 20), 4294967297) + self.assertEqual(int('281d55i5', 21), 4294967297) + self.assertEqual(int('1fj8b185', 22), 4294967297) + self.assertEqual(int('1606k7id', 23), 4294967297) + self.assertEqual(int('mb994ah', 24), 4294967297) + self.assertEqual(int('hek2mgm', 25), 4294967297) + self.assertEqual(int('dnchbnn', 26), 4294967297) + self.assertEqual(int('b28jpdn', 27), 4294967297) + self.assertEqual(int('8pfgih5', 28), 4294967297) + self.assertEqual(int('76beigh', 29), 4294967297) + self.assertEqual(int('5qmcpqh', 30), 4294967297) + self.assertEqual(int('4q0jto5', 31), 4294967297) + self.assertEqual(int('4000001', 32), 4294967297) + self.assertEqual(int('3aokq95', 33), 4294967297) + self.assertEqual(int('2qhxjlj', 34), 4294967297) + self.assertEqual(int('2br45qc', 35), 4294967297) + self.assertEqual(int('1z141z5', 36), 4294967297) def test_longconversion(self): # Test __long__() class Foo0: def __long__(self): - return 42L + return 42 class Foo1(object): def __long__(self): - return 42L + return 42 - class Foo2(long): + class Foo2(int): def __long__(self): - return 42L + return 42 - class Foo3(long): + class Foo3(int): def __long__(self): return self - class Foo4(long): + class Foo4(int): def __long__(self): return 42 - class Foo5(long): + class Foo5(int): def __long__(self): return 42. - self.assertEqual(long(Foo0()), 42L) - self.assertEqual(long(Foo1()), 42L) + self.assertEqual(int(Foo0()), 42) + self.assertEqual(int(Foo1()), 42) # XXX invokes __int__ now # self.assertEqual(long(Foo2()), 42L) - self.assertEqual(long(Foo3()), 0) + self.assertEqual(int(Foo3()), 0) # XXX likewise # self.assertEqual(long(Foo4()), 42) # self.assertRaises(TypeError, long, Foo5()) @@ -1174,9 +1174,9 @@ self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) - self.assertEqual(max(1, 2L, 3.0), 3.0) - self.assertEqual(max(1L, 2.0, 3), 3) - self.assertEqual(max(1.0, 2, 3L), 3L) + self.assertEqual(max(1, 2, 3.0), 3.0) + self.assertEqual(max(1, 2.0, 3), 3) + self.assertEqual(max(1.0, 2, 3), 3) for stmt in ( "max(key=int)", # no args @@ -1208,9 +1208,9 @@ self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) - self.assertEqual(min(1, 2L, 3.0), 1) - self.assertEqual(min(1L, 2.0, 3), 1L) - self.assertEqual(min(1.0, 2, 3L), 1.0) + self.assertEqual(min(1, 2, 3.0), 1) + self.assertEqual(min(1, 2.0, 3), 1) + self.assertEqual(min(1.0, 2, 3), 1.0) self.assertRaises(TypeError, min) self.assertRaises(TypeError, min, 42) @@ -1250,9 +1250,9 @@ def test_oct(self): self.assertEqual(oct(100), '0144') - self.assertEqual(oct(100L), '0144') + self.assertEqual(oct(100), '0144') + self.assertEqual(oct(-100), '-0144') self.assertEqual(oct(-100), '-0144') - self.assertEqual(oct(-100L), '-0144') self.assertRaises(TypeError, oct, ()) def write_testfile(self): @@ -1309,20 +1309,20 @@ self.assertEqual(pow(-2,2), 4) self.assertEqual(pow(-2,3), -8) - self.assertEqual(pow(0L,0), 1) - self.assertEqual(pow(0L,1), 0) - self.assertEqual(pow(1L,0), 1) - self.assertEqual(pow(1L,1), 1) - - self.assertEqual(pow(2L,0), 1) - self.assertEqual(pow(2L,10), 1024) - self.assertEqual(pow(2L,20), 1024*1024) - self.assertEqual(pow(2L,30), 1024*1024*1024) - - self.assertEqual(pow(-2L,0), 1) - self.assertEqual(pow(-2L,1), -2) - self.assertEqual(pow(-2L,2), 4) - self.assertEqual(pow(-2L,3), -8) + self.assertEqual(pow(0,0), 1) + self.assertEqual(pow(0,1), 0) + self.assertEqual(pow(1,0), 1) + self.assertEqual(pow(1,1), 1) + + self.assertEqual(pow(2,0), 1) + self.assertEqual(pow(2,10), 1024) + self.assertEqual(pow(2,20), 1024*1024) + self.assertEqual(pow(2,30), 1024*1024*1024) + + self.assertEqual(pow(-2,0), 1) + self.assertEqual(pow(-2,1), -2) + self.assertEqual(pow(-2,2), 4) + self.assertEqual(pow(-2,3), -8) self.assertAlmostEqual(pow(0.,0), 1.) self.assertAlmostEqual(pow(0.,1), 0.) @@ -1339,9 +1339,9 @@ self.assertAlmostEqual(pow(-2.,2), 4.) self.assertAlmostEqual(pow(-2.,3), -8.) - for x in 2, 2L, 2.0: - for y in 10, 10L, 10.0: - for z in 1000, 1000L, 1000.0: + for x in 2, 2, 2.0: + for y in 10, 10, 10.0: + for z in 1000, 1000, 1000.0: if isinstance(x, float) or \ isinstance(y, float) or \ isinstance(z, float): @@ -1351,8 +1351,8 @@ self.assertRaises(TypeError, pow, -1, -2, 3) self.assertRaises(ValueError, pow, 1, 2, 0) - self.assertRaises(TypeError, pow, -1L, -2L, 3L) - self.assertRaises(ValueError, pow, 1L, 2L, 0L) + self.assertRaises(TypeError, pow, -1, -2, 3) + self.assertRaises(ValueError, pow, 1, 2, 0) self.assertRaises(ValueError, pow, -342.43, 0.234) self.assertRaises(TypeError, pow) @@ -1371,12 +1371,12 @@ self.assertEqual(range(0, 2**100, -1), []) self.assertEqual(range(0, 2**100, -1), []) - a = long(10 * sys.maxint) - b = long(100 * sys.maxint) - c = long(50 * sys.maxint) + a = int(10 * sys.maxint) + b = int(100 * sys.maxint) + c = int(50 * sys.maxint) self.assertEqual(range(a, a+2), [a, a+1]) - self.assertEqual(range(a+2, a, -1L), [a+2, a+1]) + self.assertEqual(range(a+2, a, -1), [a+2, a+1]) self.assertEqual(range(a+4, a, -2), [a+4, a+2]) seq = range(a, b, c) @@ -1397,7 +1397,7 @@ self.assertRaises(TypeError, range) self.assertRaises(TypeError, range, 1, 2, 3, 4) self.assertRaises(ValueError, range, 1, 2, 0) - self.assertRaises(ValueError, range, a, a + 1, long(0)) + self.assertRaises(ValueError, range, a, a + 1, int(0)) class badzero(int): def __eq__(self, other): @@ -1428,7 +1428,7 @@ def test_repr(self): self.assertEqual(repr(''), '\'\'') self.assertEqual(repr(0), '0') - self.assertEqual(repr(0L), '0') + self.assertEqual(repr(0), '0') self.assertEqual(repr(()), '()') self.assertEqual(repr([]), '[]') self.assertEqual(repr({}), '{}') @@ -1484,7 +1484,7 @@ def test_str(self): self.assertEqual(str(''), '') self.assertEqual(str(0), '0') - self.assertEqual(str(0L), '0') + self.assertEqual(str(0), '0') self.assertEqual(str(()), '()') self.assertEqual(str([]), '[]') self.assertEqual(str({}), '{}') Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Mon Jan 15 17:59:06 2007 @@ -361,9 +361,9 @@ def test_contains(self): b = bytes("abc") self.failUnless(ord('a') in b) - self.failUnless(long(ord('a')) in b) + self.failUnless(int(ord('a')) in b) + self.failIf(200 in b) self.failIf(200 in b) - self.failIf(200L in b) self.assertRaises(ValueError, lambda: 300 in b) self.assertRaises(ValueError, lambda: -1 in b) self.assertRaises(TypeError, lambda: None in b) Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Mon Jan 15 17:59:06 2007 @@ -84,10 +84,6 @@ print "__float__:", args return 1.0 - def __long__(self, *args): - print "__long__:", args - return 1L - def __oct__(self, *args): print "__oct__:", args return '01' @@ -238,7 +234,7 @@ +testme abs(testme) int(testme) -long(testme) +int(testme) float(testme) oct(testme) hex(testme) @@ -289,7 +285,6 @@ def __int__(self): return None __float__ = __int__ - __long__ = __int__ __str__ = __int__ __repr__ = __int__ __oct__ = __int__ @@ -307,31 +302,11 @@ check_exc("int(BadTypeClass())", TypeError) check_exc("float(BadTypeClass())", TypeError) -check_exc("long(BadTypeClass())", TypeError) check_exc("str(BadTypeClass())", TypeError) check_exc("repr(BadTypeClass())", TypeError) check_exc("oct(BadTypeClass())", TypeError) check_exc("hex(BadTypeClass())", TypeError) -# mixing up ints and longs is okay -class IntLongMixClass: - def __int__(self): - return 0L - - def __long__(self): - return 0 - -try: - int(IntLongMixClass()) -except TypeError: - raise TestFailed, "TypeError should not be raised" - -try: - long(IntLongMixClass()) -except TypeError: - raise TestFailed, "TypeError should not be raised" - - # Test correct errors from hash() on objects with comparisons but no __hash__ class C0: Modified: python/branches/p3yk/Lib/test/test_code.py ============================================================================== --- python/branches/p3yk/Lib/test/test_code.py (original) +++ python/branches/p3yk/Lib/test/test_code.py Mon Jan 15 17:59:06 2007 @@ -70,7 +70,7 @@ ... 'doc string' ... 'not a docstring' ... 53 -... 53L +... 0x53 >>> dump(optimize_away.func_code) name: optimize_away Modified: python/branches/p3yk/Lib/test/test_compare.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compare.py (original) +++ python/branches/p3yk/Lib/test/test_compare.py Mon Jan 15 17:59:06 2007 @@ -17,7 +17,7 @@ return self.arg == other class ComparisonTest(unittest.TestCase): - set1 = [2, 2.0, 2L, 2+0j, Cmp(2.0)] + set1 = [2, 2.0, 2, 2+0j, Cmp(2.0)] set2 = [[1], (3,), None, Empty()] candidates = set1 + set2 Modified: python/branches/p3yk/Lib/test/test_compile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compile.py (original) +++ python/branches/p3yk/Lib/test/test_compile.py Mon Jan 15 17:59:06 2007 @@ -182,10 +182,8 @@ self.assertRaises(SyntaxError, eval, arg) self.assertEqual(eval("0777"), 511) - self.assertEqual(eval("0777L"), 511) self.assertEqual(eval("000777"), 511) self.assertEqual(eval("0xff"), 255) - self.assertEqual(eval("0xffL"), 255) self.assertEqual(eval("0XfF"), 255) self.assertEqual(eval("0777."), 777) self.assertEqual(eval("0777.0"), 777) @@ -212,19 +210,19 @@ if sys.maxint == 2147483647: # 32-bit machine all_one_bits = '0xffffffff' - self.assertEqual(eval(all_one_bits), 4294967295L) - self.assertEqual(eval("-" + all_one_bits), -4294967295L) + self.assertEqual(eval(all_one_bits), 4294967295) + self.assertEqual(eval("-" + all_one_bits), -4294967295) elif sys.maxint == 9223372036854775807: # 64-bit machine all_one_bits = '0xffffffffffffffff' - self.assertEqual(eval(all_one_bits), 18446744073709551615L) - self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L) + self.assertEqual(eval(all_one_bits), 18446744073709551615) + self.assertEqual(eval("-" + all_one_bits), -18446744073709551615) else: self.fail("How many bits *does* this machine have???") # Verify treatment of contant folding on -(sys.maxint+1) # i.e. -2147483648 on 32 bit platforms. Should return int, not long. self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 1)), int)) - self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 2)), long)) + self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 2)), int)) if sys.maxint == 9223372036854775807: def test_32_63_bit_values(self): Modified: python/branches/p3yk/Lib/test/test_complex.py ============================================================================== --- python/branches/p3yk/Lib/test/test_complex.py (original) +++ python/branches/p3yk/Lib/test/test_complex.py Mon Jan 15 17:59:06 2007 @@ -93,7 +93,7 @@ self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j) def test_richcompare(self): - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) + self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1<<10000) self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) @@ -180,25 +180,25 @@ self.assertAlmostEqual(complex("1+10j"), 1+10j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10.0), 10+0j) - self.assertAlmostEqual(complex(10L), 10+0j) + self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10+0j), 10+0j) self.assertAlmostEqual(complex(1,10), 1+10j) - self.assertAlmostEqual(complex(1,10L), 1+10j) + self.assertAlmostEqual(complex(1,10), 1+10j) + self.assertAlmostEqual(complex(1,10.0), 1+10j) + self.assertAlmostEqual(complex(1,10), 1+10j) + self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) - self.assertAlmostEqual(complex(1L,10), 1+10j) - self.assertAlmostEqual(complex(1L,10L), 1+10j) - self.assertAlmostEqual(complex(1L,10.0), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) - self.assertAlmostEqual(complex(1.0,10L), 1+10j) + self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10.0), 1+10j) self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) self.assertAlmostEqual(complex(3.14), 3.14+0j) self.assertAlmostEqual(complex(314), 314.0+0j) - self.assertAlmostEqual(complex(314L), 314.0+0j) + self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) - self.assertAlmostEqual(complex(314L, 0L), 314.0+0j) + self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0j, 3.14), 3.14j) @@ -232,7 +232,7 @@ self.assertRaises(ValueError, complex, '1+1j\0j') self.assertRaises(TypeError, int, 5+3j) - self.assertRaises(TypeError, long, 5+3j) + self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, float, 5+3j) self.assertRaises(ValueError, complex, "") self.assertRaises(TypeError, complex, None) Modified: python/branches/p3yk/Lib/test/test_cookielib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cookielib.py (original) +++ python/branches/p3yk/Lib/test/test_cookielib.py Mon Jan 15 17:59:06 2007 @@ -103,7 +103,7 @@ from cookielib import parse_ns_headers # quotes should be stripped - expected = [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]] + expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]] for hdr in [ 'foo=bar; expires=01 Jan 2040 22:23:32 GMT', 'foo=bar; expires="01 Jan 2040 22:23:32 GMT"', Modified: python/branches/p3yk/Lib/test/test_copy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_copy.py (original) +++ python/branches/p3yk/Lib/test/test_copy.py Mon Jan 15 17:59:06 2007 @@ -82,7 +82,7 @@ pass def f(): pass - tests = [None, 42, 2L**100, 3.14, True, False, 1j, + tests = [None, 42, 2**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10), Classic, max] for x in tests: @@ -255,7 +255,7 @@ pass def f(): pass - tests = [None, 42, 2L**100, 3.14, True, False, 1j, + tests = [None, 42, 2**100, 3.14, True, False, 1j, "hello", u"hello\u1234", f.func_code, NewStyle, xrange(10), Classic, max] for x in tests: Modified: python/branches/p3yk/Lib/test/test_copy_reg.py ============================================================================== --- python/branches/p3yk/Lib/test/test_copy_reg.py (original) +++ python/branches/p3yk/Lib/test/test_copy_reg.py Mon Jan 15 17:59:06 2007 @@ -96,7 +96,7 @@ e.restore() # Ensure invalid codes blow up. - for code in -1, 0, 0x80000000L: + for code in -1, 0, 0x80000000: self.assertRaises(ValueError, copy_reg.add_extension, mod, func, code) Modified: python/branches/p3yk/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_datetime.py (original) +++ python/branches/p3yk/Lib/test/test_datetime.py Mon Jan 15 17:59:06 2007 @@ -32,7 +32,7 @@ # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. -OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) +OTHERSTUFF = (10, 10, 34.5, "abc", {}, [], ()) ############################################################################# @@ -149,11 +149,11 @@ self.failIf(() == me) self.failUnless(() != me) - self.failUnless(me in [1, 20L, [], me]) - self.failIf(me not in [1, 20L, [], me]) + self.failUnless(me in [1, 20, [], me]) + self.failIf(me not in [1, 20, [], me]) - self.failUnless([] in [me, 1, 20L, []]) - self.failIf([] not in [me, 1, 20L, []]) + self.failUnless([] in [me, 1, 20, []]) + self.failIf([] not in [me, 1, 20, []]) def test_harmful_mixed_comparison(self): me = self.theclass(1, 1, 1) @@ -222,13 +222,13 @@ eq(td(0, 0, 60*1000000), b) eq(a*10, td(70)) eq(a*10, 10*a) - eq(a*10L, 10*a) + eq(a*10, 10*a) eq(b*10, td(0, 600)) eq(10*b, td(0, 600)) - eq(b*10L, td(0, 600)) + eq(b*10, td(0, 600)) eq(c*10, td(0, 0, 10000)) eq(10*c, td(0, 0, 10000)) - eq(c*10L, td(0, 0, 10000)) + eq(c*10, td(0, 0, 10000)) eq(a*-1, -a) eq(b*-2, -b-b) eq(c*-2, -c+-c) @@ -246,7 +246,7 @@ a = timedelta(42) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) @@ -263,7 +263,7 @@ # Divison of int by timedelta doesn't make sense. # Division by zero doesn't make sense. - for zero in 0, 0L: + for zero in 0, 0: self.assertRaises(TypeError, lambda: zero // a) self.assertRaises(ZeroDivisionError, lambda: a // zero) @@ -696,7 +696,7 @@ self.assertEqual(a - (a - day), day) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) @@ -1325,7 +1325,7 @@ self.assertEqual(a - (week + day + hour + millisec), (((a - week) - day) - hour) - millisec) # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: + for i in 1, 1, 1.0: self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: i+a) Modified: python/branches/p3yk/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decimal.py (original) +++ python/branches/p3yk/Lib/test/test_decimal.py Mon Jan 15 17:59:06 2007 @@ -907,8 +907,8 @@ self.assertEqual(int(d2), 15) #long - self.assertEqual(long(d1), 66) - self.assertEqual(long(d2), 15) + self.assertEqual(int(d1), 66) + self.assertEqual(int(d2), 15) #float self.assertEqual(float(d1), 66) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Mon Jan 15 17:59:06 2007 @@ -191,7 +191,7 @@ vereq(d, dict([("two", 2)], one=1)) vereq(d, dict([("one", 100), ("two", 200)], **d)) verify(d is not dict(**d)) - for badarg in 0, 0L, 0j, "0", [0], (0,): + for badarg in 0, 0, 0j, "0", [0], (0,): try: dict(badarg) except TypeError: @@ -264,7 +264,7 @@ del junk # Just make sure these don't blow up! - for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir: + for arg in 2, 2, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir: dir(arg) # Test dir on custom classes. Since these have object as a @@ -385,7 +385,6 @@ 'abs': 'abs', 'invert': '~', 'int': 'int', - 'long': 'long', 'float': 'float', 'oct': 'oct', 'hex': 'hex', @@ -423,7 +422,7 @@ class C(int): def __add__(self, other): return NotImplemented - vereq(C(5L), 5) + vereq(C(5), 5) try: C() + "" except TypeError: @@ -433,7 +432,7 @@ def longs(): if verbose: print "Testing long operations..." - numops(100L, 3L) + numops(100, 3) def floats(): if verbose: print "Testing float operations..." @@ -1263,10 +1262,10 @@ vereq(I(3)*I(2), 6) # Test handling of long*seq and seq*long - class L(long): + class L(int): pass - vereq("a"*L(2L), "aa") - vereq(L(2L)*"a", "aa") + vereq("a"*L(2), "aa") + vereq(L(2)*"a", "aa") vereq(2*L(3), 6) vereq(L(3)*2, 6) vereq(L(3)*L(2), 6) @@ -2041,7 +2040,7 @@ verify((hexint(0) << 12).__class__ is int) verify((hexint(0) >> 12).__class__ is int) - class octlong(long): + class octlong(int): __slots__ = [] def __str__(self): s = oct(self) @@ -2056,39 +2055,39 @@ # because the example uses a short int left argument.) vereq(str(5 + octlong(3000)), "05675") a = octlong(12345) - vereq(a, 12345L) - vereq(long(a), 12345L) - vereq(hash(a), hash(12345L)) - verify(long(a).__class__ is long) - verify((+a).__class__ is long) - verify((-a).__class__ is long) - verify((-octlong(0)).__class__ is long) - verify((a >> 0).__class__ is long) - verify((a << 0).__class__ is long) - verify((a - 0).__class__ is long) - verify((a * 1).__class__ is long) - verify((a ** 1).__class__ is long) - verify((a // 1).__class__ is long) - verify((1 * a).__class__ is long) - verify((a | 0).__class__ is long) - verify((a ^ 0).__class__ is long) - verify((a & -1L).__class__ is long) - verify((octlong(0) << 12).__class__ is long) - verify((octlong(0) >> 12).__class__ is long) - verify(abs(octlong(0)).__class__ is long) + vereq(a, 12345) + vereq(int(a), 12345) + vereq(hash(a), hash(12345)) + verify(int(a).__class__ is int) + verify((+a).__class__ is int) + verify((-a).__class__ is int) + verify((-octlong(0)).__class__ is int) + verify((a >> 0).__class__ is int) + verify((a << 0).__class__ is int) + verify((a - 0).__class__ is int) + verify((a * 1).__class__ is int) + verify((a ** 1).__class__ is int) + verify((a // 1).__class__ is int) + verify((1 * a).__class__ is int) + verify((a | 0).__class__ is int) + verify((a ^ 0).__class__ is int) + verify((a & -1).__class__ is int) + verify((octlong(0) << 12).__class__ is int) + verify((octlong(0) >> 12).__class__ is int) + verify(abs(octlong(0)).__class__ is int) # Because octlong overrides __add__, we can't check the absence of +0 # optimizations using octlong. - class longclone(long): + class longclone(int): pass a = longclone(1) - verify((a + 0).__class__ is long) - verify((0 + a).__class__ is long) + verify((a + 0).__class__ is int) + verify((0 + a).__class__ is int) # Check that negative clones don't segfault a = longclone(-1) vereq(a.__dict__, {}) - vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit + vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit class precfloat(float): __slots__ = ['prec'] @@ -2366,7 +2365,7 @@ print "Testing keyword args to basic type constructors ..." vereq(int(x=1), 1) vereq(float(x=2), 2.0) - vereq(long(x=3), 3L) + vereq(int(x=3), 3) vereq(complex(imag=42, real=666), complex(666, 42)) vereq(str(object=500), '500') vereq(unicode(string='abc', errors='strict'), u'abc') @@ -2374,7 +2373,7 @@ vereq(list(sequence=(0, 1, 2)), range(3)) # note: as of Python 2.3, dict() no longer has an "items" keyword arg - for constructor in (int, float, long, complex, str, unicode, + for constructor in (int, float, int, complex, str, unicode, tuple, list, file): try: constructor(bogus_keyword_arg=1) @@ -2472,37 +2471,37 @@ def __eq__(self, other): if isinstance(other, C): return self.value == other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value >= other return NotImplemented @@ -2550,37 +2549,37 @@ def __eq__(self, other): if isinstance(other, C): return self.value == other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value - if isinstance(other, int) or isinstance(other, long): + if isinstance(other, int) or isinstance(other, int): return self.value >= other return NotImplemented c1 = C(1) @@ -3250,11 +3249,11 @@ y *= 2 vereq(y, (x, 2)) y = x - y *= 3L - vereq(y, (x, 3L)) + y *= 3 + vereq(y, (x, 3)) y = x - y *= 1L<<100 - vereq(y, (x, 1L<<100)) + y *= 1<<100 + vereq(y, (x, 1<<100)) y = x y *= None vereq(y, (x, None)) @@ -3444,7 +3443,7 @@ def __pow__(self, *args): pass try: - pow(0L, UserLong(), 0L) + pow(0, UserLong(), 0) except: pass @@ -3956,7 +3955,7 @@ else: raise TestFailed("no TypeError from %r" % (expr,)) - N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors + N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger # ValueErrors instead of TypeErrors for metaclass in [type, types.ClassType]: Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Mon Jan 15 17:59:06 2007 @@ -314,7 +314,7 @@ # verify longs/ints get same value when key > 32 bits (for 64-bit archs) # see SF bug #689659 - x = 4503599627370496L + x = 4503599627370496 y = 4503599627370496 h = {x: 'anything', y: 'something else'} self.assertEqual(h[x], h[y]) @@ -371,7 +371,7 @@ def test_eq(self): self.assertEqual({}, {}) - self.assertEqual({1: 2}, {1L: 2L}) + self.assertEqual({1: 2}, {1: 2}) class Exc(Exception): pass Modified: python/branches/p3yk/Lib/test/test_format.py ============================================================================== --- python/branches/p3yk/Lib/test/test_format.py (original) +++ python/branches/p3yk/Lib/test/test_format.py Mon Jan 15 17:59:06 2007 @@ -57,14 +57,14 @@ # Formatting of long integers. Overflow is not ok overflowok = 0 -testboth("%x", 10L, "a") -testboth("%x", 100000000000L, "174876e800") -testboth("%o", 10L, "12") -testboth("%o", 100000000000L, "1351035564000") -testboth("%d", 10L, "10") -testboth("%d", 100000000000L, "100000000000") +testboth("%x", 10, "a") +testboth("%x", 100000000000, "174876e800") +testboth("%o", 10, "12") +testboth("%o", 100000000000, "1351035564000") +testboth("%d", 10, "10") +testboth("%d", 100000000000, "100000000000") -big = 123456789012345678901234567890L +big = 123456789012345678901234567890 testboth("%d", big, "123456789012345678901234567890") testboth("%d", -big, "-123456789012345678901234567890") testboth("%5d", -big, "-123456789012345678901234567890") @@ -83,7 +83,7 @@ testboth("%.31d", big, "0123456789012345678901234567890") testboth("%32.31d", big, " 0123456789012345678901234567890") -big = 0x1234567890abcdef12345L # 21 hex digits +big = 0x1234567890abcdef12345 # 21 hex digits testboth("%x", big, "1234567890abcdef12345") testboth("%x", -big, "-1234567890abcdef12345") testboth("%5x", -big, "-1234567890abcdef12345") @@ -120,7 +120,7 @@ # same, except no 0 flag testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345") -big = 012345670123456701234567012345670L # 32 octal digits +big = 012345670123456701234567012345670 # 32 octal digits testboth("%o", big, "12345670123456701234567012345670") testboth("%o", -big, "-12345670123456701234567012345670") testboth("%5o", -big, "-12345670123456701234567012345670") @@ -163,34 +163,34 @@ # Some small ints, in both Python int and long flavors). testboth("%d", 42, "42") testboth("%d", -42, "-42") -testboth("%d", 42L, "42") -testboth("%d", -42L, "-42") +testboth("%d", 42, "42") +testboth("%d", -42, "-42") testboth("%#x", 1, "0x1") -testboth("%#x", 1L, "0x1") +testboth("%#x", 1, "0x1") +testboth("%#X", 1, "0X1") testboth("%#X", 1, "0X1") -testboth("%#X", 1L, "0X1") testboth("%#o", 1, "01") -testboth("%#o", 1L, "01") +testboth("%#o", 1, "01") +testboth("%#o", 0, "0") testboth("%#o", 0, "0") -testboth("%#o", 0L, "0") testboth("%o", 0, "0") -testboth("%o", 0L, "0") +testboth("%o", 0, "0") testboth("%d", 0, "0") -testboth("%d", 0L, "0") +testboth("%d", 0, "0") +testboth("%#x", 0, "0x0") testboth("%#x", 0, "0x0") -testboth("%#x", 0L, "0x0") testboth("%#X", 0, "0X0") -testboth("%#X", 0L, "0X0") +testboth("%#X", 0, "0X0") testboth("%x", 0x42, "42") testboth("%x", -0x42, "-42") -testboth("%x", 0x42L, "42") -testboth("%x", -0x42L, "-42") +testboth("%x", 0x42, "42") +testboth("%x", -0x42, "-42") testboth("%o", 042, "42") testboth("%o", -042, "-42") -testboth("%o", 042L, "42") -testboth("%o", -042L, "-42") +testboth("%o", 042, "42") +testboth("%o", -042, "-42") # Test exception for unknown format characters if verbose: @@ -230,7 +230,7 @@ test_exc(u'no format', u'1', TypeError, "not all arguments converted during string formatting") -class Foobar(long): +class Foobar(int): def __oct__(self): # Returning a non-string should not blow up. return self + 1 Modified: python/branches/p3yk/Lib/test/test_functools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_functools.py (original) +++ python/branches/p3yk/Lib/test/test_functools.py Mon Jan 15 17:59:06 2007 @@ -293,8 +293,8 @@ ) self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040) self.assertEqual( - self.func(lambda x, y: x*y, range(2,21), 1L), - 2432902008176640000L + self.func(lambda x, y: x*y, range(2,21), 1), + 2432902008176640000 ) self.assertEqual(self.func(lambda x, y: x+y, Squares(10)), 285) self.assertEqual(self.func(lambda x, y: x+y, Squares(10), 0), 285) Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Mon Jan 15 17:59:06 2007 @@ -1057,9 +1057,9 @@ # generates the possiblities for the columns in that row. self.rowgenerators = [] for i in rangen: - rowuses = [(1L << j) | # column ordinal - (1L << (n + i-j + n-1)) | # NW-SE ordinal - (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal + rowuses = [(1 << j) | # column ordinal + (1 << (n + i-j + n-1)) | # NW-SE ordinal + (1 << (n + 2*n-1 + i+j)) # NE-SW ordinal for j in rangen] def rowgen(rowuses=rowuses): Modified: python/branches/p3yk/Lib/test/test_getargs2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_getargs2.py (original) +++ python/branches/p3yk/Lib/test/test_getargs2.py Mon Jan 15 17:59:06 2007 @@ -45,7 +45,7 @@ """ LARGE = 0x7FFFFFFF -VERY_LARGE = 0xFF0000121212121212121242L +VERY_LARGE = 0xFF0000121212121212121242 from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \ INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX @@ -57,7 +57,7 @@ class Long: def __int__(self): - return 99L + return 99 class Int: def __int__(self): @@ -77,7 +77,7 @@ self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1) self.failUnlessEqual(42, getargs_b(42)) - self.failUnlessEqual(42, getargs_b(42L)) + self.failUnlessEqual(42, getargs_b(42)) self.assertRaises(OverflowError, getargs_b, VERY_LARGE) def test_B(self): @@ -88,13 +88,13 @@ self.failUnlessEqual(99, getargs_B(Int())) self.failUnlessEqual(UCHAR_MAX, getargs_B(-1)) - self.failUnlessEqual(UCHAR_MAX, getargs_B(-1L)) + self.failUnlessEqual(UCHAR_MAX, getargs_B(-1)) self.failUnlessEqual(0, getargs_B(0)) self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX)) self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1)) self.failUnlessEqual(42, getargs_B(42)) - self.failUnlessEqual(42, getargs_B(42L)) + self.failUnlessEqual(42, getargs_B(42)) self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) def test_H(self): @@ -110,7 +110,7 @@ self.failUnlessEqual(0, getargs_H(USHRT_MAX+1)) self.failUnlessEqual(42, getargs_H(42)) - self.failUnlessEqual(42, getargs_H(42L)) + self.failUnlessEqual(42, getargs_H(42)) self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE)) @@ -127,7 +127,7 @@ self.failUnlessEqual(0, getargs_I(UINT_MAX+1)) self.failUnlessEqual(42, getargs_I(42)) - self.failUnlessEqual(42, getargs_I(42L)) + self.failUnlessEqual(42, getargs_I(42)) self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE)) @@ -145,7 +145,7 @@ self.failUnlessEqual(0, getargs_k(ULONG_MAX+1)) self.failUnlessEqual(42, getargs_k(42)) - self.failUnlessEqual(42, getargs_k(42L)) + self.failUnlessEqual(42, getargs_k(42)) self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE)) @@ -163,7 +163,7 @@ self.assertRaises(OverflowError, getargs_i, INT_MAX+1) self.failUnlessEqual(42, getargs_i(42)) - self.failUnlessEqual(42, getargs_i(42L)) + self.failUnlessEqual(42, getargs_i(42)) self.assertRaises(OverflowError, getargs_i, VERY_LARGE) def test_l(self): @@ -179,7 +179,7 @@ self.assertRaises(OverflowError, getargs_l, LONG_MAX+1) self.failUnlessEqual(42, getargs_l(42)) - self.failUnlessEqual(42, getargs_l(42L)) + self.failUnlessEqual(42, getargs_l(42)) self.assertRaises(OverflowError, getargs_l, VERY_LARGE) def test_n(self): @@ -196,7 +196,7 @@ self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1) self.failUnlessEqual(42, getargs_n(42)) - self.failUnlessEqual(42, getargs_n(42L)) + self.failUnlessEqual(42, getargs_n(42)) self.assertRaises(OverflowError, getargs_n, VERY_LARGE) @@ -215,7 +215,7 @@ self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1) self.failUnlessEqual(42, getargs_L(42)) - self.failUnlessEqual(42, getargs_L(42L)) + self.failUnlessEqual(42, getargs_L(42)) self.assertRaises(OverflowError, getargs_L, VERY_LARGE) def test_K(self): @@ -229,7 +229,7 @@ self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1)) self.failUnlessEqual(42, getargs_K(42)) - self.failUnlessEqual(42, getargs_K(42L)) + self.failUnlessEqual(42, getargs_K(42)) self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE)) Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Mon Jan 15 17:59:06 2007 @@ -55,14 +55,14 @@ self.fail('Weird maxint value %r' % maxint) def testLongIntegers(self): - x = 0L - x = 0l - x = 0xffffffffffffffffL - x = 0xffffffffffffffffl - x = 077777777777777777L - x = 077777777777777777l - x = 123456789012345678901234567890L - x = 123456789012345678901234567890l + x = 0 + x = 0 + x = 0xffffffffffffffff + x = 0xffffffffffffffff + x = 077777777777777777 + x = 077777777777777777 + x = 123456789012345678901234567890 + x = 123456789012345678901234567890 def testFloats(self): x = 3.14 @@ -327,7 +327,7 @@ l1 = lambda : 0 self.assertEquals(l1(), 0) l2 = lambda : a[d] # XXX just testing the expression - l3 = lambda : [2 < x for x in [-1, 3, 0L]] + l3 = lambda : [2 < x for x in [-1, 3, 0]] self.assertEquals(l3(), [0, 1, 0]) l4 = lambda x = lambda y = lambda z=1 : z : y() : x() self.assertEquals(l4(), 1) Modified: python/branches/p3yk/Lib/test/test_hash.py ============================================================================== --- python/branches/p3yk/Lib/test/test_hash.py (original) +++ python/branches/p3yk/Lib/test/test_hash.py Mon Jan 15 17:59:06 2007 @@ -17,14 +17,14 @@ self.fail("hashed values differ: %r" % (objlist,)) def test_numeric_literals(self): - self.same_hash(1, 1L, 1.0, 1.0+0.0j) + self.same_hash(1, 1, 1.0, 1.0+0.0j) def test_coerced_integers(self): - self.same_hash(int(1), long(1), float(1), complex(1), + self.same_hash(int(1), int(1), float(1), complex(1), int('1'), float('1.0')) def test_coerced_floats(self): - self.same_hash(long(1.23e300), float(1.23e300)) + self.same_hash(int(1.23e300), float(1.23e300)) self.same_hash(float(0.5), complex(0.5, 0.0)) Modified: python/branches/p3yk/Lib/test/test_hexoct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_hexoct.py (original) +++ python/branches/p3yk/Lib/test/test_hexoct.py Mon Jan 15 17:59:06 2007 @@ -41,26 +41,26 @@ def test_hex_unsigned(self): if platform_long_is_32_bits: # Positive constants - self.assertEqual(0x80000000, 2147483648L) - self.assertEqual(0xffffffff, 4294967295L) + self.assertEqual(0x80000000, 2147483648) + self.assertEqual(0xffffffff, 4294967295) # Ditto with a minus sign and parentheses - self.assertEqual(-(0x80000000), -2147483648L) - self.assertEqual(-(0xffffffff), -4294967295L) + self.assertEqual(-(0x80000000), -2147483648) + self.assertEqual(-(0xffffffff), -4294967295) # 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, -4294967295L) + self.assertEqual(-0x80000000, -2147483648) + self.assertEqual(-0xffffffff, -4294967295) else: # Positive constants - self.assertEqual(0x8000000000000000, 9223372036854775808L) - self.assertEqual(0xffffffffffffffff, 18446744073709551615L) + self.assertEqual(0x8000000000000000, 9223372036854775808) + self.assertEqual(0xffffffffffffffff, 18446744073709551615) # Ditto with a minus sign and parentheses - self.assertEqual(-(0x8000000000000000), -9223372036854775808L) - self.assertEqual(-(0xffffffffffffffff), -18446744073709551615L) + self.assertEqual(-(0x8000000000000000), -9223372036854775808) + self.assertEqual(-(0xffffffffffffffff), -18446744073709551615) # 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, -18446744073709551615L) + self.assertEqual(-0x8000000000000000, -9223372036854775808) + self.assertEqual(-0xffffffffffffffff, -18446744073709551615) def test_oct_baseline(self): # Baseline tests @@ -88,26 +88,26 @@ def test_oct_unsigned(self): if platform_long_is_32_bits: # Positive constants - self.assertEqual(020000000000, 2147483648L) - self.assertEqual(037777777777, 4294967295L) + self.assertEqual(020000000000, 2147483648) + self.assertEqual(037777777777, 4294967295) # Ditto with a minus sign and parentheses - self.assertEqual(-(020000000000), -2147483648L) - self.assertEqual(-(037777777777), -4294967295L) + self.assertEqual(-(020000000000), -2147483648) + self.assertEqual(-(037777777777), -4294967295) # 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, -4294967295L) + self.assertEqual(-020000000000, -2147483648) + self.assertEqual(-037777777777, -4294967295) else: # Positive constants - self.assertEqual(01000000000000000000000, 9223372036854775808L) - self.assertEqual(01777777777777777777777, 18446744073709551615L) + self.assertEqual(01000000000000000000000, 9223372036854775808) + self.assertEqual(01777777777777777777777, 18446744073709551615) # Ditto with a minus sign and parentheses - self.assertEqual(-(01000000000000000000000), -9223372036854775808L) - self.assertEqual(-(01777777777777777777777), -18446744073709551615L) + self.assertEqual(-(01000000000000000000000), -9223372036854775808) + self.assertEqual(-(01777777777777777777777), -18446744073709551615) # 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, -18446744073709551615L) + self.assertEqual(-01000000000000000000000, -9223372036854775808) + self.assertEqual(-01777777777777777777777, -18446744073709551615) def test_main(): test_support.run_unittest(TextHexOct) Modified: python/branches/p3yk/Lib/test/test_index.py ============================================================================== --- python/branches/p3yk/Lib/test/test_index.py (original) +++ python/branches/p3yk/Lib/test/test_index.py Mon Jan 15 17:59:06 2007 @@ -15,7 +15,7 @@ def __index__(self): return self -class TrapLong(long): +class TrapLong(int): def __index__(self): return self @@ -44,7 +44,7 @@ self.o.ind = 4 self.n.ind = 5 self.assertEqual(6 .__index__(), 6) - self.assertEqual(-7L.__index__(), -7) + self.assertEqual(-7 .__index__(), -7) self.assertEqual(self.o.__index__(), 4) self.assertEqual(self.n.__index__(), 5) Modified: python/branches/p3yk/Lib/test/test_isinstance.py ============================================================================== --- python/branches/p3yk/Lib/test/test_isinstance.py (original) +++ python/branches/p3yk/Lib/test/test_isinstance.py Mon Jan 15 17:59:06 2007 @@ -242,7 +242,7 @@ self.assertEqual(False, issubclass(NewChild, ())) self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,)))) - self.assertEqual(True, issubclass(int, (long, (float, int)))) + self.assertEqual(True, issubclass(int, (int, (float, int)))) if test_support.have_unicode: self.assertEqual(True, issubclass(str, (unicode, (Child, NewChild, basestring)))) Modified: python/branches/p3yk/Lib/test/test_largefile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_largefile.py (original) +++ python/branches/p3yk/Lib/test/test_largefile.py Mon Jan 15 17:59:06 2007 @@ -19,7 +19,7 @@ # create >2GB file (2GB = 2147483648 bytes) -size = 2500000000L +size = 2500000000 name = test_support.TESTFN @@ -37,7 +37,7 @@ f = open(test_support.TESTFN, 'wb') try: # 2**31 == 2147483648 - f.seek(2147483649L) + f.seek(2147483649) # Seeking is not enough of a test: you must write and flush, too! f.write("x") f.flush() Modified: python/branches/p3yk/Lib/test/test_long.py ============================================================================== --- python/branches/p3yk/Lib/test/test_long.py (original) +++ python/branches/p3yk/Lib/test/test_long.py Mon Jan 15 17:59:06 2007 @@ -23,11 +23,11 @@ MAXDIGITS = 15 # build some special values -special = map(long, [0, 1, 2, BASE, BASE >> 1]) -special.append(0x5555555555555555L) -special.append(0xaaaaaaaaaaaaaaaaL) +special = map(int, [0, 1, 2, BASE, BASE >> 1]) +special.append(0x5555555555555555) +special.append(0xaaaaaaaaaaaaaaaa) # some solid strings of one bits -p2 = 4L # 0 and 1 already added +p2 = 4 # 0 and 1 already added for i in range(2*SHIFT): special.append(p2 - 1) p2 = p2 << 1 @@ -49,7 +49,7 @@ self.assert_(ndigits > 0) nbits_hi = ndigits * SHIFT nbits_lo = nbits_hi - SHIFT + 1 - answer = 0L + answer = 0 nbits = 0 r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start while nbits < nbits_lo: @@ -70,7 +70,7 @@ # BASE). The sign bit is also random. def getran2(ndigits): - answer = 0L + answer = 0 for i in xrange(ndigits): answer = (answer << SHIFT) | random.randint(0, MASK) if random.random() < 0.5: @@ -98,7 +98,7 @@ for lenx in digits: x = self.getran(lenx) for leny in digits: - y = self.getran(leny) or 1L + y = self.getran(leny) or 1 self.check_division(x, y) def test_karatsuba(self): @@ -110,15 +110,15 @@ # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) == # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check. for abits in bits: - a = (1L << abits) - 1 + a = (1 << abits) - 1 for bbits in bits: if bbits < abits: continue - b = (1L << bbits) - 1 + b = (1 << bbits) - 1 x = a * b - y = ((1L << (abits + bbits)) - - (1L << abits) - - (1L << bbits) + + y = ((1 << (abits + bbits)) - + (1 << abits) - + (1 << bbits) + 1) self.assertEqual(x, y, Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y)) @@ -141,7 +141,7 @@ eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x)) eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x)) for n in xrange(2*SHIFT): - p2 = 2L ** n + p2 = 2 ** n eq(x << n >> n, x, Frm("x << n >> n != x for x=%r, n=%r", (x, n))) eq(x // p2, x >> n, @@ -217,7 +217,7 @@ msg = Frm("%s returned %r but expected %r for %r", mapper.__name__, got, expected, x) self.assertEqual(got, expected, msg) - self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x)) + self.assertEqual(int(got, 0), x, Frm('long("%s", 0) != %r', got, x)) # str() has to be checked a little differently since there's no # trailing "L" got = str(x) @@ -240,8 +240,8 @@ # check the extremes in int<->long conversion hugepos = sys.maxint hugeneg = -hugepos - 1 - hugepos_aslong = long(hugepos) - hugeneg_aslong = long(hugeneg) + hugepos_aslong = int(hugepos) + hugeneg_aslong = int(hugeneg) self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint") self.assertEqual(hugeneg, hugeneg_aslong, "long(-sys.maxint-1) != -sys.maxint-1") @@ -270,7 +270,7 @@ y = int(x) except OverflowError: self.fail("int(long(sys.maxint) + 1) mustn't overflow") - self.assert_(isinstance(y, long), + self.assert_(isinstance(y, int), "int(long(sys.maxint) + 1) should have returned long") x = hugeneg_aslong - 1 @@ -278,14 +278,14 @@ y = int(x) except OverflowError: self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow") - self.assert_(isinstance(y, long), + self.assert_(isinstance(y, int), "int(long(-sys.maxint-1) - 1) should have returned long") - class long2(long): + class long2(int): pass - x = long2(1L<<100) + x = long2(1<<100) y = int(x) - self.assert_(type(y) is long, + self.assert_(type(y) is int, "overflowing int conversion must return long not long subtype") # long -> Py_ssize_t conversion @@ -293,10 +293,10 @@ def __getslice__(self, i, j): return i, j - self.assertEqual(X()[-5L:7L], (-5, 7)) + self.assertEqual(X()[-5:7], (-5, 7)) # use the clamping effect to test the smallest and largest longs # that fit a Py_ssize_t - slicemin, slicemax = X()[-2L**100:2L**100] + slicemin, slicemax = X()[-2**100:2**100] self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax)) # ----------------------------------- tests of auto int->long conversion @@ -315,14 +315,14 @@ Frm("for %r expected %r got %r", args, expected, got)) for x in special: - longx = long(x) + longx = int(x) expected = -longx got = -x checkit('-', x) for y in special: - longy = long(y) + longy = int(y) expected = longx + longy got = x + y @@ -357,20 +357,20 @@ for z in special: if z != 0 : if y >= 0: - expected = pow(longx, longy, long(z)) + expected = pow(longx, longy, int(z)) got = pow(x, y, z) checkit('pow', x, y, '%', z) else: - self.assertRaises(TypeError, pow,longx, longy, long(z)) + self.assertRaises(TypeError, pow,longx, longy, int(z)) def test_float_overflow(self): import math for x in -2.0, -1.0, 0.0, 1.0, 2.0: - self.assertEqual(float(long(x)), x) + self.assertEqual(float(int(x)), x) shuge = '12345' * 120 - huge = 1L << 30000 + huge = 1 << 30000 mhuge = -huge namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math} for test in ["float(huge)", "float(mhuge)", @@ -410,7 +410,7 @@ log = math.log(value) self.assertAlmostEqual(log, expected) - for bad in -(1L << 10000), -2L, 0L: + for bad in -(1 << 10000), -2, 0: self.assertRaises(ValueError, math.log, bad) self.assertRaises(ValueError, math.log10, bad) @@ -426,7 +426,7 @@ # represents all Python ints, longs and floats exactly). class Rat: def __init__(self, value): - if isinstance(value, (int, long)): + if isinstance(value, (int, int)): self.n = value self.d = 1 elif isinstance(value, float): @@ -475,12 +475,12 @@ # important boundary for IEEE double precision. for t in 2.0**48, 2.0**50, 2.0**53: cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0, - long(t-1), long(t), long(t+1)]) + int(t-1), int(t), int(t+1)]) cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)]) # 1L<<20000 should exceed all double formats. long(1e200) is to # check that we get equality with 1e200 above. - t = long(1e200) - cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1]) + t = int(1e200) + cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1]) cases.extend([-x for x in cases]) for x in cases: Rx = Rat(x) Modified: python/branches/p3yk/Lib/test/test_long_future.py ============================================================================== --- python/branches/p3yk/Lib/test/test_long_future.py (original) +++ python/branches/p3yk/Lib/test/test_long_future.py Mon Jan 15 17:59:06 2007 @@ -8,16 +8,16 @@ def test_true_division(): if verbose: print "long true division" - huge = 1L << 40000 + huge = 1 << 40000 mhuge = -huge verify(huge / huge == 1.0) verify(mhuge / mhuge == 1.0) verify(huge / mhuge == -1.0) verify(mhuge / huge == -1.0) verify(1 / huge == 0.0) - verify(1L / huge == 0.0) + verify(1 / huge == 0.0) + verify(1 / mhuge == 0.0) verify(1 / mhuge == 0.0) - verify(1L / mhuge == 0.0) verify((666 * huge + (huge >> 1)) / huge == 666.5) verify((666 * mhuge + (mhuge >> 1)) / mhuge == 666.5) verify((666 * huge + (huge >> 1)) / mhuge == -666.5) @@ -28,8 +28,8 @@ namespace = {'huge': huge, 'mhuge': mhuge} for overflow in ["float(huge)", "float(mhuge)", - "huge / 1", "huge / 2L", "huge / -1", "huge / -2L", - "mhuge / 100", "mhuge / 100L"]: + "huge / 1", "huge / 2", "huge / -1", "huge / -2", + "mhuge / 100", "mhuge / 100"]: try: eval(overflow, namespace) except OverflowError: @@ -37,14 +37,14 @@ else: raise TestFailed("expected OverflowError from %r" % overflow) - for underflow in ["1 / huge", "2L / huge", "-1 / huge", "-2L / huge", - "100 / mhuge", "100L / mhuge"]: + for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge", + "100 / mhuge", "100 / mhuge"]: result = eval(underflow, namespace) if result != 0.0: raise TestFailed("expected underflow to 0 from %r" % underflow) - for zero in ["huge / 0", "huge / 0L", - "mhuge / 0", "mhuge / 0L"]: + for zero in ["huge / 0", "huge / 0", + "mhuge / 0", "mhuge / 0"]: try: eval(zero, namespace) except ZeroDivisionError: Modified: python/branches/p3yk/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_marshal.py (original) +++ python/branches/p3yk/Lib/test/test_marshal.py Mon Jan 15 17:59:06 2007 @@ -33,7 +33,7 @@ value >>= 8 return ''.join(bytes) - maxint64 = (1L << 63) - 1 + maxint64 = (1 << 63) - 1 minint64 = -maxint64-1 for base in maxint64, minint64, -maxint64, -(minint64 >> 1): @@ -152,7 +152,7 @@ d = {'astring': 'foo at bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, - 'ashortlong': 2L, + 'ashortlong': 2, 'alist': ['.zyx.41'], 'atuple': ('.zyx.41',)*10, 'aboolean': False, @@ -204,7 +204,7 @@ def test_patch_873224(self): self.assertRaises(Exception, marshal.loads, '0') self.assertRaises(Exception, marshal.loads, 'f') - self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65L)[:-1]) + self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1]) def test_version_argument(self): # Python 2.4.0 crashes for any call to marshal.dumps(x, y) Modified: python/branches/p3yk/Lib/test/test_multibytecodec_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_multibytecodec_support.py (original) +++ python/branches/p3yk/Lib/test/test_multibytecodec_support.py Mon Jan 15 17:59:06 2007 @@ -98,7 +98,7 @@ def test_callback_long_index(self): def myreplace(exc): - return (u'x', long(exc.end)) + return (u'x', int(exc.end)) codecs.register_error("test.cjktest", myreplace) self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh', 'test.cjktest'), ('abcdxefgh', 9)) Modified: python/branches/p3yk/Lib/test/test_operator.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operator.py (original) +++ python/branches/p3yk/Lib/test/test_operator.py Mon Jan 15 17:59:06 2007 @@ -199,7 +199,7 @@ self.failUnlessRaises(TypeError, operator.isNumberType) self.failUnless(operator.isNumberType(8)) self.failUnless(operator.isNumberType(8j)) - self.failUnless(operator.isNumberType(8L)) + self.failUnless(operator.isNumberType(8)) self.failUnless(operator.isNumberType(8.3)) self.failIf(operator.isNumberType(dir())) Modified: python/branches/p3yk/Lib/test/test_optparse.py ============================================================================== --- python/branches/p3yk/Lib/test/test_optparse.py (original) +++ python/branches/p3yk/Lib/test/test_optparse.py Mon Jan 15 17:59:06 2007 @@ -1598,7 +1598,7 @@ def setUp(self): self.parser = InterceptingOptionParser() self.parser.add_option("-n", type=int) - self.parser.add_option("-l", type=long) + self.parser.add_option("-l", type=int) def test_parse_num_fail(self): self.assertRaises( @@ -1606,17 +1606,17 @@ ValueError, re.compile(r"invalid literal for int().*: '?'?")) self.assertRaises( - _parse_num, ("0xOoops", long), {}, + _parse_num, ("0xOoops", int), {}, ValueError, re.compile(r"invalid literal for int().*: '?0xOoops'?")) def test_parse_num_ok(self): self.assertEqual(_parse_num("0", int), 0) self.assertEqual(_parse_num("0x10", int), 16) - self.assertEqual(_parse_num("0XA", long), 10L) - self.assertEqual(_parse_num("010", long), 8L) + self.assertEqual(_parse_num("0XA", int), 10) + self.assertEqual(_parse_num("010", int), 8) self.assertEqual(_parse_num("0b11", int), 3) - self.assertEqual(_parse_num("0b", long), 0L) + self.assertEqual(_parse_num("0b", int), 0) def test_numeric_options(self): self.assertParseOK(["-n", "42", "-l", "0x20"], Modified: python/branches/p3yk/Lib/test/test_poll.py ============================================================================== --- python/branches/p3yk/Lib/test/test_poll.py (original) +++ python/branches/p3yk/Lib/test/test_poll.py Mon Jan 15 17:59:06 2007 @@ -143,7 +143,7 @@ pollster = select.poll() pollster.register(1) - self.assertRaises(OverflowError, pollster.poll, 1L << 64) + self.assertRaises(OverflowError, pollster.poll, 1 << 64) x = 2 + 3 if x != 5: Modified: python/branches/p3yk/Lib/test/test_pow.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pow.py (original) +++ python/branches/p3yk/Lib/test/test_pow.py Mon Jan 15 17:59:06 2007 @@ -18,14 +18,14 @@ self.assertEquals(pow(2, i), pow2) if i != 30 : pow2 = pow2*2 - for othertype in int, long: + for othertype in int, int: 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 othertype in int, int, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) @@ -42,7 +42,7 @@ asseq = self.assertAlmostEqual elif type == int: jl = 0 - elif type == long: + elif type == int: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): @@ -60,7 +60,7 @@ self.powtest(int) def test_powlong(self): - self.powtest(long) + self.powtest(int) def test_powfloat(self): self.powtest(float) @@ -74,12 +74,12 @@ 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)) + 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)) for i in range(-10, 11): for j in range(0, 6): @@ -91,8 +91,8 @@ ) if j >= 0 and k != 0: self.assertEquals( - pow(long(i),j) % k, - pow(long(i),j,k) + pow(int(i),j) % k, + pow(int(i),j,k) ) def test_bug643260(self): Modified: python/branches/p3yk/Lib/test/test_pprint.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pprint.py (original) +++ python/branches/p3yk/Lib/test/test_pprint.py Mon Jan 15 17:59:06 2007 @@ -114,12 +114,12 @@ # multiple lines. For that reason, dicts with more than one element # aren't tested here. verify = self.assert_ - for simple in (0, 0L, 0+0j, 0.0, "", uni(""), + for simple in (0, 0, 0+0j, 0.0, "", uni(""), (), tuple2(), tuple3(), [], list2(), list3(), {}, dict2(), dict3(), verify, pprint, - -6, -6L, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6}, + -6, -6, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6}, (1,2), [3,4], {5: 6, 7: 8}, tuple2((1,2)), tuple3((1,2)), tuple3(range(100)), [3,4], list2([3,4]), list3([3,4]), list3(range(100)), Modified: python/branches/p3yk/Lib/test/test_random.py ============================================================================== --- python/branches/p3yk/Lib/test/test_random.py (original) +++ python/branches/p3yk/Lib/test/test_random.py Mon Jan 15 17:59:06 2007 @@ -34,7 +34,7 @@ self.assertEqual(randseq, self.randomlist(N)) def test_seedargs(self): - for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20), + for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20), 3.14, 1+2j, 'a', tuple('abc')]: self.gen.seed(arg) for arg in [range(3), dict(one=1)]: @@ -268,7 +268,7 @@ # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in xrange(1, 1000): - n = 1L << i # check an exact power of two + n = 1 << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) @@ -327,7 +327,7 @@ 0.089215024911993401, 0.78486196105372907] - self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96)) + self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): self.assertAlmostEqual(a,e,places=14) @@ -339,20 +339,20 @@ # no rounding errors -- all results are exact). from math import ldexp - expected = [0x0eab3258d2231fL, - 0x1b89db315277a5L, - 0x1db622a5518016L, - 0x0b7f9af0d575bfL, - 0x029e4c4db82240L, - 0x04961892f5d673L, - 0x02b291598e4589L, - 0x11388382c15694L, - 0x02dad977c9e1feL, - 0x191d96d4d334c6L] - self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96)) + expected = [0x0eab3258d2231f, + 0x1b89db315277a5, + 0x1db622a5518016, + 0x0b7f9af0d575bf, + 0x029e4c4db82240, + 0x04961892f5d673, + 0x02b291598e4589, + 0x11388382c15694, + 0x02dad977c9e1fe, + 0x191d96d4d334c6] + self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): - self.assertEqual(long(ldexp(a, 53)), e) + self.assertEqual(int(ldexp(a, 53)), e) def test_long_seed(self): # This is most interesting to run in debug mode, just to make sure @@ -360,7 +360,7 @@ # is allocated, consuming space proportional to the number of bits # in the seed. Unfortunately, that's a quadratic-time algorithm, # so don't make this horribly big. - seed = (1L << (10000 * 8)) - 1 # about 10K bytes + seed = (1 << (10000 * 8)) - 1 # about 10K bytes self.gen.seed(seed) def test_53_bits_per_float(self): @@ -399,7 +399,7 @@ # Verify cross-platform repeatability self.gen.seed(1234567) self.assertEqual(self.gen.getrandbits(100), - 97904845777343510404718956115L) + 97904845777343510404718956115) # Verify ranges for k in xrange(1, 1000): self.assert_(0 <= self.gen.getrandbits(k) < 2**k) @@ -424,7 +424,7 @@ # show that: k = int(1.001 + _log(n, 2)) # is equal to or one greater than the number of bits in n for i in xrange(1, 1000): - n = 1L << i # check an exact power of two + n = 1 << i # check an exact power of two numbits = i+1 k = int(1.00001 + _log(n, 2)) self.assertEqual(k, numbits) Modified: python/branches/p3yk/Lib/test/test_repr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_repr.py (original) +++ python/branches/p3yk/Lib/test/test_repr.py Mon Jan 15 17:59:06 2007 @@ -90,10 +90,10 @@ def test_numbers(self): eq = self.assertEquals eq(r(123), repr(123)) - eq(r(123L), repr(123L)) + eq(r(123), repr(123)) eq(r(1.0/3), repr(1.0/3)) - n = 10L**100 + n = 10**100 expected = repr(n)[:18] + "..." + repr(n)[-19:] eq(r(n), expected) Modified: python/branches/p3yk/Lib/test/test_resource.py ============================================================================== --- python/branches/p3yk/Lib/test/test_resource.py (original) +++ python/branches/p3yk/Lib/test/test_resource.py Mon Jan 15 17:59:06 2007 @@ -45,7 +45,7 @@ resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) # And be sure that setrlimit is checking for really large values -too_big = 10L**50 +too_big = 10**50 try: resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max)) except (OverflowError, ValueError): Modified: python/branches/p3yk/Lib/test/test_slice.py ============================================================================== --- python/branches/p3yk/Lib/test/test_slice.py (original) +++ python/branches/p3yk/Lib/test/test_slice.py Mon Jan 15 17:59:06 2007 @@ -86,11 +86,11 @@ slice(100, -100, -1).indices(10), slice(None, None, -1).indices(10) ) - self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2)) + self.assertEqual(slice(-100, 100, 2).indices(10), (0, 10, 2)) self.assertEqual(range(10)[::sys.maxint - 1], [0]) - self.assertRaises(OverflowError, slice(None).indices, 1L<<100) + self.assertRaises(OverflowError, slice(None).indices, 1<<100) def test_main(): test_support.run_unittest(SliceTest) Modified: python/branches/p3yk/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket.py (original) +++ python/branches/p3yk/Lib/test/test_socket.py Mon Jan 15 17:59:06 2007 @@ -302,17 +302,17 @@ sizes = {socket.htonl: 32, socket.ntohl: 32, socket.htons: 16, socket.ntohs: 16} for func, size in sizes.items(): - mask = (1L< 0 expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: @@ -316,7 +316,7 @@ if self.unsigned_min <= x <= self.unsigned_max: # Try big-endian. format = ">" + code - expected = long(x) + expected = int(x) expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: expected = "0" + expected @@ -372,11 +372,11 @@ # Create all interesting powers of 2. values = [] for exp in range(self.bitsize + 3): - values.append(1L << exp) + values.append(1 << exp) # Add some random values. for i in range(self.bitsize): - val = 0L + val = 0 for j in range(self.bytesize): val = (val << 8) | randrange(256) values.append(val) @@ -485,15 +485,15 @@ def test_1229380(): import sys for endian in ('', '>', '<'): - for cls in (int, long): + for cls in (int, int): for fmt in ('B', 'H', 'I', 'L'): deprecated_err(struct.pack, endian + fmt, cls(-1)) deprecated_err(struct.pack, endian + 'B', cls(300)) deprecated_err(struct.pack, endian + 'H', cls(70000)) - deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L) - deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L) + deprecated_err(struct.pack, endian + 'I', sys.maxint * 4) + deprecated_err(struct.pack, endian + 'L', sys.maxint * 4) if PY_STRUCT_RANGE_CHECKING: test_1229380() Modified: python/branches/p3yk/Lib/test/test_time.py ============================================================================== --- python/branches/p3yk/Lib/test/test_time.py (original) +++ python/branches/p3yk/Lib/test/test_time.py Mon Jan 15 17:59:06 2007 @@ -20,8 +20,8 @@ def test_conversions(self): self.assert_(time.ctime(self.t) == time.asctime(time.localtime(self.t))) - self.assert_(long(time.mktime(time.localtime(self.t))) - == long(self.t)) + self.assert_(int(time.mktime(time.localtime(self.t))) + == int(self.t)) def test_sleep(self): time.sleep(1.2) Modified: python/branches/p3yk/Lib/test/test_timeout.py ============================================================================== --- python/branches/p3yk/Lib/test/test_timeout.py (original) +++ python/branches/p3yk/Lib/test/test_timeout.py Mon Jan 15 17:59:06 2007 @@ -46,7 +46,7 @@ def testTypeCheck(self): # Test type checking by settimeout() self.sock.settimeout(0) - self.sock.settimeout(0L) + self.sock.settimeout(0) self.sock.settimeout(0.0) self.sock.settimeout(None) self.assertRaises(TypeError, self.sock.settimeout, "") @@ -59,7 +59,7 @@ def testRangeCheck(self): # Test range checking by settimeout() self.assertRaises(ValueError, self.sock.settimeout, -1) - self.assertRaises(ValueError, self.sock.settimeout, -1L) + self.assertRaises(ValueError, self.sock.settimeout, -1) self.assertRaises(ValueError, self.sock.settimeout, -1.0) def testTimeoutThenBlocking(self): Modified: python/branches/p3yk/Lib/test/test_types.py ============================================================================== --- python/branches/p3yk/Lib/test/test_types.py (original) +++ python/branches/p3yk/Lib/test/test_types.py Mon Jan 15 17:59:06 2007 @@ -9,11 +9,11 @@ def test_truth_values(self): if None: self.fail('None is true instead of false') if 0: self.fail('0 is true instead of false') - if 0L: self.fail('0L is true instead of false') + if 0: self.fail('0L is true instead of false') if 0.0: self.fail('0.0 is true instead of false') if '': self.fail('\'\' is true instead of false') if not 1: self.fail('1 is false instead of true') - if not 1L: self.fail('1L is false instead of true') + if not 1: self.fail('1L is false instead of true') if not 1.0: self.fail('1.0 is false instead of true') if not 'x': self.fail('\'x\' is false instead of true') if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true') @@ -35,7 +35,7 @@ def test_comparisons(self): if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass else: self.fail('int comparisons failed') - if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass + if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass else: self.fail('long int comparisons failed') if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass else: self.fail('float comparisons failed') @@ -61,30 +61,30 @@ except ZeroDivisionError: pass else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError") - try: 5 / 0L + try: 5 / 0 except ZeroDivisionError: pass else: self.fail("5 / 0L didn't raise ZeroDivisionError") - try: 5 // 0L + try: 5 // 0 except ZeroDivisionError: pass else: self.fail("5 // 0L didn't raise ZeroDivisionError") - try: 5 % 0L + try: 5 % 0 except ZeroDivisionError: pass else: self.fail("5 % 0L didn't raise ZeroDivisionError") def test_numeric_types(self): - if 0 != 0L or 0 != 0.0 or 0L != 0.0: self.fail('mixed comparisons') - if 1 != 1L or 1 != 1.0 or 1L != 1.0: self.fail('mixed comparisons') - if -1 != -1L or -1 != -1.0 or -1L != -1.0: + if 0 != 0 or 0 != 0.0 or 0 != 0.0: self.fail('mixed comparisons') + if 1 != 1 or 1 != 1.0 or 1 != 1.0: self.fail('mixed comparisons') + if -1 != -1 or -1 != -1.0 or -1 != -1.0: self.fail('int/long/float value not equal') # calling built-in types without argument must return 0 if int() != 0: self.fail('int() does not return 0') - if long() != 0L: self.fail('long() does not return 0L') + if int() != 0: self.fail('long() does not return 0L') if float() != 0.0: self.fail('float() does not return 0.0') if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass else: self.fail('int() does not round properly') - if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass + if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass else: self.fail('long() does not round properly') if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass else: self.fail('float() does not work properly') @@ -118,7 +118,7 @@ for divisor in 1, 2, 4, 8, 16, 32: j = m // divisor - 1 prod = divisor * j - if type(prod) is not long: + if type(prod) is not int: self.fail("expected type(%r) to be long, not %r" % (prod, type(prod))) # Check for expected * overflow to long. @@ -126,35 +126,35 @@ for divisor in 1, 2, 4, 8, 16, 32: j = m // divisor + 1 prod = divisor * j - if type(prod) is not long: + if type(prod) is not int: self.fail("expected type(%r) to be long, not %r" % (prod, type(prod))) def test_long_integers(self): - if 12L + 24L != 36L: self.fail('long op') - if 12L + (-24L) != -12L: self.fail('long op') - if (-12L) + 24L != 12L: self.fail('long op') - if (-12L) + (-24L) != -36L: self.fail('long op') - if not 12L < 24L: self.fail('long op') - if not -24L < -12L: self.fail('long op') + if 12 + 24 != 36: self.fail('long op') + if 12 + (-24) != -12: self.fail('long op') + if (-12) + 24 != 12: self.fail('long op') + if (-12) + (-24) != -36: self.fail('long op') + if not 12 < 24: self.fail('long op') + if not -24 < -12: self.fail('long op') x = sys.maxint - if int(long(x)) != x: self.fail('long op') - try: y = int(long(x)+1L) + if int(int(x)) != x: self.fail('long op') + try: y = int(int(x)+1) except OverflowError: self.fail('long op') - if not isinstance(y, long): self.fail('long op') + if not isinstance(y, int): self.fail('long op') x = -x - if int(long(x)) != x: self.fail('long op') + if int(int(x)) != x: self.fail('long op') x = x-1 - if int(long(x)) != x: self.fail('long op') - try: y = int(long(x)-1L) + if int(int(x)) != x: self.fail('long op') + try: y = int(int(x)-1) except OverflowError: self.fail('long op') - if not isinstance(y, long): self.fail('long op') + if not isinstance(y, int): self.fail('long op') try: 5 << -5 except ValueError: pass else: self.fail('int negative shift <<') - try: 5L << -5L + try: 5 << -5 except ValueError: pass else: self.fail('long negative shift <<') @@ -162,7 +162,7 @@ except ValueError: pass else: self.fail('int negative shift >>') - try: 5L >> -5L + try: 5 >> -5 except ValueError: pass else: self.fail('long negative shift >>') @@ -197,7 +197,7 @@ self.assertEqual(a[3::-2], '31') self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) - self.assertEqual(a[-100L:100L:2L], '02468') + self.assertEqual(a[-100:100:2], '02468') if have_unicode: a = unicode('0123456789', 'ascii') @@ -209,7 +209,7 @@ self.assertEqual(a[3::-2], unicode('31', 'ascii')) self.assertEqual(a[-100:100:], a) self.assertEqual(a[100:-100:-1], a[::-1]) - self.assertEqual(a[-100L:100L:2L], unicode('02468', 'ascii')) + self.assertEqual(a[-100:100:2], unicode('02468', 'ascii')) def test_type_function(self): Modified: python/branches/p3yk/Lib/test/test_unary.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unary.py (original) +++ python/branches/p3yk/Lib/test/test_unary.py Mon Jan 15 17:59:06 2007 @@ -9,7 +9,7 @@ self.assert_(-2 == 0 - 2) self.assert_(-0 == 0) self.assert_(--2 == 2) - self.assert_(-2L == 0 - 2L) + self.assert_(-2 == 0 - 2) self.assert_(-2.0 == 0 - 2.0) self.assert_(-2j == 0 - 2j) @@ -17,7 +17,7 @@ self.assert_(+2 == 2) self.assert_(+0 == 0) self.assert_(++2 == 2) - self.assert_(+2L == 2L) + self.assert_(+2 == 2) self.assert_(+2.0 == 2.0) self.assert_(+2j == 2j) @@ -25,13 +25,13 @@ self.assert_(-2 == 0 - 2) self.assert_(-0 == 0) self.assert_(--2 == 2) - self.assert_(-2L == 0 - 2L) + self.assert_(-2 == 0 - 2) def test_no_overflow(self): nines = "9" * 32 - self.assert_(eval("+" + nines) == eval("+" + nines + "L")) - self.assert_(eval("-" + nines) == eval("-" + nines + "L")) - self.assert_(eval("~" + nines) == eval("~" + nines + "L")) + self.assert_(eval("+" + nines) == 10**32-1) + self.assert_(eval("-" + nines) == -(10**32-1)) + self.assert_(eval("~" + nines) == ~(10**32-1)) def test_negation_of_exponentiation(self): # Make sure '**' does the right thing; these form a Modified: python/branches/p3yk/Lib/test/test_unicode.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unicode.py (original) +++ python/branches/p3yk/Lib/test/test_unicode.py Mon Jan 15 17:59:06 2007 @@ -483,7 +483,7 @@ UnicodeCompat(u"u'%s' % obj falls back to obj.__str__()"), u"u'%s' % obj falls back to obj.__str__()") - for obj in (123, 123.45, 123L): + for obj in (123, 123.45, 123): self.assertEqual(unicode(obj), unicode(str(obj))) # unicode(obj, encoding, error) tests (this maps to Modified: python/branches/p3yk/Lib/test/test_uuid.py ============================================================================== --- python/branches/p3yk/Lib/test/test_uuid.py (original) +++ python/branches/p3yk/Lib/test/test_uuid.py Mon Jan 15 17:59:06 2007 @@ -32,19 +32,19 @@ '000102030405060708090a0b0c0d0e0f', '\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f', '\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f', - (0x00010203L, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0fL), - 0x000102030405060708090a0b0c0d0e0fL, + (0x00010203, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0f), + 0x000102030405060708090a0b0c0d0e0f, 'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f', - 0x607040500010203L, 0x809, uuid.RESERVED_NCS, None), + 0x607040500010203, 0x809, uuid.RESERVED_NCS, None), ('02d9e6d5-9467-382e-8f9b-9300a64ac3cd', '{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}', '02d9e6d59467382e8f9b9300a64ac3cd', '\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd', '\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd', - (0x02d9e6d5L, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cdL), - 0x02d9e6d59467382e8f9b9300a64ac3cdL, + (0x02d9e6d5, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cd), + 0x02d9e6d59467382e8f9b9300a64ac3cd, 'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd', - 0x82e946702d9e6d5L, 0xf9b, uuid.RFC_4122, 3), + 0x82e946702d9e6d5, 0xf9b, uuid.RFC_4122, 3), ('12345678-1234-5678-1234-567812345678', '{12345678-1234-5678-1234-567812345678}', '12345678123456781234567812345678', @@ -53,97 +53,97 @@ (0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678), 0x12345678123456781234567812345678, 'urn:uuid:12345678-1234-5678-1234-567812345678', - 0x678123412345678L, 0x1234, uuid.RESERVED_NCS, None), + 0x678123412345678, 0x1234, uuid.RESERVED_NCS, None), ('6ba7b810-9dad-11d1-80b4-00c04fd430c8', '{6ba7b810-9dad-11d1-80b4-00c04fd430c8}', '6ba7b8109dad11d180b400c04fd430c8', '\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', '\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', - (0x6ba7b810L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L), - 0x6ba7b8109dad11d180b400c04fd430c8L, + (0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8), + 0x6ba7b8109dad11d180b400c04fd430c8, 'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8', - 0x1d19dad6ba7b810L, 0xb4, uuid.RFC_4122, 1), + 0x1d19dad6ba7b810, 0xb4, uuid.RFC_4122, 1), ('6ba7b811-9dad-11d1-80b4-00c04fd430c8', '{6ba7b811-9dad-11d1-80b4-00c04fd430c8}', '6ba7b8119dad11d180b400c04fd430c8', '\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', '\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', - (0x6ba7b811L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L), - 0x6ba7b8119dad11d180b400c04fd430c8L, + (0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8), + 0x6ba7b8119dad11d180b400c04fd430c8, 'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8', - 0x1d19dad6ba7b811L, 0xb4, uuid.RFC_4122, 1), + 0x1d19dad6ba7b811, 0xb4, uuid.RFC_4122, 1), ('6ba7b812-9dad-11d1-80b4-00c04fd430c8', '{6ba7b812-9dad-11d1-80b4-00c04fd430c8}', '6ba7b8129dad11d180b400c04fd430c8', '\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', '\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', - (0x6ba7b812L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L), - 0x6ba7b8129dad11d180b400c04fd430c8L, + (0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8), + 0x6ba7b8129dad11d180b400c04fd430c8, 'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8', - 0x1d19dad6ba7b812L, 0xb4, uuid.RFC_4122, 1), + 0x1d19dad6ba7b812, 0xb4, uuid.RFC_4122, 1), ('6ba7b814-9dad-11d1-80b4-00c04fd430c8', '{6ba7b814-9dad-11d1-80b4-00c04fd430c8}', '6ba7b8149dad11d180b400c04fd430c8', '\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', '\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8', - (0x6ba7b814L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L), - 0x6ba7b8149dad11d180b400c04fd430c8L, + (0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8), + 0x6ba7b8149dad11d180b400c04fd430c8, 'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8', - 0x1d19dad6ba7b814L, 0xb4, uuid.RFC_4122, 1), + 0x1d19dad6ba7b814, 0xb4, uuid.RFC_4122, 1), ('7d444840-9dc0-11d1-b245-5ffdce74fad2', '{7d444840-9dc0-11d1-b245-5ffdce74fad2}', '7d4448409dc011d1b2455ffdce74fad2', '\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2', '\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2', - (0x7d444840L, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2L), - 0x7d4448409dc011d1b2455ffdce74fad2L, + (0x7d444840, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2), + 0x7d4448409dc011d1b2455ffdce74fad2, 'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2', - 0x1d19dc07d444840L, 0x3245, uuid.RFC_4122, 1), + 0x1d19dc07d444840, 0x3245, uuid.RFC_4122, 1), ('e902893a-9d22-3c7e-a7b8-d6e313b71d9f', '{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}', 'e902893a9d223c7ea7b8d6e313b71d9f', '\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f', '\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f', - (0xe902893aL, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9fL), - 0xe902893a9d223c7ea7b8d6e313b71d9fL, + (0xe902893a, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9f), + 0xe902893a9d223c7ea7b8d6e313b71d9f, 'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f', - 0xc7e9d22e902893aL, 0x27b8, uuid.RFC_4122, 3), + 0xc7e9d22e902893a, 0x27b8, uuid.RFC_4122, 3), ('eb424026-6f54-4ef8-a4d0-bb658a1fc6cf', '{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}', 'eb4240266f544ef8a4d0bb658a1fc6cf', '\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf', '\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf', - (0xeb424026L, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cfL), - 0xeb4240266f544ef8a4d0bb658a1fc6cfL, + (0xeb424026, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cf), + 0xeb4240266f544ef8a4d0bb658a1fc6cf, 'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf', - 0xef86f54eb424026L, 0x24d0, uuid.RFC_4122, 4), + 0xef86f54eb424026, 0x24d0, uuid.RFC_4122, 4), ('f81d4fae-7dec-11d0-a765-00a0c91e6bf6', '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}', 'f81d4fae7dec11d0a76500a0c91e6bf6', '\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6', '\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6', - (0xf81d4faeL, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6L), - 0xf81d4fae7dec11d0a76500a0c91e6bf6L, + (0xf81d4fae, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6), + 0xf81d4fae7dec11d0a76500a0c91e6bf6, 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6', - 0x1d07decf81d4faeL, 0x2765, uuid.RFC_4122, 1), + 0x1d07decf81d4fae, 0x2765, uuid.RFC_4122, 1), ('fffefdfc-fffe-fffe-fffe-fffefdfcfbfa', '{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}', 'fffefdfcfffefffefffefffefdfcfbfa', '\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa', '\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa', - (0xfffefdfcL, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfaL), - 0xfffefdfcfffefffefffefffefdfcfbfaL, + (0xfffefdfc, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfa), + 0xfffefdfcfffefffefffefffefdfcfbfa, 'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa', - 0xffefffefffefdfcL, 0x3ffe, uuid.RESERVED_FUTURE, None), + 0xffefffefffefdfc, 0x3ffe, uuid.RESERVED_FUTURE, None), ('ffffffff-ffff-ffff-ffff-ffffffffffff', '{ffffffff-ffff-ffff-ffff-ffffffffffff}', 'ffffffffffffffffffffffffffffffff', '\xff'*16, '\xff'*16, - (0xffffffffL, 0xffffL, 0xffffL, 0xff, 0xff, 0xffffffffffffL), - 0xffffffffffffffffffffffffffffffffL, + (0xffffffff, 0xffff, 0xffff, 0xff, 0xff, 0xffffffffffff), + 0xffffffffffffffffffffffffffffffff, 'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff', - 0xfffffffffffffffL, 0x3fff, uuid.RESERVED_FUTURE, None), + 0xfffffffffffffff, 0x3fff, uuid.RESERVED_FUTURE, None), ]: equivalents = [] # Construct each UUID in several different ways. @@ -217,17 +217,17 @@ # Field values out of range. badvalue(lambda: uuid.UUID(fields=(-1, 0, 0, 0, 0, 0))) - badvalue(lambda: uuid.UUID(fields=(0x100000000L, 0, 0, 0, 0, 0))) + badvalue(lambda: uuid.UUID(fields=(0x100000000, 0, 0, 0, 0, 0))) badvalue(lambda: uuid.UUID(fields=(0, -1, 0, 0, 0, 0))) - badvalue(lambda: uuid.UUID(fields=(0, 0x10000L, 0, 0, 0, 0))) + badvalue(lambda: uuid.UUID(fields=(0, 0x10000, 0, 0, 0, 0))) badvalue(lambda: uuid.UUID(fields=(0, 0, -1, 0, 0, 0))) - badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000L, 0, 0, 0))) + badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000, 0, 0, 0))) badvalue(lambda: uuid.UUID(fields=(0, 0, 0, -1, 0, 0))) - badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100L, 0, 0))) + badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100, 0, 0))) badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, -1, 0))) - badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100L, 0))) + badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100, 0))) badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, -1))) - badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000L))) + badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000))) # Version number out of range. badvalue(lambda: uuid.UUID('00'*16, version=0)) @@ -235,7 +235,7 @@ # Integer value out of range. badvalue(lambda: uuid.UUID(int=-1)) - badvalue(lambda: uuid.UUID(int=1<<128L)) + badvalue(lambda: uuid.UUID(int=1<<128)) # Must supply exactly one of hex, bytes, fields, int. h, b, f, i = '00'*16, '\0'*16, (0, 0, 0, 0, 0, 0), 0 @@ -281,15 +281,15 @@ badtype(lambda: setattr(u, 'node', 0)) def check_node(self, node, source): - individual_group_bit = (node >> 40L) & 1 - universal_local_bit = (node >> 40L) & 2 + individual_group_bit = (node >> 40) & 1 + universal_local_bit = (node >> 40) & 2 message = "%012x doesn't look like a real MAC address" % node self.assertEqual(individual_group_bit, 0, message) self.assertEqual(universal_local_bit, 0, message) self.assertNotEqual(node, 0, message) - self.assertNotEqual(node, 0xffffffffffffL, message) + self.assertNotEqual(node, 0xffffffffffff, message) self.assert_(0 <= node, message) - self.assert_(node < (1L << 48), message) + self.assert_(node < (1 << 48), message) TestUUID.source2node[source] = node if TestUUID.last_node: @@ -332,7 +332,7 @@ def test_random_getnode(self): node = uuid._random_getnode() self.assert_(0 <= node) - self.assert_(node < (1L <<48)) + self.assert_(node < (1 <<48)) def test_unixdll_getnode(self): import sys Modified: python/branches/p3yk/Lib/test/test_xdrlib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xdrlib.py (original) +++ python/branches/p3yk/Lib/test/test_xdrlib.py Mon Jan 15 17:59:06 2007 @@ -15,7 +15,7 @@ p.pack_uint(9) p.pack_bool(True) p.pack_bool(False) - p.pack_uhyper(45L) + p.pack_uhyper(45) p.pack_float(1.9) p.pack_double(1.9) p.pack_string(s) @@ -40,7 +40,7 @@ up.set_position(pos) self.assert_(up.unpack_bool() is False) - self.assertEqual(up.unpack_uhyper(), 45L) + self.assertEqual(up.unpack_uhyper(), 45) self.assertAlmostEqual(up.unpack_float(), 1.9) self.assertAlmostEqual(up.unpack_double(), 1.9) self.assertEqual(up.unpack_string(), s) Modified: python/branches/p3yk/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xmlrpc.py (original) +++ python/branches/p3yk/Lib/test/test_xmlrpc.py Mon Jan 15 17:59:06 2007 @@ -14,7 +14,7 @@ alist = [{'astring': 'foo at bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, - 'ashortlong': 2L, + 'ashortlong': 2, 'anotherlist': ['.zyx.41'], 'abase64': xmlrpclib.Binary("my dog has fleas"), 'boolean': xmlrpclib.False, @@ -96,15 +96,15 @@ self.assertEquals(t2, t.__dict__) def test_dump_big_long(self): - self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,)) + self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,)) def test_dump_bad_dict(self): self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},)) def test_dump_big_int(self): - if sys.maxint > 2L**31-1: + if sys.maxint > 2**31-1: self.assertRaises(OverflowError, xmlrpclib.dumps, - (int(2L**34),)) + (int(2**34),)) def test_dump_none(self): value = alist + [None] Modified: python/branches/p3yk/Lib/test/test_xrange.py ============================================================================== --- python/branches/p3yk/Lib/test/test_xrange.py (original) +++ python/branches/p3yk/Lib/test/test_xrange.py Mon Jan 15 17:59:06 2007 @@ -21,7 +21,7 @@ c = 50 self.assertEqual(list(xrange(a, a+2)), [a, a+1]) - self.assertEqual(list(xrange(a+2, a, -1L)), [a+2, a+1]) + self.assertEqual(list(xrange(a+2, a, -1)), [a+2, a+1]) self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2]) seq = list(xrange(a, b, c)) Modified: python/branches/p3yk/Lib/test/test_zipimport.py ============================================================================== --- python/branches/p3yk/Lib/test/test_zipimport.py (original) +++ python/branches/p3yk/Lib/test/test_zipimport.py Mon Jan 15 17:59:06 2007 @@ -31,7 +31,7 @@ if mtime < 0x7fffffff: mtime = int(mtime) else: - mtime = int(-0x100000000L + long(mtime)) + mtime = int(-0x100000000 + int(mtime)) pyc = imp.get_magic() + struct.pack("> 96L + return self.int >> 96 time_low = property(get_time_low) def get_time_mid(self): - return (self.int >> 80L) & 0xffff + return (self.int >> 80) & 0xffff time_mid = property(get_time_mid) def get_time_hi_version(self): - return (self.int >> 64L) & 0xffff + return (self.int >> 64) & 0xffff time_hi_version = property(get_time_hi_version) def get_clock_seq_hi_variant(self): - return (self.int >> 56L) & 0xff + return (self.int >> 56) & 0xff clock_seq_hi_variant = property(get_clock_seq_hi_variant) def get_clock_seq_low(self): - return (self.int >> 48L) & 0xff + return (self.int >> 48) & 0xff clock_seq_low = property(get_clock_seq_low) def get_time(self): - return (((self.time_hi_version & 0x0fffL) << 48L) | - (self.time_mid << 32L) | self.time_low) + return (((self.time_hi_version & 0x0fff) << 48) | + (self.time_mid << 32) | self.time_low) time = property(get_time) def get_clock_seq(self): - return (((self.clock_seq_hi_variant & 0x3fL) << 8L) | + return (((self.clock_seq_hi_variant & 0x3f) << 8) | self.clock_seq_low) clock_seq = property(get_clock_seq) @@ -300,11 +302,11 @@ urn = property(get_urn) def get_variant(self): - if not self.int & (0x8000 << 48L): + if not self.int & (0x8000 << 48): return RESERVED_NCS - elif not self.int & (0x4000 << 48L): + elif not self.int & (0x4000 << 48): return RFC_4122 - elif not self.int & (0x2000 << 48L): + elif not self.int & (0x2000 << 48): return RESERVED_MICROSOFT else: return RESERVED_FUTURE @@ -314,7 +316,7 @@ def get_version(self): # The version bits are only meaningful for RFC 4122 UUIDs. if self.variant == RFC_4122: - return int((self.int >> 76L) & 0xf) + return int((self.int >> 76) & 0xf) version = property(get_version) @@ -411,8 +413,8 @@ continue status._unpack() bytes = map(ord, status.adapter_address) - return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) + - (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5]) + return ((bytes[0]<<40) + (bytes[1]<<32) + (bytes[2]<<24) + + (bytes[3]<<16) + (bytes[4]<<8) + bytes[5]) # Thanks to Thomas Heller for ctypes and for his help with its use here. @@ -464,7 +466,7 @@ def _random_getnode(): """Get a random node ID, with eighth bit set as suggested by RFC 4122.""" import random - return random.randrange(0, 1<<48L) | 0x010000000000L + return random.randrange(0, 1<<48) | 0x010000000000 _node = None @@ -514,18 +516,18 @@ nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. - timestamp = int(nanoseconds/100) + 0x01b21dd213814000L + timestamp = int(nanoseconds/100) + 0x01b21dd213814000 if _last_timestamp is not None and timestamp <= _last_timestamp: timestamp = _last_timestamp + 1 _last_timestamp = timestamp if clock_seq is None: import random - clock_seq = random.randrange(1<<14L) # instead of stable storage - time_low = timestamp & 0xffffffffL - time_mid = (timestamp >> 32L) & 0xffffL - time_hi_version = (timestamp >> 48L) & 0x0fffL - clock_seq_low = clock_seq & 0xffL - clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL + clock_seq = random.randrange(1<<14) # instead of stable storage + time_low = timestamp & 0xffffffff + time_mid = (timestamp >> 32) & 0xffff + time_hi_version = (timestamp >> 48) & 0x0fff + clock_seq_low = clock_seq & 0xff + clock_seq_hi_variant = (clock_seq >> 8) & 0x3f if node is None: node = getnode() return UUID(fields=(time_low, time_mid, time_hi_version, Modified: python/branches/p3yk/Lib/xdrlib.py ============================================================================== --- python/branches/p3yk/Lib/xdrlib.py (original) +++ python/branches/p3yk/Lib/xdrlib.py Mon Jan 15 17:59:06 2007 @@ -61,8 +61,8 @@ else: self.__buf.write('\0\0\0\0') def pack_uhyper(self, x): - self.pack_uint(x>>32 & 0xffffffffL) - self.pack_uint(x & 0xffffffffL) + self.pack_uint(x>>32 & 0xffffffff) + self.pack_uint(x & 0xffffffff) pack_hyper = pack_uhyper @@ -164,12 +164,12 @@ def unpack_uhyper(self): hi = self.unpack_uint() lo = self.unpack_uint() - return long(hi)<<32 | lo + return int(hi)<<32 | lo def unpack_hyper(self): x = self.unpack_uhyper() - if x >= 0x8000000000000000L: - x = x - 0x10000000000000000L + if x >= 0x8000000000000000: + x = x - 0x10000000000000000 return x def unpack_float(self): Modified: python/branches/p3yk/Lib/xml/dom/NodeFilter.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/NodeFilter.py (original) +++ python/branches/p3yk/Lib/xml/dom/NodeFilter.py Mon Jan 15 17:59:06 2007 @@ -9,7 +9,7 @@ FILTER_REJECT = 2 FILTER_SKIP = 3 - SHOW_ALL = 0xFFFFFFFFL + SHOW_ALL = 0xFFFFFFFF SHOW_ELEMENT = 0x00000001 SHOW_ATTRIBUTE = 0x00000002 SHOW_TEXT = 0x00000004 Modified: python/branches/p3yk/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk/Lib/xmlrpclib.py (original) +++ python/branches/p3yk/Lib/xmlrpclib.py Mon Jan 15 17:59:06 2007 @@ -183,8 +183,8 @@ __version__ = "1.0.1" # xmlrpc integer limits -MAXINT = 2L**31-1 -MININT = -2L**31 +MAXINT = 2**31-1 +MININT = -2**31 # -------------------------------------------------------------------- # Error constants (from Dan Libby's specification at Modified: python/branches/p3yk/Lib/zipfile.py ============================================================================== --- python/branches/p3yk/Lib/zipfile.py (original) +++ python/branches/p3yk/Lib/zipfile.py Mon Jan 15 17:59:06 2007 @@ -280,15 +280,15 @@ idx = 0 # ZIP64 extension (large files and/or large archives) - if self.file_size == -1 or self.file_size == 0xFFFFFFFFL: + if self.file_size == -1 or self.file_size == 0xFFFFFFFF: self.file_size = counts[idx] idx += 1 - if self.compress_size == -1 or self.compress_size == 0xFFFFFFFFL: + if self.compress_size == -1 or self.compress_size == 0xFFFFFFFF: self.compress_size = counts[idx] idx += 1 - if self.header_offset == -1 or self.header_offset == 0xffffffffL: + if self.header_offset == -1 or self.header_offset == 0xffffffff: old = self.header_offset self.header_offset = counts[idx] idx+=1 @@ -548,7 +548,7 @@ while arcname[0] in (os.sep, os.altsep): arcname = arcname[1:] zinfo = ZipInfo(arcname, date_time) - zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes + zinfo.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: Modified: python/branches/p3yk/Parser/tokenizer.c ============================================================================== --- python/branches/p3yk/Parser/tokenizer.c (original) +++ python/branches/p3yk/Parser/tokenizer.c Mon Jan 15 17:59:06 2007 @@ -1323,17 +1323,13 @@ return ERRORTOKEN; } } - if (c == 'l' || c == 'L') - c = tok_nextc(tok); } else { /* Decimal */ do { c = tok_nextc(tok); } while (isdigit(c)); - if (c == 'l' || c == 'L') - c = tok_nextc(tok); - else { + { /* Accept floating point numbers. */ if (c == '.') { fraction: Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Mon Jan 15 17:59:06 2007 @@ -2126,7 +2126,6 @@ SETBUILTIN("property", &PyProperty_Type); SETBUILTIN("int", &PyLong_Type); SETBUILTIN("list", &PyList_Type); - SETBUILTIN("long", &PyLong_Type); SETBUILTIN("object", &PyBaseObject_Type); SETBUILTIN("reversed", &PyReversed_Type); SETBUILTIN("set", &PySet_Type); From python-3000-checkins at python.org Mon Jan 15 18:02:52 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 15 Jan 2007 18:02:52 +0100 (CET) Subject: [Python-3000-checkins] r53453 - python/branches/p3yk/setup.py Message-ID: <20070115170252.30CBD1E4005@bag.python.org> Author: guido.van.rossum Date: Mon Jan 15 18:02:51 2007 New Revision: 53453 Modified: python/branches/p3yk/setup.py Log: Fix L-suffixed literal straggler. Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Mon Jan 15 18:02:51 2007 @@ -461,7 +461,7 @@ exts.append( Extension('audioop', ['audioop.c']) ) # Disabled on 64-bit platforms - if sys.maxint != 9223372036854775807L: + if sys.maxint != 9223372036854775807: # Operations on images exts.append( Extension('imageop', ['imageop.c']) ) # Read SGI RGB image files (but coded portably) From python-3000-checkins at python.org Tue Jan 30 00:43:38 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 30 Jan 2007 00:43:38 +0100 (CET) Subject: [Python-3000-checkins] r53598 - python/branches/p3yk/Python/ceval.c Message-ID: <20070129234338.CB48A1E4009@bag.python.org> Author: brett.cannon Date: Tue Jan 30 00:43:38 2007 New Revision: 53598 Modified: python/branches/p3yk/Python/ceval.c Log: Fix minor grammar typo. Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Tue Jan 30 00:43:38 2007 @@ -2772,7 +2772,7 @@ } PyErr_Format(PyExc_TypeError, "%.200s() needs " - "keyword only argument %s", + "keyword-only argument %s", PyString_AsString(co->co_name), PyString_AsString(name)); goto fail; From python-3000-checkins at python.org Tue Jan 30 00:44:37 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 30 Jan 2007 00:44:37 +0100 (CET) Subject: [Python-3000-checkins] r53599 - python/branches/p3yk/Misc/NEWS Message-ID: <20070129234437.9BE4A1E4009@bag.python.org> Author: brett.cannon Date: Tue Jan 30 00:44:37 2007 New Revision: 53599 Modified: python/branches/p3yk/Misc/NEWS Log: Add missing entry for PEP 3102 (keyword-only arguments). Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Jan 30 00:44:37 2007 @@ -36,6 +36,8 @@ Core and Builtins ----------------- +- PEP 3102: keyword-only arguments. + - Int/Long unification is halfway complete. The 'long' built-in type hasn't been removed yet, and literals with trailing 'L' or 'l' are still recognized. Performance may be sub-optimal. From python-3000-checkins at python.org Tue Jan 30 01:00:40 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 30 Jan 2007 01:00:40 +0100 (CET) Subject: [Python-3000-checkins] r53600 - python/branches/p3yk/Misc/NEWS Message-ID: <20070130000040.88D001E4009@bag.python.org> Author: guido.van.rossum Date: Tue Jan 30 01:00:40 2007 New Revision: 53600 Modified: python/branches/p3yk/Misc/NEWS Log: Update news about int/long unification. Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Jan 30 01:00:40 2007 @@ -38,9 +38,9 @@ - PEP 3102: keyword-only arguments. -- Int/Long unification is halfway complete. The 'long' built-in type - hasn't been removed yet, and literals with trailing 'L' or 'l' are - still recognized. Performance may be sub-optimal. +- Int/Long unification is mostly complete. The 'long' built-in type + and literals with trailing 'L' or 'l' have been removed. + Performance may be sub-optimal (haven't really benchmarked). - 'except E, V' must now be spelled as 'except E as V' and deletes V at the end of the except clause; V must be a simple name.